Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I HyperLink to another model using the property of a ForeignKey in a serializer
I'm trying to generate a link to the user when serializing a snippet (i.e. my model). The model already has a foreign key that links to the user who creates this snippet, but I don't know how to link HyperlinkedRelatedField to that user. The code is based on django-rest-framework's official tutorial 05, you can find it here serializers.py: class SnippetSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="rest-serial:snippet-detail") # TODO: Link to the user # Currently this would use the snippet's pk as the user's pk owner = serializers.HyperlinkedRelatedField(view_name="rest-serial:user-detail") ... class Meta: model = Snippet fields = ['url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style'] models.py from django.contrib.auth.models import User class Snippet(models.Model): owner = models.ForeignKey(User, related_name='snippets', on_delete=models.CASCADE, null=True) ... I was thinking about something like owner = serializers.HyperlinkedRelatedField(view_name="rest-serial:user-detail", queryset=User.objects.filter(id='owner.id')) but apparently that's not how django works. Can anyone point me a direction? -
Adding One-To-One field to the default Django user model
I'm trying to add one-to-one field to the default Django user model but for some reason I keep getting error from the database: django.db.utils.IntegrityError: NOT NULL constraint failed: frontend_usermodel.test_suites_id this is models file: from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.db import models class TestSuite(models.Model): id = models.IntegerField(primary_key=True) ... ... def __str__(self): return self.name class Meta: ordering = ('name',) class UserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) test_suites = models.OneToOneField(TestSuite, on_delete=models.CASCADE) def __str__(self): return self.email @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserModel.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() What can I do to solve this ? -
Amazon Web Services - S3 'The authorization mechanism you have provided is not supported' in Django
I am trying to configure my Django application to host image files within an AWS S3 bucket, but the images won't load. Instead, I receive the following error message: 'The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256' I'm aware that this issue has been raised by others using different languages, and I've tried some suggested solutions but nothing has worked so far. My config settings are displayed below: # env.py os.environ.setdefault("AWS_ACCESS_KEY_ID", "AKIA6A6ODKPNZNKA2ZFS") os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "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") os.environ.setdefault("AWS_STORAGE_BUCKET_NAME", "acceler8-company-logos") os.environ.setdefault("AWS_S3_REGION_NAME", "eu-west-2") # settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # boto.cfg [s3] use-sigv4 = True I initially didn't include AWS_S3_REGION_NAME in my configuration because in the S3 console it says 'S3 does not require region selection'. What I read regarding the error message suggested that this was necessary, but adding it to the config hasn't helped. I also added the 'boto.cfg' file, following AWS guidance (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html) but this hasn't helped either. -
What's the purpose of verbose_name and help_text in Django model fieds?
I'm wondering what's the purpose of setting verbose_name on Django model fields and how it's different from help_text. How are these being used by Django? -
How can I reject and close connections in django-channels 2?
It's been 1 month since I started using django-channels and now I have a feeling that I am not disconnecting websockets properly. When I disconnect I want to destroy the group completely if no one is there and it should be no sign of existence. When I'm rejecting connections I raise channels.exceptions.DenyConnection or send {'accepted': 'False'} I was just wondering if this is the right way to do things that I've mentioned or not. -
Passing two models data which have Foreign key relationship to one html Template
I have two models. First one is Cars second one is Rating. I have list view, I am showing all cars here and I want to show cars average rating and rating count also. I have tried adding new fields (avg_rating and rating_count) to my cars model and updating these fields while new rating was submitted. But it is not seen me as good way. Cars Model class Cars(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name Rating Model class RatingModel(models.Model): reviewed_item = models.ForeignKey( Cars, on_delete=models.CASCADE ) excellent = models.FloatField( max_length=20, default=0 )... bad = models.FloatField( max_length=20, default=0 ) cars view class CarsView(BaseContext, TemplateView): template_name = "pages/all_cars.html" def get_context_data(self, **kwargs): context = super(CarsView, self).get_context_data(**kwargs) context["cars"] = Cars.objects.all().order_by("-id") return context -
Is secure to use jwt in android?
is secure to use JWT token in android ? i'm thinking it's not secure because when the user posts the username and password to the server the receives a token and i should save that to the database and use this token in app but the question is is that secure ??? because any rooted app can access to the database and use token in Api Url. one of the solutions i've read is to save token with encryption methods like AES or RSA (same question is that sequre?) should i use OAUTH2(is that more secure that jwt?)? -
Passing Parameters From a Class Based View in Django
I have a class based Update view "ManifestUpdate", which is a modal pop up, and is launched from within another function based view "Manifest". I need to be able to take the field = 'reference' from my ManifestUpdate view and make it available to the "Manifest" view as 'Reference_Nos'. As you can see ManifestUpdate should direct the user to Manifest, but it does not, just nothing happens (it works if I change this to direct to any other view). I believe this is because I am not passing that parameter. Can anyone tell me how to capture that 'reference' parameter within ManifestUpdate and pass it to Manifest from the class based view? views.py class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() reference_id = form.cleaned_data.get('reference') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': … -
Keeping a database size down using unique fields with Django
I ran into a snag on a project today, and considering it's already got quite a bit of data entered, destruction and rebuilding is not a good option. So here it is... This is a site that is basically a helper tool for people learning Mandarin Chinese (for now). A user keeps track of their phrases, vocab, grammar points. Originally, I just set all three of these to be unique fields in that (for example) nobody can enter the same vocab twice. For some reason, that change was either reverted or I did away with it. I don't remember, and it's too late for back tracking now. So my question here is, how can I change my model up so that one user can't make the same exact entry as another user? And as a follow up, if a user does try and make a duplicate entry, I can give said user is given the option to view\modify that entry? from django.contrib.auth.models import User from django.db.models.aggregates import Count from django.db import models from random import randint # Create your models here. SOURCES = [ ('DUOLINGO', 'Duolingo'), ('MEMRISE', 'Memrise'), ('CLASS', 'Class'), ('OTHER', 'Other'), ] LEVELS = [ (1, 1), (2, 2), … -
How to format Django's timezone.now()
I am trying to autofill a django datetimefield using a timezone aware date. Using Django's timezone.now() outputs Aug. 21, 2019, 5:57 a.m.. How can I convert this to 2019-08-21 14:30:59 ? -
Multiple django fields reflects to one db field
How to create a model with 2 different fields with the same db_column? In my example queue_id and content_type_id are always the same id value. So I don't want to store that information twice in a DB table. I set a db_column for both fields but got the error (models.E007) Field 'content_type' has column name 'queue_id' that is used by another field. I added error supression. As result I have an invalid sql code for migration: CREATE TABLE `queue_items_generic` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `object_id` integer UNSIGNED NOT NULL, `queue_id` integer NOT NULL, `queue_id` integer NOT NULL); Manual migration patch has helped. But is there an easier way to do the same stuff? I don't want to patch migrations and supress any errors. Here is the reproducing problem code: from django.db.models import ( Model, ForeignKey, OneToOneField, CASCADE, PositiveIntegerField, ) from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class QueueGeneric(Model): content_type = OneToOneField( ContentType, on_delete = CASCADE, primary_key = True, ) last_object_id = PositiveIntegerField( default = 0, ) last_object = GenericForeignKey('content_type', 'last_object_id') class QueueItemsGeneric(Model): queue = ForeignKey( QueueGeneric, db_column = 'queue_id', on_delete = CASCADE ) content_type = ForeignKey( ContentType, db_column = 'queue_id', on_delete = CASCADE ) object_id = … -
why its showing csrf verification failed even though i imported render
CSRF verification failed. Request aborted. i already tried importing render but it doesnt worked out for me. from django.contrib.auth import login as auth_login from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'signup.html', {'form': form}) -
How to log request and response for 4XX Http status in Django Rest Framework?
The default behaviour of DRF is to throw exception for 5XX, but return valid response with error details for 4XX. I want to log request and response of any API call which fails with 4XX. Currently the log only shows Bad Request : /path/api/ -
OAuth Callback URL incompatible with nginx proxy server behavior
I have spent a good part of the last 3 days trying every solution that is on the internet and feeling desperate. Here's the problem statement: I have a Dockerized app with three services: A django application with gunicorn (web) A Nginx server (nginx) PostgreSQL (db) My web application requires user to log in with their GitHub account through a fairly standard OAuth process. This has always worked without nginx. User clicks on the "log in with github" button, sent them to GitHub to authorize the application, and redirects it back to a completion page. I have "Authorization callback URL" filled in as http://localhost:8000. Without Nginx I can navigate to the app on localhost, click on the button, and upon authorization, get redirected back to my app on localhost. With Nginx, I would always fail with the error: This is my Nginx configuration: upstream webserver { # docker will automatically resolve this to the correct address # because we use the same name as the service: "web" server web:8000; } # now we declare our main server server { listen 80; server_name localhost; location / { # everything is passed to Gunicorn proxy_pass http://webserver; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; … -
I can't solve this "parsererror" ajax error
I am currently doing ajax with django. However, the response becomes an error. Access the views with ajax and create a model. And now we ’re ready to create. I think there is a problem with the return of views. Add any additional information you need. #error fail 200 (index):150 parsererror (index):151 SyntaxError: Unexpected token a in JSON at position 0 at parse (<anonymous>) at Ut (jquery-3.3.1.min.js:2) at k (jquery-3.3.1.min.js:2) at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2) #JavaScript $('form').on('submit', function(e){ let $submit_input = $(this).find('input') let $data = $(this).data('group') console.log($data); e.preventDefault(); $.ajax({ 'url': "{% url 'groups:ajax_post_add' %}", 'type': 'POST', 'data': { 'group': $data, csrfmiddlewaretoken: '{{ csrf_token }}', }, 'dataType': 'json', beforeSend: function(xhr, settings) { $submit_input.attr('disabled', true); } }).then((...args) => { // done const [data, textStatus, jqXHR] = args; console.log('done', jqXHR.status); }) .catch((...args) => { // fail const [jqXHR, textStatus, errorThrown] = args; console.log('fail', jqXHR.status); console.log(textStatus); console.log(errorThrown); }) }); #python #views @require_http_methods(["POST"]) def GroupRequestAdd(request): group_id = request.POST.get('group') group_id = group.objects.get(id=group_id) request_add = belong.objects.create(user=request.user,group=group_id) return HttpResponse("ajax is done!") -
Django single sign on between different ports
thank you for taking a look at this question. I have 2 separate Django projects and host the two project through nginx as such: http://xxx.xx.x.xxx:8080/ => Django Project A http://xxx.xx.x.xxx:8000/ => Django Project B The 2 projects are integrated in such a way that the projects share the same user table of PostgreSQL. Each of the projects has its own login page but I can use the same login credentials on the both login pages. The thing is, the projects cannot share login sessions(or cookies?) with each other. So I need to sign in on the project A first and sign in on the project B once more(or vice versa) with the same credential. I've heard that I need to use SSO(Single Sign On) to solve this problem but none of solutions below could solve it. django-simple-sso django-cas-provider/consumer MamaCAS Tried to tweak session options on settings.py (e.g. SESSION_COOKIE_DOMAIN) Maybe there could be some lack of my understanding on one of those solutions above but most of the solutions were outdated or not fit for this case. How could I deal with this issue? Have you solved any similar issues? -
why does it say "module does not exist" despite multiple installations
I am running the following steps in Mac Terminal: (1) sudo easy_install pip (2) sudo pip install virtualenv (3) virtualenv NameOfFolder (4) cd NameOfFolder (5) source bin/activate (6) sudo pip install django (7) django-admin startproject NameOfFolderSub1 (8) cd NameOfFolderSub1 (9) python manage.py runserver At this last steps, it communicates this msg occurred: Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Attempted to check the Django version using this command in Terminal: python -m django --version it confirmed that django is not there with the following msg: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3: No module named django What did I do wrong int he step-by-step installation above ? Appreciate the help. The code in manage.py is … -
Saving on a Model that has foreign and M2M relation
I have 3 models, say, Fruits, Season, and FruitSeason class Fruit(models.Model): fruit_name = models.CharField(max_length=30) class Season(models.Model): season_name = models.CharField(max_length=30) country = models.CharField(max_length=30) class FruitSeason(models.Model): season = models.ForeignKey(Season, on_delete=models.CASCADE) fruit = models.ManyToManyField(Fruit) I have a form that lets me add Season and (multiple)Fruit details class FruitSeasonForm(forms.ModelForm): season_name = forms.CharField(max_length=30) fruit = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Add comma separated values'})) class Meta: model = FruitSeason exclude('fruit', 'season') I tried saving the list of fruits as individual records in the Fruit Model as well as season details in Season on Form post. views.py class seasonal_fruit(request): if request.method == 'POST': form = FruitSeasonForm(request.POST) if form.is_valid(): fruit_season_form = form.save(commit=False) season=Season.objects.create(season_name=form.cleaned_data['season_name'], country=form.cleaned_data['country']) fruit_season_form.save_m2m() form.save() form post does not save on both the models. How do I work around with it? Not sure where am I going wrong. Is it the modelling of those 3 models or something else. -
How to annotate a queryset with the difference between today & a DateField using ExpressionWrapper
I'm trying to do an annotation of the queryset based on a DateField as shown. I am using Django version 1.8.12 and MYSQL version 5.6.40. Tried following How to annotate a queryset with number of days since creation, but here its a DateTimeField. The comments below says "Changing it to Value(now.date(), DateField()) - F('creation_date__date'), doesn't work" The Model code is shown below: class Holding(models.Model): trans_date = models.DateField(_("Trans. Date"), null=False) ... And the annotate query that gives the wrong duration is shown below: today = timezone.now().date() testqs = Holding.objects.filter(id=1) myqs = testqs.annotate(duration = ExpressionWrapper( Value(today, DateField()) - F('trans_date'), output_field=DurationField())) And when i try to print, all I get is None for the duration. Difference printed for reference. for i in myqs: print i.duration, '-', today-i.trans_date None - 1224 days, 0:00:00 None - 1206 days, 0:00:00 None - 1144 days, 0:00:00 None - 1051 days, 0:00:00 None - 1045 days, 0:00:00 I expect the duration to be a timedelta values with the difference between today and trans_date and not None. -
Connect django project with mongodb
I am not getting any migrations for mongodb(no changes made when i am done with python manage.py migrate commmand) while i am using djongo in settings.py file of my django project. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'student_db', #database_name } } -
Set up a redirect
There is a mixin in the view, where a slash is added to the url. It is necessary that when you open a non-existent page (for example, example.com/index), immediately throw 404, without 301 (so as not to add a slash at the end). Only a check on 404 status comes to mind, if there is one. Like if there is a page, then do not need to add a slash. If there is no such page, then to formally add a slash at the end (without a redirect). And if the status is 200, then okay, and if not, then throw 404. def is_normal_slash_count(url): temp_url = url slash_count = 0 while temp_url.endswith('/'): slash_count += 1 temp_url = temp_url[:-1] return (slash_count == 1, slash_count) def replace_bad_slash(url, slash_count): if slash_count == 2: return url.replace('//', '/') return url.replace('/'*(slash_count-1), '') def normalize_url(url): if len(url) > 1: if not url.endswith('/'): return url + '/' # replace the url like /contacts//// to /contacts/ good_slash, slash_count = is_normal_slash_count(url) if not good_slash: url = replace_bad_slash(url, slash_count) return url def is_bad_url(url): if len(url) > 1: good_slash, slash_count = is_normal_slash_count(url) if not good_slash: return True return False class RedirectMixinView: def dispatch(self, *args, **kwargs): url = self.request.path redirect_setting = RedirectSettings.objects.filter(url_from=url).first() if … -
Passing class to label from forms.py in ChoiceField/MultipleChoiceField
How can I pass a class to label in the field MultipleChoiceField in forms.py to my template. For example, I want my check box to look like this: <div class="custom-control custom-checkbox"> [...] <input type="checkbox" class="custom-control-input" id="customCheck1"> <label class="custom-control-label" for="customCheck1">Option 2</label> [...] </div> So I create a form that looks like this: class Form(forms.Form): field = forms.MultipleChoiceField(choices=MY_OPTION, widget=CheckboxSelectMultiple(attrs={'class': 'custom-control-input', 'label': 'custom-control-label'})) But in my template the form looks like this: <div class="custom-control custom-checkbox"> [...] <input type="checkbox" class="custom-control-input" label="custom-control-label" id="customCheck1"> <label for="customCheck1">Option 2</label> [...] </div> So the label goes to the input field, not the label. How can I add a label to the label field(<label></label>)? Any help will be appreciated. -
ModelForm has no model class specified. (value Error)
from django import forms from .models import Topic class NewTopicForm(forms.ModelForm): message = forms.CharField(widget=forms.Textarea(), max_length=4000) class meta: model = Topic fields = ['subject', 'message'] -
ModelForm validation in Django
I'm trying to validate two forms on one page with single submit button. I don't really mind using either forms.Form or forms.ModelForm knowing the difference. However, when I submit the form for validation all data is being discarded and I get This field is required shouting at me from all fields except the timeout field as that one is optional and defaults to 10. Please see my files: this view I'm using when trying to make it work with ModelForm class. When I'm trying to use just Form class I uncomment the lines and comment out the .save() lines: def index(request): if request.method == 'POST': form_tc = TestCaseForm(request.POST) form_ts = TestCaseSuiteForm(request.POST) if form_tc.is_valid() and form_ts.is_valid(): # TestCase.objects.create( # name=form_tc.cleaned_data['name'], # documentation=form_tc.cleaned_data['documentation'], # steps=form_tc.cleaned_data['steps'], # tags=form_tc.cleaned_data['tags'], # setup=form_tc.cleaned_data['setup'], # teardown=form_tc.cleaned_data['teardown'], # template=form_tc.cleaned_data['template'], # timeout=form_tc.cleaned_data.get('timeout', 10), # ) # # TestSuite.objects.create( # name=form_ts.cleaned_data['name'], # documentation=form_ts.cleaned_data['documentation'], # setup=form_ts.cleaned_data['setup'], # teardown=form_ts.cleaned_data['teardown'], # force_tags=form_ts.cleaned_data['force_tags'], # timeout=form_ts.cleaned_data.get('timeout', 10), # ) form_tc.save() form_ts.save() return redirect('/list') forms.py: class TestCaseForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Name'}), label='') documentation = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Documentation'}), label='') steps = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Steps'}), label='') tags = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Tags'}), label='') setup = forms.CharField(widget=forms.TextInput(attrs={ … -
Filter select field in ModelForm by participant in tournament
i want to create game using forms like this siteaname.com/tournament/creategame. And then i have 2 select field team1 and team2. i have lots of team (500+) but a tournament include 10-16 teams so i want the teams participating in the tournament appear in the team selection section.Sso I can easily select team1 and team2 from only teams participating in the tournament instead of all teams. what do you suggest I do? forms.py class GameForm(models.ModelForm): ... def __init__(self, *args, **kwargs): super(GameForm, self).__init__(*args, **kwargs) self.fields["team1"].queryset =Team.objects.filter(tournament=tournamentslug)#this code is wrong views.py def creategame(request,tournamentslug): form=GameForm() ... context={ 'form':form, } return render(request,'gamecreateform.html',context) urls.py path('<str:tournamentslug>/creategame',creategame,name='create_game'), models.py class Team(models.Model): name=models.CharField(max_length=120,verbose_name="Takım ismi") class Game(models.Model): team1=models.ForeignKey(Team,on_delete=models.CASCADE,verbose_name='Team1',related_name='t1',null=True,blank=True) team2=models.ForeignKey(Team,on_delete=models.CASCADE,verbose_name='Team2',related_name='t2',null=True,blank=True) tournament = models.ForeignKey('Tournament', on_delete=models.CASCADE,related_name="gametournament",verbose_name="Tournament") class Tournament(models.Model): teams = models.ManyToManyField(Team,blank=True,related_name='t_teams',verbose_name="Teams")