Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check_password() with salt?
I have a problem. I am creating a user by User.objects.create(..., password=make_password(data['password'], salt='some_salt'). Thats okay, but how can I check password with this salt? A cant add salt in check_password() method. -
No PUT method in DRF using ModelViewset
I am using Django 2.2 with Django Rest Framework 3.7. I have created a class like this ``` class UserViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = UserSerializer queryset = User.objects.all() def update(self, request, *args, **kwargs): import pdb;pdb.set_trace() I've created UserSerializer like this - class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'name', 'password') write_only_fields = ('password',) read_only_fields = ('id',) def create(self, validated_data): user = User.objects.create( email=validated_data['email'], name=validated_data['name'], ) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): print('lalala from serialzier') import pdb;pdb.set_trace() instance.username = validated_data['username'] instance.save() return instance Only allowed methods being shown are - Allow: GET, POST, HEAD, OPTIONS I wonder why I am unable to perform actions like PUT, DELETE, RETRIEVE. These are by default supported by using ModelViewset as per documentation. In shown code neither serializer's update() nor views.py update() method getting called. Any hint would be appreciable. -
Python List to a Django Databse Table
I have some Django fields, and here is what i'm trying to do. I have a "Times" field, a "Price" Field and a "Start Date" field. So the User would input, for example: Times = 12 Price = 100,00 Start Date = 2019-11-01 with those, the following lists are created: Times = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] Price = [100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, ] Start Date = [2019-11-01, 2019-12-01, 2020-01-01, 2020-02-01, 2020-03-01, 2020-04-01, 2020-05-01, 2020-06-01, 2020-07-01, 2020-08-01, 2020-09-01, 2020-10-01, 2020-11-01] I already know how to create those lists, i'm struggling on how to insert them into Django's Database Table, one per line with the same ID or PK. Example - Times Price Dates 1 100,00 2019-11-01 2 100,00 2019-12-01..... -
go to login_url if user is not a staff member
Within my Django site, how would I go to the login_url if the user is not a staff? @user_passes_test(lambda u: u.is_staff, login_url='/denied/') The login_url argument worked with urls that had a permission_required decorator, but is there any way that I can send them to the url /denied/ f they are not a staff with the lambda notaion function shown above? Or is there another way to check if a user is staff, and then send them to the /denied/ url? Thanks for the help! -
How can i get Survey model data from django-survey-and-report with Graphene?
i'm making an API with Django + GraphQL using Graphene, and will like to add a survey feature, i added and install successfully the django-survey-and-report app, and can create and save surveys from the admin panel, but when i try to retrieved the data from the Survey model it gives me an error. # Type Definition class SurveyType(DjangoObjectType): class Meta: model = Survey # Query survey = graphene.List(SurveyType) # Resolver def resolve_survey(self, info, **kwargs): return Survey.objects.all() GraphQL query query{ survey{ id name } } Error "errors": [ { "message": "Received incompatible instance \"<QuerySet [<Survey: Test>]>\"." } ] -
What is default configuration used by gunicorn?
If for example, in the gunicorn startup, I do not set any config like worker_class or workers or even worker_connections, what configs will be used? -
Django database routing on startup
I'm not even sure if this is possible, but is there a way to have Django test the default database upon startup and, if it fails, to then select another database defined in the config? The closest I've seen is writing a DB Router, but that doesn't work if the default connection already fails upon startup. -
How to use .filter()/.get() to see whether a value is in an external model for validation in Django?
I made a form from a model (EmployeeWorkAreaLog) where the user can enter their Employee # and once they press Enter/Leave, it searches a separate model (Salesman) in the db to make sure this person is a valid employee, if not, a message would pop up from the html side saying it's not valid. Now, I'm trying to add another constraint, such that, if the employee is not in the 'WF' team then it would also give an error, and say to contact a manager. I tried doing it from the forms, but I keep getting this error: int() argument must be a string, a bytes-like object or a number, not 'Salesman' and according to the traceback, it comes from if Salesman.objects.get(id=employee_number).count(): Why is this error occurring? Is there a more efficient/better way to check the employee's team? models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, null=True, blank=False) ... def __str__(self): return self.employee_number The part where I filter it so only employee #'s from Salesman is under the widget attrs as shown below forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def clean_employee_number(self): employee_number = self.cleaned_data.get('employee_number') … -
Images are not displayed with Django in Ubuntu while works well in Windows 10
I have built a gallery website with Django in Win10 and everything works well. However when I want to deploy it in Ubuntu 18.04, all images are not displayed. I think the problem is about the image paths: Source code for images: <img src="{% static img_path %}"> I use for loop for img_path so one img_path can be "home/xinliy/IAI/semlog_web/web/website/static/1.png" Generated html code for this image: <img src="/home/xinliy/IAI/semlog_web/web/website/static/1.png"> hyperlink for this image: 127.0.0.1:8000/home/xinliy/IAI/semlog_web/web/website/static/1.png And the django fail to load this image. I tried to change the hyperlink to be "File:///home/xinliy/IAI/semlog_web/web/website/static/1.png" Then I can see the image in the browser. However all html generated from Django would have a hyperlink with the prefix of "127.0.0.1:8000/" in default and I can never show a single image. I also create a single html file with src="/home/xinliy/IAI/semlog_web/web/website/static/1.png" and it works.But in Django I cannot get away from that prefix. In Win10 images can display but in Ubuntu it cannot. I need help! -
How to delete data from user profile in django
I am trying to remove dns-records that are associated to the user profile via ForeignKey but I am unable to achieve that. How can I delete it? When I try deleting from the shell DnsRecord.objects.filter(profile=self.id).delete() its working OK but when I run the same queryset in the model it is not deleting. def save(self, *args, **kwargs): try: DnsRecord.objects.filter(profile=self.id).delete() except DnsRecord.DoesNotExist: pass super(Profile, self).save(*args, **kwargs) And the Model looks like this class DnsRecord(models.Model): profile = models.ForeignKey(Profile, related_name='dns_records', on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) value = models.CharField(max_length=255, blank=False) objects = DnsRecordManager() class Meta: unique_together = ['profile', 'name', 'value'] def __str__(self): return f'{self.name} {self.value}' -
Variable return types of DecimalField
I have a model thats something like this: class Item(models.Model): value = models.DecimalField(default=0.0, decimal_places=4, max_digits=20) Now suppose that I have two items: a = Item() a.value = 1.20 b = Item() b.value = 2 When I access the model values I get: a.value = 1.2 <float> b.value = 2 <int> Why DecimalField does that? Can't I get the values always as python Decimal? -
How to change model attribute from template?
I am trying to add a user to a ManytoManyField when a button is clicked in the template. The idea is that I want users to mark a memo as read by clicking a button. First I tried to use a ModelManager method to accomplish this but the problem is that I need to pass the request.user arg; therefore that doesn't work. Next I tried a template tag but it didn't seem to work as I couldn't seem to call it in the template. Also, this seems like it is just wrong because I am writing a function in the ModelManager then another function to call that function in the template tag. @register.simple_tag def user_read_memo(user): Memo.mark_as_read(user) I tried to just add a custom view method to call from the template when the user presses a button but this doesn't seem to work either.. And now I am thinking that if I want to add a function then it needs to not be in a view but rather on the Model level. Therefore it seems that a template tag is necessary. Either this or I need to create a new view but that doesn't seem right because I would need to … -
How to add extra category field in django.views.generic
I have class in views.py: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content',] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I want to add object to fields, but when I'm trying to add like this: fields = ['title', 'content', 'category'] the debugger send an error log like this -> FieldError at /post/new/ Unknown field(s) (category) specified for Post I need an extra column to add category field when creating post in my django blog. Here is blog_category.html {% extends 'blog/base.html' %} {% block content %} <h1 class='mb-3'>Category: {{ category | title }}</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2 author_title" href="{% url 'user-posts' post.author.username %}">@{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"N d, Y" }}</small> <div> <small class="text-muted"> Categories:&nbsp; {% for category in post.categories.all %} <a href="{% url 'blog_category' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> </div> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content|slice:200 }}...</p> </div> </article> {% endfor %} {% endblock content %} The main goal is: create category field in views.py -> after pressing "Post" this field should push the content to the … -
Celery Incorrect Padding Base64
I'm having an issue with my worker and I don't know what to do. I have: @periodic_task(run_every=crontab(hour='*', minute='*', day_of_week="*")) def print_hello(): print('hello world') It works and it prints: hell world the first a handful of times and then I get this: [2019-11-05 12:28:57,824: CRITICAL/MainProcess] Unrecoverable error: Error('Incorrect padding') Traceback (most recent call last):... File "/home/xxxxxxxxx/xxxxxxxxx/project/lib64/python3.7/base64.py", line 87, in b64decode return binascii.a2b_base64(s) I'm using Django with Celery. I saw this SO answer. But I'm not trying to send messages to SQS. Plus, this works in another app I've been using so I don't think I need to decode and encode a simple string. Help would be appreciated. -
How to display an image from django models?
I am currently learning to make a blog website using Django.On my index page I want that there should be thumbnails present for the blogs in list form with the image which I asked them to upload while creating the post. I grabbed all the posts from my Post model but I don't know how to grab the image. Here is my index page: <div class="container-fluid row" > {%for post in post_list%} <div class="col-sm-6 col-md-4 bor"> <div class="thumbnail"> <img src="{{...}}" class="img-thumbnail" alt="..."> <div class="caption"> <h3>{{post.title}}</h3> <p>Published on: {{post.published_date}}</p> <p><a href="{%url 'post_detail' pk=post.pk%}" class="btn btn-primary" role="button">Read</a> <a href="#" class="btn btn-default" role="button">Button</a></p> </div> I read several answers related to Model.objects.all thing but I can't really understand what and how to do? I am new to Django. Can anyone help me please?? -
How to change pk field on existing database with data?
I have a user model which has an AutoField as the pk field. Now I want to change pk to uuid as I need to use it on my API. The biggest problem is that project is already running and there some 3-rd party apps which have relation with User model. For example it's DRF Token model. I tried to write some migrations to replace tables and keep my data safe. here is User model: class User(PermissionsMixin, AbstractBaseUser): email = models.EmailField(_("email address"), max_length=64, unique=True) first_name = models.CharField(_("first name"), max_length=30, blank=True) last_name = models.CharField(_("last name"), max_length=50, blank=True) Here are my steps: 1) I created the first migration by adding uuid = models.UUIDField(default=uuid4, editable=False) 2) Then I created empty migrations and filled new uuids from uuid import uuid4 from django.db import migrations def fill_ids(apps, schema_editor): user_model = apps.get_model("users", "User") for user in user_model.objects.all(): user.uuid = uuid4() user.save() class Migration(migrations.Migration): dependencies = [ ('users', '0002_user_uuid'), ] operations = [ migrations.RunPython(fill_ids) ] 3) Before this step everything works good. Then I tried to fill my related models with new ids from django.db import migrations, models from django.conf import settings def change_model_fks(apps, schema_editor): log_model = apps.get_model('admin', 'logentry') token_model = apps.get_model('authtoken', 'token') user_model = apps.get_model('users', "user") … -
How to implement a ManyToMany form with a through model and record multiple relations at once
I have a simple Order and Product models. They have a M2M relationship, so that a Product can be in several Orders and an Order can have several Products. I need a form for the users to gather the following information: List of products to be ordered and units of each one of those products. Date of creation of the Order User who made the order Etc As far as I understand, I need a through model to record the units for each product and I'm okay with that, but I have no idea on how to implement it in the Forms.py and Views.py and neither in the html. How can I show a "units" field next to each of the "product" MultipleChoice field? I already tried the "add form" for the through model in the admin site, but it only let me add relations one by one. After googling I managed to get a form like that, but then again, it's not what I'm looking form. In a magical scenario I would have several form fields with TextWidgets with django-autocomplete to search in them for products (one field per category of product, making it easier to find stuff) and … -
Unable to implement dependent dropdowns
been trying to implement dependent dropdown in my forms but I have been unable to get it right since I don't know much about jquery, but I think I'm doing something wrong if someone could help me out would really appreciate it the problem is upon selecting the fl no field, park_bay does not get updated screenshot followed the post written by Vitor Freitas which can be found here link models.py of app called postlog: from django.db import models class flight(models.Model): fl_no =models.CharField(max_length=6,primary_key=True) inbound= models.CharField(max_length=15,blank=True) dest= models.CharField(max_length=15,blank=True) park_bay= models.CharField(max_length=3) airline= models.CharField(max_length=15) dep_time= models.TimeField() arr_time= models.TimeField() def __str__(self): return self.fl_no the below provided table is in a different app models.py of an app called status: from django.db import models from postlog.models import flight # Create your models here. class FlightStatus(models.Model): Yes = 1 No = 2 CLEANING_CHOICES = ( (Yes, 'Yes'), (No,'No'), ) fl_no= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='fli_no') park_bay= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='parki_bay') catering= models.CharField(max_length=9) fuel= models.IntegerField() pas_cnt= models.IntegerField() dest= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='desti') dep_time=models.ForeignKey(flight,on_delete=models.CASCADE,related_name='dept_time') Cleaning = models.PositiveSmallIntegerField(choices=CLEANING_CHOICES) def __str__(self): return self.fl_no views.py in status app: from django.shortcuts import render,redirect from django.views.generic.base import TemplateView from status.forms import StatusForm from status.models import FlightStatus from postlog.models import flight from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy # Create your views … -
Best way for allowing %d.%m.%Y-formated strings to be passed a model's DateField?
I have been trying to understand the effects of the DATE_INPUT_FORMATS settings and the way Django processes these datfields but whatever I find is either not understanable to me (being relatively new to DJango) or seems to relate to Forms, which doesn't seem to be applicable here. My user model has a birthday field: class LocalUser(AbstractUser): birthday = models.DateField(blank=True, null=True) and I want to create users from a csv. I upload the csv and process its contents: class InputFileForm(forms.Form): file = forms.FileField() def process_file(self): file = io.TextIOWrapper(self.cleaned_data['file'].file, encoding='utf-8-sig') reader = csv.DictReader(file, delimiter=";") l = LocalUser(**dict(line)) l.save() The csv contains dates in e. g. "01.01.1999" format. It works when I reformat dates e. g. via line["birthday"] = datetime.strptime(line["birthday"], '%d.%m.%Y') but I am sure there must be a nicer solution, one where I don't have to modify code wherever a birthday is passed to the user model as string. In the settingy.py file I added: #USE_L10N = False from django.conf.global_settings import DATE_INPUT_FORMATS DATE_INPUT_FORMATS += ('%d.%m.%Y',) but that doesn't help. The error message I get is: ValidationError at /import_export/import_data ["'11.02.1993' value has an invalid date format. It must be in YYYY-MM-DD format."] Do you have any recommendations on how to solve this? -
my ci/cd pipeline on azure builds but the staging app doesnt work
My cicd pipeline on azure will build successfully but when I get to staging it turns out it breaks in the backend. My backend is in django is there either 1. A way to make the entire piepline fail if the backend has an exit code of 1 2. Write a unit test to see if python manage.py works -
How to implement JQuery confirm dialog popup
I have a form with a submit button ant I want to add a confirm modal dialog using JQuery example without success when I use django template I currently used the JS confirm() (see below) but I would like to customize the dialog box I have understand that I should use a JQuery Dialog so I try to implement this solution this is my template: {% extends 'layouts/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block extrahead %} <!--<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />--> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(document).ready(function() { $("#randomize").click(function(event){ var response = confirm("Do you confirm randomization"); if (response == false) { event.preventDefault() } }); }); </script> {% endblock %} {% block title %}Index | Intense TBM{% endblock %} {% block content %} <div class='container'> <h1>Randomization form</h1> </br> <div class="row"> <div class="col-sm"> <strong>Patient code: </strong>{{ preincluded.pat_num }} </div> <div class="col-sm"> <strong>Age: </strong>{{ preincluded.age }} </div> <div class="col-sm"> <strong>Sex: </strong> {% if preincluded.pat_sex == 1 %} Male {% else %} Female {% endif %} </div> </br></br> </div> <form method="POST" class="post-form"> {% csrf_token %} {{ form |crispy }} <!--<button id="randomize" type="submit" class="btn btn-primary" onclick="confirm('Do you confirm randomization?')">Randomize</button>--> <button id="randomize" type="submit" class="btn btn-primary">Randomize</button> … -
Wrote some code for a model.PositiveIntegerField but changed it to Float and it wont register
I am currently working with Django and I just added a models.PositiveIntegerField and then migrated but decided I wanted to change it to models.FloatField. After making that change I went into django admin dashboard and was checking out an entry that I made which had 0 set as quantity at first but after I migrated the new changes it is now 0.0 Now the problem is that if I try to save a number, say 5.0, it would require me to enter a whole number. Even if I try to save the page with 0.0 it would summon an error. Should I reverse my migration? -
Target WSGI Script Cannot be loaded as a Python Module: No module named 'pytz'
This error seems fairly simple to solve right? I tried doing pip3 install pytz. But it still seems to think it's not there. Any ideas? For context I'm following this guide https://mindchasers.com/dev/apache-install And here is my error.log: [Tue Nov 05 16:36:26.413502 2019] [wsgi:error] [pid 23202:tid 140594089387776] mod_wsgi (pid=23202): Target WSGI script '/build/CommsApp/CommsApp/wsgi.py' cannot be loaded as Python module. [Tue Nov 05 16:36:26.413537 2019] [wsgi:error] [pid 23202:tid 140594089387776] mod_wsgi (pid=23202): Exception occurred processing WSGI script '/build/CommsApp/CommsApp/wsgi.py'. [Tue Nov 05 16:36:26.413732 2019] [wsgi:error] [pid 23202:tid 140594089387776] Traceback (most recent call last): [Tue Nov 05 16:36:26.413800 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/CommsApp/CommsApp/wsgi.py", line 12, in <module> [Tue Nov 05 16:36:26.413805 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.core.wsgi import get_wsgi_application [Tue Nov 05 16:36:26.413811 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/django/django/core/wsgi.py", line 2, in <module> [Tue Nov 05 16:36:26.413815 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.core.handlers.wsgi import WSGIHandler [Tue Nov 05 16:36:26.413820 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/django/django/core/handlers/wsgi.py", line 8, in <module> [Tue Nov 05 16:36:26.413824 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.core.handlers import base [Tue Nov 05 16:36:26.413830 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/django/django/core/handlers/base.py", line 8, in <module> [Tue Nov 05 16:36:26.413833 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.urls import … -
select2 multi select box only takes in the last selected value into the array
I recently tried using select2 multi-select box in my django app, the select2 box displayed properly and I can select multiple options like it should, but there is just a problem when the selected values taken into the array, this is my code : html page <head> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" /> <script src="{% static 'js/vendor/jquery-3.4.1.min.js' %}"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script> <script> $(document).ready(function() { $('.recipientMultiSelect').select2({ placeholder: "Choose Recipient Numbers / Groups", tags: true }); }); </script> </head> <body> <form action="{% url 'broadcast_single' %}" method="POST"> {% csrf_token %} <div class="col-md-4"> <div class="form-group"> <label for="broadcast_name" class="col-form-label"> Broadcast Name: </label> <input type="text" name="broadcast_name" class="form-control" required> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="recipients[]" class="col-form-label"> Recipient List: </label> <select class="recipientMultiSelect form-control" name="recipients[]" multiple="multiple" required> <option value="aaaaaa">aaaaaa</option> <option value="bbbbbb">bbbbbb</option> <option value="cccccc">cccccc</option> </select> </div> </div> </br> </br> </br> </br> <div class="col-xs-8 col-md-8"> <div class="form-group"> <label for="broadcast-content" class="col-form-label"> SMS Content: </label> <textarea name="broadcast_content" rows="15" cols="85" maxlength="160" class="form-control"> </textarea> </div> </div> <div class="col-xs-8 col-md-8"> <div class="form-group"> <button class="btn btn-primary btn-block mt-4" type="submit">Send Broadcast</button> </div> </div> </form> </body> lets assume that all 3 options are selected and passed into the array recipients[] views.py def broadcastSingle(request): if request.method == 'POST': bcName = request.POST['broadcast_name'] bcRecArray = request.POST['recipients[]'] bcContent = request.POST['broadcast_content'] print('PRINT : ',len(bcRecArray)) print(', … -
How to make DRF pass query parameters to the actions
I am using filtering in the django rest framework using django-filters. Due to the nature of some @actions I have on my viewset, I need the filter parameters to be passed to these actions. Is there any way to pass the query parameters of the current listview of a viewset to these actions?