求助 关于Django ,AttributeError:'Topic' object has no attribute 'owner'

python编程入门到实践第十九章中的问题

浏览器报错信息如下

图片说明

关于我的views.py 的代码如下

from django.shortcuts import render
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required

from .models import Topic, Entry
from .forms import TopicForm, EntryForm



# Create your views here.
def index(request):
    '''
    学习笔记的主页
    :return:
    '''
    return render(request,'learning_logs/index.html')
def topics(request):
    """Show all topics."""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)




@login_required
def new_topic(request):
    '''添加新主题'''
    if request.method != 'POST':
        form = TopicForm()
    else:
        form = TopicForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))
    context = {'form':form}
    return render(request,'learning_logs/new_topic.html',context)


def edit_entry(request, entry_id):
    """Edit an existing entry."""
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    if topic.owner != request.user:
        raise Http404

    if request.method != 'POST':
        # Initial request; pre-fill form with the current entry.
        form = EntryForm(instance=entry)
    else:
        # POST data submitted; process data.
        form = EntryForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',
                                                args=[topic.id]))

    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'learning_logs/edit_entry.html', context)


def topic(request, topic_id):
    """Show a single topic, and all its entries."""
    topic = Topic.objects.get(id = topic_id)
    # Make sure the topic belongs to the current user.
    if topic.owner != request.user:
        raise Http404

    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)


def new_entry(request, topic_id):
    """Add a new entry for a particular topic."""
    topic = Topic.objects.get(id=topic_id)
    if topic.owner != request.user:
        raise Http404

    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = EntryForm()
    else:
        # POST data submitted; process data.
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',
                                                args=[topic_id]))

    context = {'topic': topic, 'form': form}
    return render(request, 'learning_logs/new_entry.html', context)




2个回答

根据页面的报错信息,报错的地方应该是 if topic.owner != request.user: 这一行,报错的原因是 topic 没有owner属性,因为没有具体的表结构,无法做出进一步推断,你可以自己调试下,目测很简单

调试看一下你的对象的数据类型

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
求助:AttributeError: type object 'Topic' has no attribute 'object'
python新手,求助个有关django的问题 django版本:2.1.5 python版本:3.6.0 问题如下: 项目路径\ learning_log 应用路径\learning_logs \learning_log\urls代码: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('learning_logs.urls')) ] \learning_logs.urls代码: from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ path('',views.index,name='index'), path('topics/',views.topics,name='topics'), ] \learning_logs.views代码: from django.shortcuts import render from .models import Topic,Entry def index(request): return render(request,'learning_logs/index.html') def topics(request): a = Topic.object.order_by('date_added') context = {'topics':a} return render(request,'learning_logs/topics.html',context) \learning_logs.models代码: from django.db import models class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): if len(self.text) < 50: return self.text else: return self.text[:50] + '...' 运行网页后: http://127.0.0.1:8000/ 显示如下,正常 Learning Log - Topics Learning Log helps you keep track of your learning, for any topic you're learning about. 运行 http://127.0.0.1:8000/Topic/ 后报错如下: AttributeError at /topics/ type object 'Topic' has no attribute 'object'
<AttributeError: 'str' object has no attribute 'decode'>,跪求大神解答。
``` from django.db import models # Create your models here. class Grades(models.Model): gname = models.CharField(max_length=20) gdate = models.DateTimeField() ggirlnum = models.IntegerField() gboynum = models.IntegerField() isDelete = models.BooleanField(default=False) class Students(models.Model): sname = models.CharField(max_length=20) sgender = models.BooleanField(default=True) sage = models.IntegerField() scontend = models.CharField(max_length=20) isDelete = models.BooleanField(default=False) # 关联外键 sgrade = models.ForeignKey(Grades, on_delete=models.CASCADE) ``` Django2.2, python3.7, 执行数据库迁移<python manage.py makemigrations>时报错,<AttributeError: 'str' object has no attribute 'decode'>
django OperationalError:no such table问题
admin界面有这些table ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566306109_375484.png) 但任何一张表打开都是operationalerror ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566306079_894027.png) 我的数据库 ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566306954_557961.png) 文件路径 ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566307025_838507.png) 运行过如下代码 ``` python manage.py makemigrations python manage.py migrate ``` ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566306389_902239.png) ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566306436_170968.png) 我觉得应该是运行成功了的 以下这些我找到的解决方法都试过了没有用 ``` python manage.py syncdb class Meta: managed = True python manage.py makemigrations HERBS python manage.py migrate HERBS ``` admin.py ``` from django.contrib import admin from HERBS.models import Herbs,DISEASE,Chemicals,CASID,TARGET class HerbAdmin(admin.ModelAdmin): search_fields = ('ID','NAME') #可进行查询的字段 list_filter = ('NAME','Function') #可进行筛选的字段 list_display = ('ID','NAME','Function') #需要在后台显示出来的字段 class DISEASEAdmin(admin.ModelAdmin): search_fields = ('Disease','MolID') list_filter = ('Disease','MolID') list_display = ('Disease','MolID') class ChemicalsAdmin(admin.ModelAdmin): search_fields = ('ChemName','MolID','PubChemcid','ChineseName','Smiles') list_filter = ('MolID','ChemName') list_display = ('ChemName','MolID','PubChemcid','HID','ChineseName','MF','MW','Smiles') class CASIDAdmin(admin.ModelAdmin): search_fields = ('ID','MolID') list_display = ('ID','MolID') class TARGETAdmin(admin.ModelAdmin): search_fields = ('MolID','Target') list_display = ('MolID','Target') # Register your models here. admin.site.register(Herbs,HerbAdmin) admin.site.register(DISEASE,DISEASEAdmin) admin.site.register(CASID,CASIDAdmin) admin.site.register(Chemicals,ChemicalsAdmin) admin.site.register(TARGET,TARGETAdmin) ``` models.py ``` from django.db import models #Create your models here. class Herbs(models.Model): ID = models.DecimalField(max_digits=5,decimal_places=0) NAME = models.TextField(max_length=50,primary_key=True) Function = models.TextField(max_length=500,null=True) class DISEASE(models.Model): Disease = models.TextField(max_length=100) MolID = models.TextField(max_length=50) class Chemicals(models.Model): ChemName = models.TextField(max_length=50) MolID = models.TextField(max_length=50) PubChemcid = models.DecimalField(max_digits=10,decimal_places=0) HID = models.DecimalField(max_digits=10,decimal_places=0) ChineseName = models.TextField(max_length=50) MF = models.TextField(max_length=50) MW = models.DecimalField(max_digits=20,decimal_places=2) Smiles = models.TextField(max_length=500) class CASID(models.Model): ID = models.TextField(max_length=50) MolID = models.TextField(max_length=50) class TARGET(models.Model): Target = models.TextField(max_length=100) MolID = models.TextField(max_length=50) class Meta: managed = True ```
django operationalerror:no such table问题
![图片说明](https://img-ask.csdn.net/upload/201908/20/1566309101_99545.png) 数据库 ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566309118_854760.png) 文件路径 ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566309159_756269.png) admin界面 ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566309201_944852.png) 运行过如下代码并且成功了 ``` python manage.py makemigrations python manage.py migrate ``` ![图片说明](https://img-ask.csdn.net/upload/201908/20/1566309301_942422.png)![图片说明](https://img-ask.csdn.net/upload/201908/20/1566309309_56608.png) 尝试过如下解决方案 ``` python manage.py makemigrations HERBS python manage.py migrate HERBS class Meta: managed = True ``` admin.py ``` from django.contrib import admin from HERBS.models import Herbs,DISEASE,Chemicals,CASID,TARGET class HerbAdmin(admin.ModelAdmin): search_fields = ('ID','NAME') list_filter = ('NAME','Function') list_display = ('ID','NAME','Function') class DISEASEAdmin(admin.ModelAdmin): search_fields = ('Disease','MolID') list_filter = ('Disease','MolID') list_display = ('Disease','MolID') class ChemicalsAdmin(admin.ModelAdmin): search_fields = ('ChemName','MolID','PubChemcid','ChineseName','Smiles') list_filter = ('MolID','ChemName') list_display = ('ChemName','MolID','PubChemcid','HID','ChineseName','MF','MW','Smiles') class CASIDAdmin(admin.ModelAdmin): search_fields = ('ID','MolID') list_display = ('ID','MolID') class TARGETAdmin(admin.ModelAdmin): search_fields = ('MolID','Target') list_display = ('MolID','Target') # Register your models here. admin.site.register(Herbs,HerbAdmin) admin.site.register(DISEASE,DISEASEAdmin) admin.site.register(CASID,CASIDAdmin) admin.site.register(Chemicals,ChemicalsAdmin) admin.site.register(TARGET,TARGETAdmin) ``` models.py ``` from django.db import models #Create your models here. class Herbs(models.Model): ID = models.DecimalField(max_digits=5,decimal_places=0) NAME = models.TextField(max_length=50,primary_key=True) Function = models.TextField(max_length=500,null=True) class DISEASE(models.Model): Disease = models.TextField(max_length=100) MolID = models.TextField(max_length=50) class Chemicals(models.Model): ChemName = models.TextField(max_length=50) MolID = models.TextField(max_length=50) PubChemcid = models.DecimalField(max_digits=10,decimal_places=0) HID = models.DecimalField(max_digits=10,decimal_places=0) ChineseName = models.TextField(max_length=50) MF = models.TextField(max_length=50) MW = models.DecimalField(max_digits=20,decimal_places=2) Smiles = models.TextField(max_length=500) class CASID(models.Model): ID = models.TextField(max_length=50) MolID = models.TextField(max_length=50) class TARGET(models.Model): Target = models.TextField(max_length=100) MolID = models.TextField(max_length=50) class Meta: managed = True ```
<python从入门到实践>19章书中只给topic设定了owner,但是entry没有出现了报错django.db.utils.OperationalError: no such column: learning_logs_entry.owner_id
我用改topic的方法改了new_entry,也没有行通。 views.py ``` from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic,Entry from .forms import TopicForm,EntryForm from django.contrib.auth.decorators import login_required def index(request): #学习笔记的主页 return render(request,'learning_logs/index.html') @login_required def topics(request): #显示所有的主题 topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics':topics} return render(request,'learning_logs/topics.html',context) @login_required def topic(request,topic_id): #显示单个主题及其所有的项目 topic = Topic.objects.filter(owner=request.user).get(id = topic_id) #确认请求的主题属于当前用户 if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic':topic,'entries':entries} return render(request,'learning_logs/topic.html',context) @login_required def new_topic(request): '''添加新主题''' if request.method != 'POST': #未提交数据 创建一个新表单 form = TopicForm() else: #POST提交的数据 对数据进行处理 form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form':form} return render(request, 'learning_logs/new_topic.html',context) @login_required def new_entry(request,topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic,'form':form} return render(request, 'learning_logs/new_entry.html',context) @login_required def edit_entry(request,entry_id): '''编辑现有的条目''' entry = Entry.objects.get(id=entry_id) topic = entry.topic if topic.owner != request.user: raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: #POST提交的数据,对数据进行处理 form = EntryForm(instance=entry,data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry':entry, 'topic':topic, 'form':form } return render(requ ``` models.py ``` from django.db import models from django.contrib.auth.models import User class Topic(models.Model): #用户学习主题 text = models.CharField(max_length= 200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): #返回模型的字符串表示 return self.text class Entry(models.Model): #学到的有关某个主题的具体知识 topic = models.ForeignKey(Topic,on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add= True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class meta: verbose_name_plural ='entries' def __str__(self): #返回模型的字符串表示 if len(self.text) >= 50: return self.text[:50] + '...' else: return self.text[:] ```
django File "/home/tarena/.local/lib/python3.5/site-packages/django/utils/crypto.py", line 6, in <module> import secrets ImportError: No module named 'secrets'
提起django服务:python3 manage.py runserver时,显示import secrets ImportError ```python File "/home/tarena/.local/lib/python3.5/site-packages/django/utils/crypto.py", line 6, in <module> import secrets ImportError: No module named 'secrets' ``` 请问有谁知道怎么解决a
pycharm创建Django,出现如下报错,求解
AttributeError: module 'pip' has no attribute 'main'
Django实现Web应用显示单个主题时出现错误: 'function' object has no attribute 'entry_set'
1。 实现显示单个主题时,点击单个主题出现以下错误 **'function' object has no attribute 'entry_set'** Request Method: GET Request URL: http://localhost:8000/topics/(%3FP1%5Cd+)/ Django Version: 2.1.4 Exception Type: AttributeError **Exception Value: 'function' object has no attribute 'entry_set'** Exception Location: D:\Python_env\learning_log\learning_logs\views.py in topic, line 22 Python Executable: D:\Python_env\learning_log\11_env\Scripts\python.exe 2. 源代码如下 ``` from django.shortcuts import render from .models import Topic # Create your views here. def index(request): return render(request, 'learning_logs/index.html') def topics(request): # 显示所有的主题 topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """显示单个主题及其所有的条目""" topic = Topic.objects.get(id = topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) ``` 好像问题是出在entries = topic.entry_set.order_by('-date_added') entry_set没有定义吗?
win7安装django-cms出现的问题
D:\untitled>python Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.get_version() '1.8.7' >>> AttributeError: 'Settings' object has no attribute 'SITE_ID'
Django报错:django.server:"GET /favicon.ico HTTP/1.1" 500 59,该如何解决?
搭建完HttpRunnerManager环境后进行接口的调试,运行用例时页面报错: A server error occurred. Please contact the administrator. ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565747464_929466.jpg) 返回用例页面收到提示: ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565747577_116158.jpg) 点击确定后页面依旧是500报错,和图一相同,刷新页面也无济于事 ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565747927_436972.jpg) dos命令窗口关于django服务的报错: ![图片说明](https://img-ask.csdn.net/upload/201908/14/1565748112_123790.jpg) 分别查询了前台和后台的错误解决办法,发现前台错误和其他人的原因不同,后台django的错误实在搜不到详细的内容,本人也是初次接触这套框架,对django的报错没有头绪,希望有大佬帮忙分析一下原因所在,万分感谢。
Django已有的model表新增字段,执行migrate报错:django.db.utils.DatabaseError:ORA-00955: name is already used by an existing object,出现重名是啥情况。。。
Django已有的model表新增字段,执行migrate报错:django.db.utils.DatabaseError:ORA-00955: name is already used by an existing object,出现重名是啥情况。。。
问个有关django+heroku的问题
``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/learning_logs/models.py", line 7, in <module> class Topic(models.Model): File "/app/learning_logs/models.py", line 8, in Topic choices=Help().choices() File "/app/learning_logs/help.py", line 9, in choices for user in users: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ``` 在heroku bash操作makemigrations,migrate中出现的错误 在本地用这些没问题 settings.py ``` """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o47!#$sbu_&=)pnbk63ra!hjbx@+pc=2j42cf(&mx82&hs&ph_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my app 'learning_logs', 'users', #other app 'bootstrap3', ) MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = '/users/login/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if os.getenv('DATABASE_URL') is not None: import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['stark-anchorage-08076.herokuapp.com'] DEBUG = False BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) ``` views.py ``` from django.shortcuts import render from .models import Topic, Entry, Root, Suf_Pre_fix from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from .forms import TopicForm, EntryForm, RootForm from django.contrib.auth.decorators import login_required from .help import Help from django.contrib.auth.models import User # Create your views here. def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.edit_able = request.POST.getlist("edit_able") new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.edit_able = request.POST.getlist("edit_able") new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic, 'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_entry.html', context) @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if not Help().check_user(request.user,entry.edit_able) or not Help().check_user(request.user,topic.edit_able): raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): edit_entry = form.save(commit=False) edit_entry.edit_able = request.POST.getlist("edit_able") edit_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form ,'users':Help().users()} return render(request, 'learning_logs/edit_entry.html', context) @login_required def roots(request): roots = Root.objects.order_by('date_added') context = {'roots': roots} return render(request, 'learning_logs/roots.html', context) def root(request, root_id): root = Root.objects.get(id=root_id) things = root.things.order_by('-date_added') context = {'root':root, 'things':things} return render(request, 'learning_logs/root.html', context) ``` help.py ``` from django.contrib.auth.models import User class Help(): def __init__(self): pass def choices(self): users=User.objects.all() choices=[] a=1 for user in users: choices.append((a,str(user))) a+=1 return choices def check_user(self,user,users): try: str(users).index(str(user)) except: return False else: return True def users(self): users=[] for user in User.objects.all(): users.append(str(user)) return users def test_list(self,list1): for item in list1: print(type(item)) def test_word(self,item): print(item,type(item)) ```
Pycharm 创建Django出现的问题
通过pycharm 创建 Django 出现 AttributeError: module 'pip' has no attribute 'main'的错误 ![图片说明](https://img-ask.csdn.net/upload/201910/15/1571141576_843540.png) 通过百度 尝试了第一种方法 pip降级 。 第二种方法 修改安装pycharm软件的目录packaging_tool.py 文件,def do_install(pkgs): try: #import pip try: from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main(['install'] + pkgs) def do_uninstall(pkgs): try: #import pip try: from pip._internal import main except Exception: from pip import main except ImportError: error_no_pip() return main(['uninstall', '-y'] + pkgs) 以上方法都没有用,解决方法链接https://blog.csdn.net/u010042585/article/details/80447109 修改完后出现这样的错误 ![图片说明](https://img-ask.csdn.net/upload/201910/15/1571141765_705180.png) 求解决啊,光是这个我都弄了3个小时了。还不行,作为初学者,恳求各位大大解决
django models实现entry类遇到诡异问题?python
我在看python变成从入门到实践这本书 18.2内容,django的learning_log小项目里面。 实现在models中实现entry类 我的代码如下,完全和书上一模一样 class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): return self.text[:50]+"..." ``` ``` 但是我发现一个诡异问题,就是不管我怎么改最后的 def __str__(self): return self.text[:50]+"..." 这个根本不起作用,并不只返回50字符以内的内容+省略号,而是返回完整内容。 而且我怎么修改都没用,哪怕我改成return "hahaha "都没用!!!!就算我把整个__str__函数删掉,他还能返回完整的所有内容。可是我改topic类return的内容却可以起作用,实在是想吐了,求求各位大神救命!!!
问个有关python+django+heroku的问题
``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/learning_logs/models.py", line 7, in <module> class Topic(models.Model): File "/app/learning_logs/models.py", line 8, in Topic choices=Help().choices() File "/app/learning_logs/help.py", line 9, in choices for user in users: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ``` 在heroku bash操作makemigrations,migrate中出现的错误 在本地用这些没问题 settings.py ``` """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o47!#$sbu_&=)pnbk63ra!hjbx@+pc=2j42cf(&mx82&hs&ph_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my app 'learning_logs', 'users', #other app 'bootstrap3', ) MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = '/users/login/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if os.getenv('DATABASE_URL') is not None: import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['stark-anchorage-08076.herokuapp.com'] DEBUG = False BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) ``` views.py ``` from django.shortcuts import render from .models import Topic, Entry, Root, Suf_Pre_fix from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from .forms import TopicForm, EntryForm, RootForm from django.contrib.auth.decorators import login_required from .help import Help from django.contrib.auth.models import User # Create your views here. def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.edit_able = request.POST.getlist("edit_able") new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.edit_able = request.POST.getlist("edit_able") new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic, 'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_entry.html', context) @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if not Help().check_user(request.user,entry.edit_able) or not Help().check_user(request.user,topic.edit_able): raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): edit_entry = form.save(commit=False) edit_entry.edit_able = request.POST.getlist("edit_able") edit_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form ,'users':Help().users()} return render(request, 'learning_logs/edit_entry.html', context) @login_required def roots(request): roots = Root.objects.order_by('date_added') context = {'roots': roots} return render(request, 'learning_logs/roots.html', context) def root(request, root_id): root = Root.objects.get(id=root_id) things = root.things.order_by('-date_added') context = {'root':root, 'things':things} return render(request, 'learning_logs/root.html', context) ``` help.py ``` from django.contrib.auth.models import User class Help(): def __init__(self): pass def choices(self): users=User.objects.all() choices=[] a=1 for user in users: choices.append((a,str(user))) a+=1 return choices def check_user(self,user,users): try: str(users).index(str(user)) except: return False else: return True def users(self): users=[] for user in User.objects.all(): users.append(str(user)) return users def test_list(self,list1): for item in list1: print(type(item)) def test_word(self,item): print(item,type(item)) ```
Django后台管理新建post保存出错
报错如下 TypeError at /admin/blog/post/add/ object of type 'int' has no len() Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog/post/add/ Django Version: 3.0.1 Exception Type: TypeError Exception Value: object of type 'int' has no len() Exception Location: C:\Users\Administrator\Desktop\website\djangoenv\lib\site-packages\django\forms\models.py in has_changed, line 1354 Python Executable: C:\Users\Administrator\Desktop\website\djangoenv\Scripts\python.exe Python Version: 3.6.5 Python Path: ['C:\\Users\\Administrator\\Desktop\\website\\blog2020', 'C:\\Users\\Administrator\\Desktop\\website\\djangoenv\\Scripts\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\Administrator\\Desktop\\website\\djangoenv', 'C:\\Users\\Administrator\\Desktop\\website\\djangoenv\\lib\\site-packages'] Server time: 星期一, 6 一月 2020 15:56:18 +0800 源代码 def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in self.prepare_value(initial)} data_set = {str(value) for value in data} return data_set != initial_set
Django开发网站时出错。
本人技术渣一枚,这几天刚入坑的Django,按照网上的教程一步步来的,到这里的时候不知道为什么出错了,求大神解答一下 ![图片说明](https://img-ask.csdn.net/upload/202002/18/1582037665_342899.png) 这里是我的new_entry文件代码 ![图片说明](https://img-ask.csdn.net/upload/202002/18/1582037695_149108.png)
pycharm创建django项目
,用pycharm创建django项目时出现该错误提示,error creating django application:could not find django installation under c:\python34\python.exe。 注:在cmd下能成功创建django项目,得到it worked页面 谢谢。
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
Python 植物大战僵尸代码实现(2):植物卡片选择和种植
这篇文章要介绍的是: - 上方植物卡片栏的实现。 - 点击植物卡片,鼠标切换为植物图片。 - 鼠标移动时,判断当前在哪个方格中,并显示半透明的植物作为提示。
死磕YOLO系列,YOLOv1 的大脑、躯干和手脚
YOLO 是我非常喜欢的目标检测算法,堪称工业级的目标检测,能够达到实时的要求,它帮我解决了许多实际问题。 这就是 YOLO 的目标检测效果。它定位了图像中物体的位置,当然,也能预测物体的类别。 之前我有写博文介绍过它,但是每次重新读它的论文,我都有新的收获,为此我准备写一个系列的文章来详尽分析它。这是第一篇,从它的起始 YOLOv1 讲起。 YOLOv1 的论文地址:https://www.c
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
记一次腾讯面试:进程之间究竟有哪些通信方式?如何通信? ---- 告别死记硬背
有一次面试的时候,被问到进程之间有哪些通信方式,不过由于之前没深入思考且整理过,说的并不好。想必大家也都知道进程有哪些通信方式,可是我猜很多人都是靠着”背“来记忆的,所以今天的这篇文章,讲给大家详细着讲解他们是如何通信的,让大家尽量能够理解他们之间的区别、优缺点等,这样的话,以后面试官让你举例子,你也能够顺手拈来。 1、管道 我们来看一条 Linux 的语句 netstat -tulnp | gr...
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片
网络(8)-HTTP、Socket、TCP、UDP的区别和联系
TCP/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据。 一、TCP与UDP的不同 1. 是否需要建立连接。 UDP在传送数据之前不需要先建立连接;TCP则提供面向连接的服务; 2. 是否需要给出确认 对方的传输层在收到UDP报文后,不需要给出任何确认,而 TCP需要给出确认报文,要提供可靠的、面向连接的传输服务。 3.虽然UDP不提供可靠交...
简明易理解的@SpringBootApplication注解源码解析(包含面试提问)
欢迎关注文章系列 ,关注我 《提升能力,涨薪可待》 《面试知识,工作可待》 《实战演练,拒绝996》 欢迎关注我博客,原创技术文章第一时间推出 也欢迎关注公 众 号【Ccww笔记】,同时推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《提升能力,涨薪可待篇》- @SpringBootApplication注解源码解析 一、@SpringBootApplication 的作用是什
防劝退!数据结构和算法难理解?可视化动画带你轻松透彻理解!
大家好,我是 Rocky0429,一个连数据结构和算法都不会的蒟蒻… 学过数据结构和算法的都知道这玩意儿不好学,没学过的经常听到这样的说法还没学就觉得难,其实难吗?真难! 难在哪呢?当年我还是个小蒟蒻,初学数据结构和算法的时候,在忍着枯燥看完定义原理,之后想实现的时候,觉得它们的过程真的是七拐八绕,及其难受。 在简单的链表、栈和队列这些我还能靠着在草稿上写写画画理解过程,但是到了数论、图...
西游记团队中如果需要裁掉一个人,会先裁掉谁?
2019年互联网寒冬,大批企业开始裁员,下图是网上流传的一张截图: 裁员不可避免,那如何才能做到不管大环境如何变化,自身不受影响呢? 我们先来看一个有意思的故事,如果西游记取经团队需要裁员一名,会裁掉谁呢,为什么? 西游记团队组成: 1.唐僧 作为团队teamleader,有很坚韧的品性和极高的原则性,不达目的不罢休,遇到任何问题,都没有退缩过,又很得上司支持和赏识(直接得到唐太宗的任命,既给
开挂的人生!那些当选院士,又是ACM/IEEE 双料Fellow的华人学者们
昨日,2019年两院院士正式官宣,一时间抢占了各大媒体头条。 朋友圈也是一片沸腾,奔走相告,赶脚比自己中了大奖还嗨皮! 谁叫咱家导师就是这么厉害呢!!! 而就在最近,新一年度的IEEE/ACM Fellow也将正式公布。 作为学术届的顶级荣誉,不自然地就会将院士与Fellow作比较,到底哪个含金量更高呢? 学术君认为,同样是专业机构对学者的认可,考量标准不一,自然不能一概而论。 但...
聊聊C语言和指针的本质
坐着绿皮车上海到杭州,24块钱,很宽敞,在火车上非正式地聊几句。 很多编程语言都以 “没有指针” 作为自己的优势来宣传,然而,对于C语言,指针却是与生俱来的。 那么,什么是指针,为什么大家都想避开指针。 很简单, 指针就是地址,当一个地址作为一个变量存在时,它就被叫做指针,该变量的类型,自然就是指针类型。 指针的作用就是,给出一个指针,取出该指针指向地址处的值。为了理解本质,我们从计算机模型说起...
Python语言高频重点汇总
Python语言高频重点汇总 GitHub面试宝典仓库——点这里跳转 文章目录Python语言高频重点汇总**GitHub面试宝典仓库——点这里跳转**1. 函数-传参2. 元类3. @staticmethod和@classmethod两个装饰器4. 类属性和实例属性5. Python的自省6. 列表、集合、字典推导式7. Python中单下划线和双下划线8. 格式化字符串中的%和format9.
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
代码详解:如何用Python快速制作美观、炫酷且有深度的图表
全文共12231字,预计学习时长35分钟生活阶梯(幸福指数)与人均GDP(金钱)正相关的正则图本文将探讨三种用Python可视化数据的不同方法。以可视化《2019年世界幸福报告》的数据为例,本文用Gapminder和Wikipedia的信息丰富了《世界幸福报告》数据,以探索新的数据关系和可视化方法。《世界幸福报告》试图回答世界范围内影响幸福的因素。报告根据对“坎特里尔阶梯问题”的回答来确定幸...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
(经验分享)作为一名普通本科计算机专业学生,我大学四年到底走了多少弯路
今年正式步入了大四,离毕业也只剩半年多的时间,回想一下大学四年,感觉自己走了不少弯路,今天就来分享一下自己大学的学习经历,也希望其他人能不要走我走错的路。 (一)初进校园 刚进入大学的时候自己完全就相信了高中老师的话:“进入大学你们就轻松了”。因此在大一的时候自己学习的激情早就被抛地一干二净,每天不是在寝室里玩游戏就是出门游玩,不过好在自己大学时买的第一台笔记本性能并不是很好,也没让我彻底沉...
如何写一篇技术博客,谈谈我的看法
前言 只有光头才能变强。 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y 我一直推崇学技术可以写技术博客去沉淀自己的知识,因为知识点实在是太多太多了,通过自己的博客可以帮助自己快速回顾自己学过的东西。 我最开始的时候也是只记笔记,认为自己能看得懂就好。但如果想验证自己是不是懂了,可以写成技术博客。在写技术博客的...
字节跳动面试官这样问消息队列:分布式事务、重复消费、顺序消费,我整理了一下
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
面试还搞不懂redis,快看看这40道面试题(含答案和思维导图)
Redis 面试题 1、什么是 Redis?. 2、Redis 的数据类型? 3、使用 Redis 有哪些好处? 4、Redis 相比 Memcached 有哪些优势? 5、Memcache 与 Redis 的区别都有哪些? 6、Redis 是单进程单线程的? 7、一个字符串类型的值能存储最大容量是多少? 8、Redis 的持久化机制是什么?各自的优缺点? 9、Redis 常见性...
大学四年自学走来,这些珍藏的「实用工具/学习网站」我全贡献出来了
知乎高赞:文中列举了互联网一线大厂程序员都在用的工具集合,涉及面非常广,小白和老手都可以进来看看,或许有新收获。
互联网公司的裁员,能玩出多少种花样?
裁员,也是一门学问,可谓博大精深!以下,是互联网公司的裁员的多种方法:-正文开始-135岁+不予续签的理由:千禧一代网感更强。95后不予通过试用期的理由:已婚已育员工更有责任心。2通知接下来要过苦日子,让一部分不肯同甘共苦的员工自己走人,以“兄弟”和“非兄弟”来区别员工。3强制996。员工如果平衡不了工作和家庭,可在离婚或离职里二选一。4不布置任何工作,但下班前必须提交千字工作日报。5不给活干+...
【设计模式】单例模式的八种写法分析
网上泛滥流传单例模式的写法种类,有说7种的,也有说6种的,当然也不排除说5种的,他们说的有错吗?其实没有对与错,刨根问底,写法终究是写法,其本质精髓大体一致!因此完全没必要去追究写法的多少,有这个时间还不如跟着宜春去网吧偷耳机、去田里抓青蛙得了,一天天的....
《面试宝典》:检验是否为合格的初中级程序员的面试知识点,你都知道了吗?查漏补缺
欢迎关注文章系列,一起学习 《提升能力,涨薪可待篇》 《面试知识,工作可待篇》 《实战演练,拒绝996篇》 也欢迎关注公 众 号【Ccww笔记】,原创技术文章第一时间推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《面试知识,工作可待篇》-Java笔试面试基础知识大全 前言 是不是感觉找工作面试是那么难呢? 在找工作面试应在学习的基础进行总结面试知识点,工作也指日可待,欢...
关于研发效能提升的思考
研发效能提升是最近比较热门的一个话题,本人根据这几年的工作心得,做了一些思考总结,由于个人深度有限,暂且抛转引入。 三要素 任何生产力的提升都离不开这三个因素:人、流程和工具,少了其中任何一个因素都无法实现。 人,即思想,也就是古人说的“道”,道不同不相为谋,是制高点,也是高层建筑的基石。 流程,即方法,也是古人说的“法”。研发效能的提升,也就是要提高投入产出比,既要增加产出,也要减...
微博推荐算法简述
在介绍微博推荐算法之前,我们先聊一聊推荐系统和推荐算法。有这样一些问题:推荐系统适用哪些场景?用来解决什么问题、具有怎样的价值?效果如何衡量? 推荐系统诞生很早,但真正被大家所重视,缘起于以”facebook”为代表的社会化网络的兴起和以“淘宝“为代表的电商的繁荣,”选择“的时代已经来临,信息和物品的极大丰富,让用户如浩瀚宇宙中的小点,无所适从。推荐系统迎来爆发的机会,变得离用户更近: 快...
GitHub 标星 1.6w+,我发现了一个宝藏项目,作为编程新手有福了!
大家好,我是 Rocky0429,一个最近老在 GitHub 上闲逛的蒟蒻… 特别惭愧的是,虽然我很早就知道 GitHub,但是学会逛 GitHub 的时间特别晚。当时一方面是因为菜,看着这种全是英文的东西难受,不知道该怎么去玩,另一方面是一直在搞 ACM,没有做一些工程类的项目,所以想当然的以为和 GitHub 也没什么关系(当然这种想法是错误的)。 后来自己花了一个星期看完了 Pyt...
相关热词 c# 时间比天数 c# oracle查询 c# 主动推送 事件 c# java 属性 c# 控制台 窗体 c# 静态类存值 c#矢量作图 c#窗体调用外部程式 c# enum是否合法 c# 如何卸载引用
立即提问