Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SyntaxError: invalid syntax re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$' [on hold]
Can't seem to resolve this syntax error... need help. Much appreciated. The error: File "/max/home/urls.py", line 9 re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', ^ SyntaxError: invalid syntax urls.py from django.urls import path, re_path from home.views import HomeView from . import views app_name='home' urlpatterns = [ path('', HomeView.as_view(), name='home') re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.change_friends, name='change_friends') ] -
django event with date available=True, make available=False on event.date is today
I have a event model which works fine, but i need the boolean to switch to false once the event_date == today, so people cannot book old events class Event(models.Model): event_date = models.DateField() start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, verbose_name='Slot Time', null=True) available = models.BooleanField(default=True) class Meta: verbose_name = u'Event' verbose_name_plural = u'Event' def __str__(self): return str(self.event_date) def get_absolute_url(self): url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk]) return u'<a href="%s">%s</a>' % (url, str(self.start)) i was thinking of something like this def save(day, month, year): events = Event.objects.filter(date__day=day, date__month=month, date__year=year) for event in events: change.available = False change.save() but it doesnt work without a self , what can i use to do make the boolean switch to false when event_date==current_date ? thanks -
Django model form cant use two modelforms
I was wondering how i use two model in a modelform I trIed from django import forms from .models import Question, Choice class CreateQuestionForm(forms.ModelForm): class Meta: model = question, choice Fields = [ 'question' 'choice_text ] -
Where should I place a currency exchange rate functionality?
I'm using Django and I need a some functions to get the exchange rates from different currencies. I want to store the rates in a database table so I need to use a models.py file. Should I place this in an app called /core where also other helper functions live or create a new app for this. -
Django Error pipeline.exceptions.CompilerError: [WinError 2] The system cannot find the file specified
Whenever i run command python manage.py collectstatic i recieve error File "C:\ProgramData\Anaconda3\envs\doors\lib\site-packages\pipeline\compilers__init__.py", line 146, in execute_command error_output=text_type(e)) pipeline.exceptions.CompilerError: [WinError 2] The system cannot find the file specifiedenter image description here -
django 2.1 rest upload file and get url
i want to upload file in django 2.1 using rest framework and save final url in database. this is my current class : class get_contract_events_log(APIView): authentication_classes = (BearerTokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) parser_classes = (JSONParser, FormParser, MultiPartParser,) def post(self, request, contract_id, format=None): print(request.FILES) screenshot_file = request.FILES["screenshot_file"] mouse_event_count = request.data["mouse_events_count"] keyboard_events_count = request.data["keyboard_events_count"] try: contract = Contract.objects.get(id=contract_id) except Contract.DoesNotExist: JsonResponse({"message":"contract id does not exist !"}, status=404) file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() ContractEvent.objects.create( title="", contract=contract, mouse_events_count=mouse_event_count, keyboard_events_count=keyboard_events_count, screenshot_filename=screenshot_file, screenshot_url="https://upload.wikimedia.org/wikipedia/commons/5/57/Bootstrap-3.1.1-screenshot-jumbotron-example.png", event_type="log", created_date_time=datetime.datetime.utcnow().replace(tzinfo=pytz.utc), created_date=datetime.datetime.utcnow().replace(tzinfo=pytz.utc).date() ) return JsonResponse({"message":"log successfully created"}, status=201) all examples on django manual is using serializer funnction, problem is .. i don't want to save file in database, i just want to upload file and save in database only the final url. replace actual screenshot_url, how i can do this ? -
Django 1.11 order results issue
I am using django 1.11: I have a model that calculates the number of false values on a foreign key attribute, like so: Model: class Model(models.Model): . . . def count_total(self): self.anothermodel_set.filter(val=False).count() View: class ModelViewSet(viewsets.ReadOnlyModelViewSet): queryset = Model.objects.all() serializer_class = ModelSerializerClass permissions = AuthenticatedReadOnly pagination_class = StandardResultsSetPagination def list(self, request): queryset = Model.objects.all() # Attempt 1: returns wrong count queryset = queryset.annotate(a_count=Count(Case(When(anothermodel__val=False, then=1), default=0, output_field=IntegerField()))) # Attempt 2: returns wrong count, same as attempt 1 queryset = queryset.annotate(b_count=Count(Q(anothermodel__val=False))) Serializer: In my serializer I've modified the to_represantation definition to debug: def to_representation(self, instance): return {'id': instance.pk, 'a_count': instance.a_count, 'b_count' : instance.b_count, 'correct_count': instance.count_total(),} The instance.save_count() returns the correct results but I cannot simply use it as queryset.order_by('count_total') in the view to order the results without an annotation. Any ideas? -
Django cached_property decorators vs core.cache
I wonder when @cached_property and django.core.cache(e.g. memcached, redis ...) of Django are used differently. I think the roles of the two are similar. I have difficulty deciding which one to use. How do I decide which one to use ? When considering multiple processes, can '@cached_property' be shared between processes? -
Setting up a Django server with Gunicorn and Nginx
I've followed this tutorial and i'm running into an ERR_SSL_PROTOCOL_ERROR that i just can't figure out. I must mention that i have set inside settings.py: DEBUG = FAlSE SECURE_SSL_REDIRECT = False And my Allowed_hosts is ['*']. I have a number of questions which reading alot of blog posts hasn't answered: In the nginx configuration, if i'm running the server from a laptop connected to a router, and the external IP is 12.34.56.78 and the port is 50000, what am i supposed to put at server_name? In the gunicorn configuration, everyone states that this is the config command: gunicorn --bind 0.0.0.0:8800 AWESOME.wsgi:application what IP should i put there in my case? 12.34.56.78:50000 or just leave it like it is? As i understand the situation, given the setting in django settings.py my server is not serving HTTPS so the error does not come from that. I've also read about certbot but since i don't have even those 2 above questions figured out i cannot understand how to configure certbot.. -
Django: How can I perform two forloop under one tablerow?
I want to do this in my template: <tr> {% for journal in journal_debit %} <th><center>{{ journal.Date}}</center></th> <th><center>To</center></th> <th><center><{{journal.To}}</center></th> <th><center>{{ journal.id }}</center></th> <th><center>{{journal.Debit}}</center></th> {% endfor %} {% for journal in journal_credit %} <th><center>{{ journal.Date}}</center></th> <th><center>By</center></th> <th><center>{{journal.By}}</center></th> <th><center>{{ journal.id }}</center></th> <th><center>{{journal.Credit}}</center></th> {% endfor %} </tr> I want to merge two forloop in one table row in django template for a better presentation in my template...If I am doing two table row the information is coming upside down... Is it possible in django? Any idea? -
GraphQL or REST? which one is better for python based web applications?
I use Django and flask as web framework for development and in a brand new project which recently started, I hesitance which one I shall use (REST or GraphQL) to have better performance and ease of usage? I must noticed that my web application will have a lots of request and responses across smartphones. many thanks in advance -
How to change a value of a field in model only a current user?
I have a field 'progress' in Level class Level(models.Model): level = models.CharField(max_length=50, unique=True) helper = models.TextField(null=True, blank=True) progress = models.IntegerField(default=0) I need to add 1 to 'progress'. All I need is to store a different value for every user. I really cannot figure it out how to dot it. Now I have a class LevelProgress in views.py that adds 1 to the field of progress, but it adds 1 globally. class LevelProgress(APIView): def get(self, request, id): queryset_ = Level.objects.get(pk=id) queryset_.progress += 1 queryset_.save() serializer = LevelFullSerializer(queryset_) return Response(serializer.data) How can I add 1 for a current user? -
django 2.1 rest upload file and get final url
I want to upload file in django rest_framework, my curent code is : class get_contract_events_log(APIView): authentication_classes = (BearerTokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) parser_classes = (JSONParser, FormParser, MultiPartParser,) def post(self, request, contract_id, format=None): screenshot_file = request.FILES["screenshot_file"] mouse_event_count = request.data["mouse_events_count"] keyboard_events_count = request.data["keyboard_events_count"] contract = Contract.objects.get(id=contract_id) # file_serializer = FileSerializer(data=request.FILES) # if file_serializer.is_valid(): # file_serializer.save() ContractEvent.objects.create( #.... screenshot_filename=screenshot_file, screenshot_url="https://upload.wikimedia.org/wikipedia/commons/5/57/Bootstrap-3.1.1-screenshot-jumbotron-example.png", ) return JsonResponse({"message":"log successfully created"}, status=201) Serializer: class FileSerializer(serializers.ModelSerializer): class Meta(): model = ContractEvent fields = ('screenshot_file') i my curent code return error : TypeError: The `fields` option must be a list or tuple or "__all__". Got str. [27/Oct/2018 15:04:25] "POST /contracts/3/events/log HTTP/1.1" 500 18899 how i can fix this error ? i need replace screenshot_url with path of uploaded file. -
Django multiple databases synchro
How to synchronize two tables in different databases in django? For example, table app_nedv.Flat in database dt1 and table app_nedv.Flats in database dt2? -
custom user creation form dosent save password
hello guys in django i tryed to make a simple custom user creation form extends as UserCreationForm .everything works but after save the record in database dont have password and i dont know why is that happening. help me plz from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class MyRegistrationForm(UserCreationForm): email=forms.EmailField(required=True) first_name = forms.TextInput() last_name = forms.TextInput() class Meta: model=User fields=('username','email','first_name','last_name','password1','password2') def save(self,commit=True): user=super(UserCreationForm,self).save(commit=False) user.email=self.cleaned_data['email'] user.first_name=self.cleaned_data['first_name'] user.last_name=self.cleaned_data['last_name'] if commit: user.save() return user and in the view the code is : def register_user_view(request): if request.method == 'POST': form=MyRegistrationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/accounts/success') args={} args.update(csrf(request)) args['form']=MyRegistrationForm().as_ul() print(args) return render_to_response('register.html',args) def register_succesfull_view(request): return render_to_response('registersucc.html') in database -
Django problem while creating custom user
I make my first steps in django. I'm trying to apply my custom User model. class HotelOwner(AbstractUser): hasHotel = models.BooleanField(default=False) in. Settings: AUTH_USER_MODEL = 'booking.HotelOwner' in Forms: class RegistrationForm(UserCreationForm): class Meta: model = HotelOwner fields = '__all__' in migrations i got this oputput: operations = [ migrations.CreateModel( name='HotelOwner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('hasHotel', models.BooleanField(default=False)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', … -
django 2.1.2 backend authentication fails
I am attempting to use a backend authentication addition to have users authenticate by email, the user fails to authenticate by email and returns 'none' backends.py from django.contrib.auth.models import User class EmailAuth(): """Authenticate a user by an exact match on the email and password""" def authenticate(self, username=None, password=None): """ Get an instance of `User` based off the email and verify the password """ try: user = User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExist: return None def get_user(self, user_id): """ Used by the Django authentiation system to retrieve a user instance """ try: user = User.onjects.get(pk=user_id) if user.is_valid(): return user return None except User.DoesNotExist: return None accounts/settings.py AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailAuth', 'django.contrib.auth.backends.ModelBackend' ] accounts/views.py excerpt, the user is 'None' but the username and password are passed to the authentication function def login(request): """Return a login page""" if request.user.is_authenticated: return redirect(reverse('index')) if request.method == "POST": login_form = UserLoginForm(request.POST) if login_form.is_valid(): user = auth.authenticate(username=request.POST['username'], password=request.POST['password']) # import pdb; pdb.set_trace() if user: login(user=user, request=request) # login(request, form.get_user()) messages.success(request, "You have successfully logged in!") return redirect(reverse('index')) else: login_form.add_error(None, "Your username or password is incorrect") else: login_form = UserLoginForm() return render(request, 'login.html', {'login_form': login_form}) account/urls.py from django.conf.urls import url, include from accounts.views import logout, … -
Django: get many to many objects from multiple objects
class Test(models.Model): tags = models.ManyToManyField(Tag, related_name='test_tag') ... I have tests = Test.objects.filter(attr='something') Now i want all the tags objects related to tests. I am trying: Tags.objects.filter('test_tag__in'=tests) but looks its not working -
Problem in creating the perfect django custom validation
I have this model for my accounting app: class Simpleunits(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) symbol = models.CharField(max_length=32) formal = models.CharField(max_length=32) class Compoundunits(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) firstunit = models.ForeignKey(Simpleunits,on_delete=models.CASCADE) conversion = models.DecimalField(max_digits=19,decimal_places=2) secondunit = models.ForeignKey(Simpleunits,on_delete=models.CASCADE) class Stockdata(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) stock_name = models.CharField(max_length=32) unitsimple = models.ForeignKey(Simpleunits,on_delete=models.CASCADE,null=True,blank=True) unitcomplex = models.ForeignKey(Compoundunits,on_delete=models.CASCADE,null=True,blank=True) I want to create a custom validation method under model class Stockdata that if the user mention both unitsimple and unitcomplex then they will get a validation error that "Only one unit should be given" and vice versa... I mean to say that the user can only mention one unit either unitsimple or unitcomplex if they mention both then they will get a validation error... Do anybody have any idea what should I do under def clean(self) function to accomplish this..??? Thank you in advance... -
Migrating from Django 1.11 to 2.1: There are duplicate field(s) in 'fieldsets[2][1]'
I'm currently migrating my Django 1.11 app to Django 2.1. I have a custom user model: from authtools.models import AbstractEmailUser, UserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from model_utils.fields import AutoLastModifiedField from model_utils.models import SoftDeletableModel from core.behaviors import UniversallyUniqueIdentifiable class User( UniversallyUniqueIdentifiable, SoftDeletableModel, AbstractEmailUser ): """ User should generally not be deleted, but rather is_removed should just be set to true. The delete() method is overwritten in the SoftDeletableModel. Also add a uuid field to avoid displaying the sequential primary key. """ name = models.CharField(_('name'), max_length=255, blank=True) modified = AutoLastModifiedField(_('modified')) objects = UserManager() And a custom admin: from authtools.admin import (BASE_FIELDS, SIMPLE_PERMISSION_FIELDS, NamedUserAdmin) from django.contrib import admin from .models import User def verified(obj): email = obj.emailaddress_set.filter(primary=True) if email.exists(): return email[0].verified return False verified.boolean = True @admin.register(User) class SoftDeletableNamedUserAdmin(NamedUserAdmin): """ Overwrite the fields of the NamedUserAdmin to add is_removed. """ date_hierarchy = "date_joined" list_display = ( 'email', 'name', verified, 'is_active', 'is_removed', ) search_fields = ["email", "name"] readonly_fields = ("date_joined", "modified") fieldsets = ( BASE_FIELDS, SIMPLE_PERMISSION_FIELDS, ("Contact information", { "fields": ( ("email", "name"), ) }), ("Account information", { "fields": ( "is_removed", ), }), ("Dates", { "fields": ( ("date_joined", "modified",), ), }) ) list_filter = ('is_active', 'is_removed',) The problem … -
Django URL dispatcher explanations 301 and 302 code error
I'm a beginner with Django and I have a problem with the Django url. The below text is my url file: path('<slug:menu_slug>/', views.home_menu, name='home-menu'), path('<slug:menu_slug>/<slug:section_slug>/', views.home_section, name='home-section'), path('<slug:menu_slug>/<slug:section_slug>/<slug:item_slug>/', views.single_item, name='single-item'), When I request for example the url guide/territory/ in my console obtain this output "GET /en/guide/territory/ HTTP/1.1" 200 11227 "GET /en/guide/territory/undefined HTTP/1.1" 301 0 "GET /en/guide/territory/undefined/ HTTP/1.1" 302 0 "GET / HTTP/1.1" 302 0 "GET /en/ HTTP/1.1" 200 26271 my question is why are there requests with undefined? Thanks in advance for the response. -
django does not allow form inputs in non-english languages
I have an input in my form which I try to label in Russian, for example: email = forms.CharField(label='ййй') The problem occurs when the label contains only non-English characters, the label simply disappears. Interestingly enough, when the label contains at least one English character, the label will appear, for example: email = forms.CharField(label='йййa') Works correctly. The same problem occurs with attributes in the widget parameter email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'ййй'})) -
unable to handle exception in django while implementing multithreading
views.py: from threading import Thread class PoliceJobs: def call_police_defence_jobs(request): job = PoliceDefenceJobs.police_jobs(request) sleep(0.5) job_details = PoliceDefenceJobDetails.police_defence_job_details(request) message = call_all(job,job_details) return HttpResponse(message) def call_statewise_police_jobs(request): job = PoliceDefenceJobs.statewise_police_jobs(request) sleep(0.5) job_details = PoliceDefenceJobDetails.statewise_police_job_details(request) message = call_all(job,job_details) return HttpResponse(message) def police_jobs(request): try: t1 = Thread(target=PoliceJobs.call_police_defence_jobs,args=[request]) t2 = Thread(target=PoliceJobs.call_statewise_police_jobs,args=[request]) t1.start() t2.start() t1.join() t2.join() return HttpResponse("success") except: return HttpResponse("error") urls.py from django.urls import path from .views import police_jobs urlpatterns = [ path('finish_police_jobs/', police_jobs), ] error in shell: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/soubhagya/Desktop/carrier-circle/backend/finalize/views.py", line 840, in call_police_defence_jobs job = PoliceDefenceJobs.police_jobs(request) AttributeError: type object 'PoliceDefenceJobs' has no attribute 'police_jobs' in PoliceJobs class i changed the function name to PoliceDefenceJobs.police_jobs which is not exist to make error. Here i am making error and handling it by adding except block but it is still showing error in console but not in browser. in browser it is showing success wheather there is an exception. -
ERROR: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am kinda new to Python Django and have already done researches on the error that I am getting but cannot find answers that will solve the problem. I have tried modifying my codes to the answers given in other similar post in stackoverflow as this and in other websites and forums but found no solutions. So here is my story! I am currently working on an ordinary Django project with only one app inside the project directory. Everything works fine until I decided to connect to my project's default sqlite3 db file named 'db.sqlite3' so as I put these lines of codes in my views.py (which I need connect to the default sqlite3 db file so that I could perform data cleaning from there and export it as a new sqlite3 db file with cleaned data). **views.py** import sqlite3 import pandas as pd def Dashboard(): connection = sqlite3.connect('db.sqlite3') df = pd.read_sql_query('select * from Client', connection) connection.close() print (df) Once I run my views in PyCharm, I got this error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So I did some researches and found … -
Djnago Signals or django routers
Is it possible to write relations of models from different projects on django? For example, there is a Flats model from test1 database, and there is a Flat model from test2 database. I need to have changes in the Flat model when changing to the Flats model and backward. I know that it is possible through routers to use several databases in one project, but this is not suitable for the current task. Is it possible to do something through django signals? In Django router i write like this: class AppTestDbRouter(object): def db_for_read(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): return True def allow_syncdb(self, db, model): return db=='default'