Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extended User model in django not saving profile image
Am trying to create a chat forum in django . but to do this i needed to extend the User Model, But after extending it the profile image does not save This is my model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField() img = models.FileField(upload_to='media/', blank=True, null=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() My View: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.profile.email = form.cleaned_data.get('email') user.profile.img = form.cleaned_data.get('img') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'tforum/signup.html', {'form': form}) My Forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(help_text='Required.') img = forms.FileField(help_text='Upload Image') class Meta: model = User fields = ('username', 'email', 'img', 'password1', 'password2', ) Signup.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> The problem is that the user … -
django blog: A server error occurred. Please contact the administrator
I run the code last it's well,but taday when i input http://127.0.0.1:8000/,it show A server error occurred. Please contact the administrator.but I can't find anyerror in settings.py,and i revised the urls.py,then it show enter image description here it seems like there are two question my urls.py from django.conf.urls import url,include,patterns from django.contrib import admin from blog.views import * #admin.autodiscover() urlpatterns = patterns('', url(r'^archive/$',archive), url(r'^admin/',include(admin.site.urls)), ) my setting.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.9.8. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'zzwayk(+k0m-+docu%uigkuymxlde34fx3$=syx#*3-i)8hlel' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
Auto create objects with ForeignKey when save in Django
I got problem with Django auto create objects.Please help me. I have a model Avatar that: class Avatar(models.Model): owner = models.ForeignKey(User, related_name='avatar_owner') photoset = models.ForeignKey(PhotoSet, null=True) image = models.ImageField(max_length=1024, upload_to=avatar_file_path) and model class PhotoSet(models.Model): title = models.CharField(_('title'), max_length=200, null=True) I want to create a def when saving model Avatar with a null photoset, it will auto get_or_create a Photoset with a certain title. I made a def like this but it's not work. @transaction.atomic def create_default_photoset(self, *args, **kwargs): if self.photoset is None: self.photoset, _ = Photoset.objects.get_or_create(title=self.id) super(Avatar, self).create_default_photoset(*args, **kwargs) Am I wrong with this def? How can I fix that? Thank you in advance! -
Django ; NameError: name 'pbkdf2' is not defined
hye i just want to ask why i keep getting this error . i dont understand why it says pbkdf2 is not defined and i already install pbkdf2 and also import PBKDF2PasswordHasher. i have been trying to fix this error for almost 4 hours . hashers.py : def encode(self, password, salt, iterations=None): assert password is not None assert salt and '$' not in salt if not iterations: iterations = self.iterations hash = pbkdf2(password, salt, iterations, digest=self.digest) hash = base64.b64encode(hash).decode('ascii').strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) can someone help me ? im really desperate :( -
What is a strategy of deploying Django + Vue with docker?
I don't fully understand how should I build and deploy the docker container with my app. I have an app which has two parts - REST API with Django REST Framework and SPA with Vue.js. API is connected to Postres. The question is, should I build a single container where I install SPA, API and database, or have app-container linked with a separate database container. I plan to build containers with gitlab ci and deploy to heroku. Or what is the best practice? -
guys i have a issue while migrating my data from models.py
guys i'm getting an error as you should have a default value to models:author,body,created,updated and here is my models.py configuration from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class post(models.Model): STATUS_CHOICE=( ('draft','DRAFT'), ('published','Published'), ) title=models.CharField(max_length=250) slug=models.SlugField(max_length = 250,unique_for_date=1) author=models.ForeignKey(User,related_name='blog_posts') body=models.TextField() publish=models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices = STATUS_CHOICE, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title and this is the error while migrating the database: You are trying to add a non-nullable field 'body' to post without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option i'm not sure what are the default values for those models and the configuration is same as it is mentioned in book but i'm still getting an error any kind of help is appreciated thanks in advance NOTE:this is a blog application and when i tried to add random default values to the models i'm getting this error: … -
How to hide button/form using django templates?
I want to hide form if user already pushed on the button. I tried to use a bit of JS code, it works well, but after refreshing page, button on form stay valid. It not a huge surprise for me)) I want hide form using Django templates, but it is not so easy as I thought. my html : <div class="who_come"> <p>Who come : </p> {% for u in who_come %} {%if u.visitor.username != request.user.username %} <form class="form-inline" role="form" method="post" id="joinToEventForm"> {% csrf_token %} <p align="left"><b ><button type="submit">I want join</button></b></p></b></p> </form> {% endif %} {% endfor %} <div id="who_come_links"> {% for u in who_come reversed %} <p><a href="profile/{{u.visiter.username}}" title="{{u.visiter.first_name}} {{u.visiter.last_name}}">{{u.visiter.username}}</a></p> {% endfor %} </div> <script> $('#joinToEventForm').submit(function() { $(this).find("button[type='submit']").prop('disabled',true); }); </script> <script> $('#joinToEventForm').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check $.ajax({ type:'POST', data:{ action: 'joinEvent', csrfmiddlewaretoken:'{{ csrf_token }}' }, success : function (data) { //console.log(data); var usernames = JSON.parse(data); var html_str = ''; for (var i=0; i < usernames.length; i++) { html_str += '<p><a href="profile/' + usernames[i] + '">' + usernames[i] + '</a></p>'; } $('#who_come_links').html(html_str); } }); }); </script> </div> my model : class WhoComeOnEvent(models.Model): visiter = models.ForeignKey(User, related_name='WhoComeOnEvent') which_event = models.ForeignKey(Topic, related_name='WhoComeOnEvent') in this place : <p>Who come : </p> … -
Unable to install mysqlclient on Ubuntu LTS 16.04 LTS on Python3.6
I installed and created a virtual environment on my Linux Ubuntu LTS 16.04 server. MySQL database is successfully installed and the database server is working. While trying to migrate django I get error that mysqlclient is not installed. When I try to install mysqlclient using the below command, pip install mysqlclient I am getting the below error, Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command /home/ubuntu/django_project/bin/python3.6 -u -c "import setuptools, tokenize;file='/tmp/pip-build-m44_w0__/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d /tmp/tmprdsdub84pip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 copying mysql_exceptions.py -> build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'mysql' extension creating build/temp.linux-x86_64-3.6 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,12,'final',0) -D__version=1.3.12 -I/usr/include/mysql -I/home/ubuntu/django_project/include -I/usr/include/python3.6m -c _mysql.c -o build/temp.linux-x86_64-3.6/_mysql.o … -
django rest api for autosuggest search
i am relatively new in django rest framework(DRF).i want to create a auto suggest api to create a list of objects, do i need to do anything more for auto sugestion or just create a create api and rest of the job will be done in front end, FYI, i am using react native for my front end. This is my model.py, class Item(models.Model): item_id = models.IntegerField(null=True, blank=True) item_name = models.CharField(max_length=100, null=True, blank=True) quantity = models.CharField(max_length=5, null=True, blank=True) unit = models.CharField(max_length=50, null=True, blank=True) and serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' and the api view class ItemList(APIView): """ List all item, or create a new item. """ permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): bazarerlist = Item.objects.all() serializer = ItemSerializer(bazarerlist, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and urls.py from django.conf.urls import url from . import views urlpatterns = [ # api endpoints url(r'^items/$', views.ItemList.as_view()), ] now what should i do more if i want o add a auto suggest while creating list item ? -
Start developer server in django
After update code I have problem with runserver. Could You help me? After typing python manage.py runserver I have following exception. Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0xb615d89c> Traceback (most recent call last): File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/amich/virtualenvs/problemondo/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 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'url_tools' Thank You -
Is there a simple way to handle SECRET_KEY update for encrypted fields?
Let's begin with two assumptions: Some of database fields like third party access tokens are encrypted using e.g. Fernet and SECRET_KEY as encryption key. SECRET_KEY needs to be changed, because of security problem. What would be the best thing to do in such situation? I assume that I should change the SECRET_KEY immediately after I've fixed the security hole, however if I do that I'll essentially lose access to all of the encrypted data. What I have came up with is to first do a migration, which would temporarily replace encrypted fields with simple charfields/textfields + data migration to unencrypt stored values. Then change the SECRET_KEY. Finally bring the encrypted fields back, again with a data migration to encrypt stored values. It seems like a great hassle though, is there a better/simpler/faster way to handle such situation? -
Django/rest: return user's data plus one more json in one response
I'm using django rest-framework in python 3.5. When User.objects.filter(uid = data['id']).exists() I want to combine user's data and {"isnew":"TRUE"} in one json string and return it as response. User's data have this structure: I have the following view function. class UserRegister(CreateAPIView): permission_classes = () serializer_class = RegisterUserSerializer def post(self, request): serializer = RegisterUserSerializer(data=request.data) # Check format and unique constraint if not serializer.is_valid(): return Response(serializer.errors, \ status=status.HTTP_400_BAD_REQUEST) data = serializer.data if User.objects.filter(uid = data['id']).exists(): user = User.objects.get(uid = data['id']) json_resp = { "user":JsonResponse(user), "isnew":"TRUE"} return Response(json_resp, status=status.HTTP_200_OK) else: u = User.objects.create(uid=data['id'], firstname=data['firstname'], yearofbirth=data['yearofbirth'], \ lastname=data['lastname'], othernames=data['othernames']) u.save() return Response(serializer.data, status=status.HTTP_201_CREATED) Then I get the error TypeError: <User: User object> is not JSON serializable. The ideal response must be something like: { user: { "user_id": "844822", "firstname": "zinonas", "yearofbirth": 1984, "lastname": "", "othernames": "" }, isnew: "false" } -
error while migrating models.py
i have created models for a blog application this my models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class post(models.Model): STATUS_CHOICE=( ('draft','DRAFT'), ('published','Published'), ) title=models.CharField(max_length=250) slug=models.SlugField(max_length = 250,unique_for_date='publish') author=models.ForeignKey(User,related_name='blog_posts') body=models.TextField() publish=models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices = 'STATUS_CHOICES', default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title and when i tried to migrate models iam getting an error as ERRORS: myblog.post.status: (fields.E004) 'choices' must be an iterable (e.g., a list or tuple). and my here is my admin.py file from django.contrib import admin from .models import post # Register your models here. admin.site.register(post) please can anyone help me solve this issue thanks in advance guys -
django NOT NULL constrait failed: BekanSite_project.owner_id
I have this problem::: IntegrityError at /addproject/ NOT NULL constraint failed: BekanSite_project.owner_id. I do not know how I can fix this problem. This is my model :: from django.db import models from django import forms from django.contrib.auth.models import User from django.core.validators import URLValidator class Project(models.Model): project_name = models.CharField(verbose_name='Имя проекта',max_length=200, default='') project_cost = models.IntegerField(verbose_name='Сумма инвестиции',default='') investor = models.IntegerField(verbose_name='Долья инвестерa',default='') email = models.EmailField(verbose_name='Почта',max_length=50, default='')..other fields owner = models.ForeignKey(User) def __str__(self): return self.owner VIEWS.py @login_required def addproject(request): if request.POST: form = ProjectForm(request.POST, request.FILES) if form.is_valid(): form.owner = request.user addproject = form.save()"<<<<where it fails" addproject.save() return HttpResponseRedirect(reverse('accounts:profile')) else: form = ProjectForm() return render(request, 'BekanSite/addproject.html', {'form':form,'username':auth.get_user(request).username}) FORMS.py from django.db import models from django import forms from .models import Project from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from PIL import Image class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['project_name','project_cost',...(other fields),] I think it is somehow related to FreignKey. Please help. Thanks beforehand. -
How can I serialize a single Django object to geojson?
I'm trying to serialize a single Django object to geojson format. I was able to do this if multiple objects is given: test = Test.objects.all() test_json = serialize('geojson' , test, fields=('test_type', 'wkb_geometry')) test_geojson = json.loads(test_json) test_geojson.pop('crs', None) test_geojson = json.dumps(test_geojson) To make the serializer accept the single object I modify it to: test_json = serialize('geojson' , [test], fields=('test_type', 'wkb_geometry')) However, the error now would be Test is not iterable in my Django template leaflet map. How can I turn one object to geojson using serializers? Do I have to do it manually? -
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 7: ordinal not in range(128)
Before asking this question, I have searched SO, find several related links:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128), regarding reading in files But they are no useful for my post, all of them are about program, but mine is for installation. After I install the pip, I check the pip list: C:\Users\jin>pip list DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning. pip (9.0.1) setuptools (28.8.0) When I install django use pip, I get the bellow error: C:\Users\jin>pip install django Collecting django Exception: Traceback (most recent call last): File "C:\Python27\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Python27\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "C:\Python27\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "C:\Python27\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "C:\Python27\lib\site-packages\pip\download.py", line 821, in unpack_url hashes=hashes File "C:\Python27\lib\site-packages\pip\download.py", line 659, in unpack_http_url hashes) File "C:\Python27\lib\site-packages\pip\download.py", line 880, in _download_http_url file_path = os.path.join(temp_dir, filename) File "C:\Python27\lib\ntpath.py", line 85, in join result_path = result_path + p_path UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 7: ordinal not in range(128) -
Django Rest Framework Token for Vue js (with axios) requests
How can I pass the token in vue js requests, actually axios requests. For example, I need to specify: axios.defaults.headers.common['Authorization'] = "Token " + $how_can_i_get_the_token_here; I don't understand how can I get the token inside the template without some security risks (I'm just being paranoic here). The code that generates the token is: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) So, I need the token for the specific user that is logged in. For csrf, I have done this: # in template <script>window.csrf = "{{ csrf_token }}";</script> # in js file axios.defaults.headers.post['X-CSRFToken'] = window.csrf; Is this a good idea? What's the best approach? Thanks in advance for answers! -
The program runs to rfuser = RFUser.objects.filter(user=request.user)[0] Being given
def homepage(request): if request.user.is_authenticated(): # get authenticated rfuser rfuser = RFUser.objects.filter(user=request.user)[0] print rfuser # show info of current user project_list = rfuser.project_set.all().order_by('project_name') # project_list = RFUser.objects.filter(user=request.user).order_by('project_name') context_dict = {'projects': project_list} return render(request, 'homepage.html', context_dict) else: return render(request, 'homepage.html') operation result: Internal Server Error: / Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\rfui_web\myaccoutsite\views.py", line 13, in homepage rfuser = RFUser.objects.filter(user=request.user)[0] File "C:\Python27\lib\site-packages\django\db\models\query.py", line 295, in __getitem__ return list(qs)[0] IndexError: list index out of range list index out of range But can not find why the reason is,Do not know if the index is not due to the array of the relevant value -
year date month in django template
I have a home page http://127.0.0.1:8000/home/ which presents a list of blogposts which are a snippet of each blogpost and each snippet links to the full blogpost page which has url for example http://127.0.0.1:8000/home/blog/2017/10/14/. the template for the full blogpost url with year month and day is working correctly however I get a NoReverseMatch on the homepage : Reverse for 'view_blogpost_with_pk' with keyword arguments '{'year': 2017, 'month': 10, 'day': 1}' not found. 1 pattern(s) tried: ['home/blog/(?P[0-9]{4})/(?P[0-9]{2})/(?P[0-9]{2})/$'] I dont know why its using 2017/10/01 instead of the correct year month day. I think im missing something from the view Here is my template for the home page: <div class = "container"> <div class = "col-md-10"> <div class ="well"> {% for p in allposts %} <a href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"><img src="{{MEDIA_URL}}/{{p.pic}}"></a> <h1 class="text-uppercase"><a href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"> {{p.title}}</a></h1> <h3 id ="smallicons"> <i id ="user" class="fa fa-user" aria-hidden="true"></i> <a href="{% url 'accounts:view_profile_with_pk' pk=p.author.pk %}"> {{p.author.username}}</a> <i id = "clock" class="fa fa-clock-o" aria-hidden="true"></i>{{p.date}} <i id = "comments" class="fa fa-comment" aria-hidden="true"></i> <a href= "{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"> {{p.comment_set.count}} comments</a> </h3> <p>{{p.body|truncatewords:"50"}}<a id= "readmore" href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"> read more</a></p> <hr id = "horizontalrule"> … -
Post empty date field error with Django rest framework
#model.py class Form(models.Model): no = models.IntegerField() finish_date = models.DateField(blank=True, null=True) >http http://127.0.0.1:8000/api/forms no=112 "finish_date"="" Return error: "finish_date": [ "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]." ] If I set "finish_date" to null , this post works. And StringField(blank=True, null=True) will not get the error. How to solve? -
many to many table in django without using manytomanyfield
rather than using the models.ManyToMany field in django i just set up a intermediary field with a bunch of foreign keys. is there any reason why this wouldn't work. I can't think of any but why not see if any of you have tried the same. class Authorization(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) permission = models.ForeignKey( 'venueadmin.Permissions', blank=True, null=True) #venue = models.ForeignKey(venue) <-- commented out cause I haven't made the model its referencing yet. -
Django - Comment form in an existing template. How to define it in views.py?
I have 4 models: Post, Comment, Blogger and User. I have an post_description template, in below of that, i has placed an comment form. But how to define it in views? I'm getting problem in - to get its username, like the user who is logged in will be stored as "posted_by" and in which blog post he post will be stored as "topic" of the blog. How to store these information, so they automatically get added? Form that i has described in post_desc.html {% if user.is_authenticated %} <form method="post"> {% csrf_token %} <input type="text" name="comment" style="width: 800px; height: 145px;"> <button type="submit">Submit Comment</button> </form> {% else %} <p><a href="{% url 'login' %}">Login</a> to comment</p> {% endif %} Current view of that post_desc: def post_desc(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'post_desc.html', {'post': post}) -
Python not importing dotenv module
I am setting up an imageboard that uses Django and when i try to load manage.py for the first time i am greeted with this error message Traceback (most recent call last): File "./manage.py", line 3, in import dotenv ImportError: No module named 'dotenv' I have tried using python-dotenv rather than dotenv and it still doesn't work. Any solution for this? -
Automatically update a field on one model after saving another [Django 1.11][Python3.x]
I am learning how to use the post_save signal on Django. Though I am not getting any errors, what I want to do will not work. I have a model (Model) that is supposed to aggregate and average the ratings from the Review model and saves that number in a field called "average_rating." I want the averaging to be done once a user provides a rating on the "Review" model and for the average rating to automatically be calculated and updated on the "Model" model. I know that I can do this with a post_save signal. But I am not sure how. How can I do what I am trying to do? Thanks in advance. models.py from django.db import models from django.db.models import Func, Avg from django.urls import reverse from django.template.defaultfilters import slugify from django.db.models.signals import post_save from django.dispatch import receiver class Model(models.Model): name = models.CharField(max_length=55, default='') slug = models.SlugField(unique=True) average_rating = models.DecimalField(decimal_places=1, max_digits=2, default=0.0, blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.average_rating = self.review_set.aggregate( rounded_avg_rating=Round(Avg('rating')))['rounded_avg_rating'] self.slug = (slugify(self.name)) super(Model, self).save(*args, **kwargs) class Review(models.Model): RATING_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ] model = models.ForeignKey(Model, null=True) rating = models.IntegerField(choices=RATING_CHOICES, default=1) review_date … -
NameError: name 'Honeywords' is not defined ; custom password hasher
hye im little bit confused on how to define Honeywords actually . can anyone help me ? im trying to create a custom password hashers called Honeyword and i already create an app called honeywordHasher and already install it in INSTALLED_APP in settings.py . i manage to make the django to not hash the password by default and use my honeywordHasher but unfortunately it did not store in the db . can anybody give a tip on how to fix this ? i try to figure out this for a week already hashers.py : def salt(self) salt = get_random_string() while Honeywords.objects.filter(salt=salt).exists(): salt = get_random_string() return salt