Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write proper code for Integrity Testing in Django?
I started testing my code and there I wrote a piece of code that will test that if any duplicate name trying to save in database it will rises Integrity Error. First I want to see you my Model: class Company(models.Model): name = models.CharField(max_length=30, primary_key=True,unique=True, validators=[check_valid_characters, check_digit, check_whitespaces]) working_languages = models.ManyToManyField(ProgrammingLanguage, verbose_name='preferred languages') employees = models.IntegerField(blank=False, null=True, verbose_name='number of employees') address = models.CharField(max_length=100, validators=[check_whitespaces]) contact_number = models.CharField(max_length=11, verbose_name='Contact Number', validators=[MinLengthValidator(11),check_valid_mobile_number]) company_website = models.URLField(max_length=200, null=False) def __str__(self): return self.name And Test Case You can see below: def test__when_company_name_duplicate__should_raise_an_error(self): ob1 = Company(name='XYZ',employees='12',address='XYz',contact_number='01784009080',company_website='https://stackoverflow.com/') ob2 = Company(name='XYZ',employees='13',address='XcYz',contact_number='01784009081',company_website='https://stackoverflow.com/new') with self.assertRaises(IntegrityError): ob1.save() ob2.save() After I ran my Testcase the error I am getting is: >>FAIL: test__when_company_name_duplicate__should_raise_an_error (testapp.tests.MyTest) Traceback (most recent call last): File "/home/anik/Works/assignment/task/testapp/tests.py", line 73, in test__when_company_name_duplicate__should_raise_an_error ob2.save() AssertionError: IntegrityError not raised -
Django - Custom default value of a custom dropdown menu
I build a dropdown category selection menu myself to make the search function of my django site more preceise and filterd. This is working pretty fine so far but I was not able to figure out how I can change the default value of my dropdown menu as it's currently showing "--------" and not something like "All" as default selected value. base.html: <div class="my-custom-dropdown"> <a>{{ categorysearch_form.category }}</a> </div> search_context_processor.py: def categorysearch_form(request): form = SearchForm() return {'categorysearch_form': form} does smb. has any idea how this can be accomplished? using the content: parameter at my css only has a very limited bennefit as the lable "All" always gets placed outside of the actual selection box. thanks for reading :) -
Cannot get url from models.py for menu item
I create menu items fro my navigation but I can get everything from models, DB images(icons), name, but when I want to get URL nothing happening. My views for menu def index(request): Post_list = BlogPost.objects.all()[:5] Slider_item = HomePageSlider.objects.all() menu_item = Menu.objects.all() template_name = 'front/index.html' return render(request, template_name, {"Post_list":Post_list, "data_item":Slider_item, "menu_item":menu_item, }) My template HTML {% for menu in menu_item %} <li class="mobile-menu-item"> <a href="{{menu.0.Menu_url}}" class="mobile-menu-item-link">{{menu.Menu_name}}</a> </li> {% endfor %} my models.py for Menu from django.db import models class Menu(models.Model): Menu_name = models.CharField(max_length=100,blank=True) Menu_slug = models.SlugField(name="სლაგი",blank=True) Menu_image = models.ImageField(upload_to="menuimages") Menu_url = models.CharField(name="url",max_length=100,blank=True,null=True) class Meta: verbose_name = "მენიუ" def __str__(self): return self.Menu_name -
django how to get list with foreign key using primary key
i have this scenario where each company have more then one car , i have linked the two models : models.py class Company(models.Model): company_name = models.CharField(max_length=100, primary_key=True, null=False) created_at = models.DateTimeField(auto_created=True, null=True) def __str__(self): return self.company_name class car(models.Model): company = models.ForeignKey(Company, null=True, related_name='companyname', on_delete=models.CASCADE) car_reg = models.CharField(max_length=8, null=True) mot6due = models.CharField(max_length=100, null=True) cut_off = models.CharField(max_length=10, null=True) notes = models.TextField(null=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.car_reg now i have list of companies listed , but now need to access each company to list separate cars belongs to each company views.py def dashboard(request): cars = car.objects.all() total_cars = cars.count() context = {'cars': cars, 'total_cars': total_cars} return render(request, 'cars/dashboard.html', context) def companyList(requst): company_list = Company.objects.all() context = {'company_list': company_list} return render(requst, 'cars/company_list.html', context) and template.html <tbody> {% for company in company_list %} <tr> <td><a href="{% url 'company-list' ?what here? %}"> {{ company.company_name }}</a></td> </tr> {% endfor %} </tbody> -
How to make unique_together both ways?
I am creating a friend model to save a user and his friend. I am using the following model: class Friend(models.Model): user = models.ForeignKey(UserProfile, related_name="user", on_delete=models.CASCADE) friends = models.ForeignKey(UserProfile, related_name="friends", on_delete=models.CASCADE) accepted = models.NullBooleanField(default=None) class Meta: unique_together = ('user', 'friends') In this model, I am able to save ('User1', 'User2') as well as ('User2, 'User1'), which is not what I want. So, how do I make this relation unique? -
facebook api with python error process finished with exit code 0 but not showing output
import json import django_facebook def main(): token={"EAAYweZAE8V28BAEvrqNvhcwiC5Y2KahleAQihgEwKacedR82qEEYWZAGvgQc8OdinAyg6jSNEapN3GR4yBgXNQY9ta2bhuVsBclR8YKRKqDF5CdKmgW0NWRDZCKlvVkmE8ZB1NRqaN6uspKkR38ZA5eVLmROxSRZAm7xgPAfZC2jKSPVmGOYZCivg05pAj0w43CpAS4JKam8xwZDZD"} graph=facebook.GraphAPI(token) fields=['id,name,age_range,hometown'] profile=graph.get_object('me',fields=fields) print(json.dumps(profile,indent=4)) if name=="main": main() i am creating this program and its executing but not showing output??? -
Current user variable in ListView class
I want to execute a database query using the currently logged in user within a ListView class. Then after that I want to put those results into the extra_context variable so I can access them on the html page. After looking on different websites I found this piece of code: class className(LoginRequiredMixin, ListView): context_object_name = 'contextName' template_name = 'app_list.html' def get_queryset(self): return Userproject.objects.filter(user=self.request.user) How can I put the current user into a variable, that I can use later on in a database query? -
Why after applying migrations in django,column is not being added to the table?
I made an app in Django namely facedetection and then after adding it to installedapps in settings.py ,i made its model with the following code:- from django.db import models subchoices=(('Signal Processing','Signal Processing'),('Indian Financial System','Indian Financial System'),('Machine Learning','Machine Learning'),('Embedded System','Embedded System'),('Cloud Computing','Cloud Computing'),) class student(models.Model): name=models.CharField(max_length=50) presentlist = models.CharField(max_length=5000,blank=True) subject=models.CharField(max_length=50,choices=subchoices,default='Signal Processing',blank=True) datelist=models.CharField(max_length=5000,blank=True) batch=models.CharField(max_length=5000) Enrollmentno=models.IntegerField() def __str__(self): return self.name And then i ran commands python manage.py makemigrations and python manage.py migrate.After that when i open the admin panel and entered all the fields in student and then saved it ,i got an error saying,subject was not being added to the column. I also checked migrations files and according to that subject was being successfully added. -
Django admin filtering/searching/sorting for inlines
I want to add changelist-view-like interface to inline models in django admin. E.g. filtering/searching/sorting. No packages or answers found for that sort of thing so far. So... did anyone try to do that yet? Maybe some hints how you would implement it? Use case: user(client) may have quite a big history of transactions, and i'd like to browse that history without having to go to transaction changelist view, filter by user and browse there(that's what i'm doing atm anyway). -
celery beat + django on Windows: [WinError 10061] No connection could be made because the target machine actively refused it
I already tried other solutions on the site and they didn't work, also, many are old questions that reference the now obsolete django-celery-beat package. I'm on Django 3 and Celery 4 which should mean, according to the documentation of the latter, that I don't need anything extra to run Celery with Django anymore. My project is structured so: proj/ |- app1/ |- app2/ |- proj/ |- settings.py |- ... |- celery.py |- tasks.py (I also tried putting tasks.py in one of the apps.) celery.py: import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") app = Celery("proj") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.on_after_configure.connect def setup_periodic_tasks(sender, **_): from .tasks import debug_task sender.add_periodic_task(crontab(), debug_task.apply_async()) tasks.py: from celery import shared_task @shared_task def debug_task(): print("Task executed.") What I do to try and run the project is: py manage.py runserver, celery -A proj.celery beat, celery -A proj.celery worker. On Ubuntu I'd run all three commands with detached screen sessions to run everything on the same terminal in case it's important, but I couldn't find any feasible alternative for Windows, so all three are executed in separate terminals opened after the previous one's command was already running. I tried putting "beat" and "worker" right after "celery" … -
How will i get this output on a ManyToManyField?
I have 3 models VehiclePrice with FK to Vehicle and Vehicle FK to Booking,(but I want to change it to MTM). i need to pull the appropriate price from the price model based on 3 fields. customer_status, duration of days and vehicle_category. (for multiple vehicles booking the customer_status and duration of days won't change) if a customer book only one vehicle it works fine, but a customer can book multiple vehicles under single or multiple categories. how can I re-write the below logic to work with MantToManyFields??? if the model Vehicle had MTM relationship with booking??? @property def unit_price(self): for item in VehiclePrice.objects.all(): if self.customer.customer_status == item.customer_status and (self.duration >= item.slab.start and self.duration <= item.slab.end) and self.vehicle.vehiclecategory == item.category : return item.total_price -
Delete the file object of form after saving or open the file before form saving
What I want is like this below upload the file -> validate -> store in db. form = DocumentForm(request.POST, request.FILES) form.save() # real file stored in directory #open file and validate.. df = pd.read_csv(form.document.path) if validate(df): pass: else: form.remove() # error occurs "DocumentForm object has no attribute 'remove'" Then now, I have two ideas. Is there a way to delete the object in model from Form??? or Is there a way to open the file before it is stored in directory??? -
I can't run the locust in bash console in pythonanywhere for django webapp
I have installed locustio but can't configured it. It is giving errors. I don't know the ports where i can log in. its giving me this error: [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: File "/home/neso/.virtualenvs/django2/lib/python3.6/site-packages/psutil/__init__.py", line 386, in _init raise NoSuchProcess(pid, None, msg) [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: psutil.NoSuchProcess: psutil.NoSuchProcess no process found with pid 6475 [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: 2020-03-15T08:29:22Z [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: [2020-03-15 08:29:22,509] blue-liveconsole4/ERROR/stderr: <Greenlet at 0x7f41eaff9148: <bound method LocustRunner.monitor_cpu of <locust.runners.LocalLocustRunner object at 0x7f41eaff2dd8>>> failed with NoSuchProcess i don"t know where to put the locust.py file. my main project is in the mysites blog subdirectory. So i put it there. and run the command$ locust -f blog/locustfile.py my locustfile.py: from locust import HttpLocust, TaskSet, task, between class UserBehaviour(TaskSet): def on_start(self): """ on_start is called when a Locust start before any task is scheduled """ self.login() def on_stop(self): """ on_stop is called when the TaskSet is stopping """ self.logout() def login(self): self.client.post("/login", {"username":"boy", "password":"testing321"}) def logout(self): self.client.post("/logout", {"username":"sourda", "password":"testing321"}) @task(1) def index(self): self.client.get("/") class WebsiteUser(HttpLocust): host = "http://127.0.0.1:8089" task_set = UserBehaviour wait_time = between(5.0, 9.0) -
django oauth toolkit unsupported_grant_type error
I tried to add outh2 to my django app, so I used django oauth toolkit. So I followed the tutorial, but if I try to get the users token it always sends me a unsupported_grant_type error. How can I fix this error? settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ) } OAUTH2_PROVIDER = { # parses OAuth2 data from application/json requests 'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore', } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('myapp.api.urls')), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), ] client type: confidential authorization grant type: Resource owner password-based chrome advanced rest client url : http://client_id:client_secret@localhost:8000/o/token/ -
django naturaltime returning the same result
In my model i have a fields like : time = models.DateTimeField(auto_now_add=True) In view page i am getting the value like in this format : 2020-03-15T11:07:07.089Z I am getting the date time in this format. {{ result.time|naturaltime }} but its not working it returning me the same date whick is comming from the data base -
How to configure WSS for AWS Elastic Beanstalk, Django-Channels and Docker
I have set up an AWS Elastic Beanstalk Multi-Container environment using a custom Django-Channels image which I deploy on Amazon ECR. All web-socket functionality is working perfectly when dealing with HTTP and WS protocols. However, when I switch to HTTPS, all HTTPS routes are handled properly but WSS fails to connect. Error in the browser console: WebSocket connection to 'wss://[REMOVED_URL]/' failed: Error during WebSocket handshake: Unexpected response code: 403 No error in the back-end logs because it seems the request from the front-end doesn't reach the back-end server. I'm using a React front-end that calls end-points of the Django-Rest-Framework (+ Django-Channels) back-end, is there any extra configuration required for WSS in the client-side? /docker-compose.yml version: "3" services: channels: build: . ports: - 80:8000 environment: - DEBUG - SECURITY_KEY - DB_HOSTNAME - DB_NAME - DB_PASSWORD - DB_PORT /Dockerrun.aws.json { "AWSEBDockerrunVersion": 2, "containerDefinitions": [ { "essential": true, "image": "[PATH_TO_AWS_ECR_IMAGE]", "name": "channels", "portMappings": [ { "containerPort": 8000, "hostPort": 80 } ], "memory": 256 } ], "family": "", "volumes": [] } /Dockerfile FROM python:3.7.5 ENV PYTHONUNBUFFERED 1 ENV REDIS_HOSTS "redis" WORKDIR /usr/src/app RUN mkdir static COPY requirements.txt . RUN pip install -r requirements.txt COPY . . RUN python manage.py migrate --no-input CMD ["daphne", "-b", … -
Django How can I roll back or retrieve data in fields?
I have a question in Django. I changed the name of fields my models.py on my editor. After changing the name, I made makemigrations and did 'migrate' on cmd. After 'migrate', I checked my database on DB broswer and I found that not only the name of fields changed, but the data of the fields also changed into the name of fields I just changed as just lowercased. i.e.) Original name of field was ingredient and I changed the name to Essential_ingredient. I checked DB and turned out that all of data for the column of changed field is essential_field like picture. I posted this question on FB page and one said I can roll back by doing "migrate ". So I tried it and then it turned out that the field came back to original table but the data of the field hasn't changed back to original. Does any know any way solution like my situation? Thanks in advance. -
How to properly return Json reponse to template for ajax/jquery?
Here I am trying to search with the help of ajax and jquery with my django view. When I try to search like this by returning the JsonReponse instead of html_template it doesn't return data below the corresponding id in html But When I return html from django view and create the new html for this searching results and including this template in the original template works perfectly but I find this a longer process So I tried to return json reponse from view and use that json objects in the template like this but it is not working. How can I solve this ? I think I need to work on the ajax part . def search_users(request): q = request.GET.get('q') if q: users = get_user_model().objects.filter(is_active=True).filter(profile__full_name__icontains=q) data = {'users': users} else: users = get_user_model().objects.filter(is_active=True) data = {'users':users} return JsonResponse(data) ajax $(function() { $('#search_users').keyup(function() { $.ajax({ type: "GET", url: "{% url 'dashboard:search_users' %}", data: { 'q' : $('#search_users').val(), }, success: searchSuccess, dataType: 'json' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search_users_results').json(data) #doing html instead of json works after returning html from django view } -
How to add ipv6 in allowed_hosts in django?
My allowed_hosts looks like below: ALLOWED_HOSTS = ['192.168.225.56','127.0.0.1,'[2409:4072:400:.....]'] Error ALLOWED_HOSTS = ['192.168.225.56','127.0.0.1,'[2409:4072:400:.....]'] SyntaxError: invalid syntax -
Getting the select form values for multiple obects in Django
I am making an attendance system for a school. I'm displaying the name and roll no. of the students in the form by retrieving the values from the database and a third option is a form dropdown to select the status of the student, i.e, Present or Absent. The problem is that if there are multiple students in the same class the attendance status of all the students are being saved as the same value as the first roll no. For ex: If roll 1 is present then all the students are marked present regardless of the options I've selected in the form element. Just need help with how to save the different status for individual student which I'm selecting. Views.py def attendance(request, pk): teacher = Teacher.objects.get(id = pk) classes = Class.objects.get(class_teacher = teacher) if request.method =="POST": if 'attend' in request.POST: request.session['date'] = request.POST.get('date') students = Student.objects.filter(classes = classes) return render(request, "dashboard/teacher_attendance.html", {"classes": classes, "students": students, "teacher": teacher}) elif 'mark' in request.POST: students = Student.objects.filter(classes = classes) date = request.session.get('date') for s in students: status = request.POST.get('status') a = Attendance() a.student = s a.classes = s.classes a.att_date = date print(status) a.attendance = status a.save() return redirect('teacher', teacher.id) else: return render(request, … -
Is there an analog of the command chmod +x in Windows
If not, how to run Python files globally as when working with Django (django-admin).Thank you in advance -
Django mail not working in case of signal only
TypeError at /admin/api/staff/4/change/ object of type 'Staff' has no len() Request Method: POST Request URL: http://127.0.0.1:8000/admin/api/staff/4/change/ Django Version: 2.2.11 Exception Type: TypeError Exception Value: object of type 'Staff' has no len() Exception Location: /usr/lib/python3.5/email/_parseaddr.py in getaddrlist, line 252 Python Executable: /home/fractaluser/Desktop/upwork/paul/env/bin/python Python Version: 3.5.2 Python Path: ['/home/fractaluser/Desktop/upwork/paul', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/fractaluser/Desktop/upwork/paul/env/lib/python3.5/site-packages'] Server time: Sun, 15 Mar 2020 05:39:20 +0000 @receiver(post_save, sender=Staff) def hear_signal(sender, instance , **kwargs): if kwargs["created"]: return # mail([instance], "name") return def mail(list, name): from smtplib import SMTP,SMTPAuthenticationError,SMTPException from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText host = "smtp.gmail.com" port = 587 username = "" password = "" from_email= username to_list=list try: email_conn = SMTP(host, port) email_conn.ehlo() email_conn.starttls() email_conn.login(username,password) the_msg = MIMEMultipart("alternative") the_msg['subject'] ="Sponsorshop approval" the_msg["from"]=from_email plain_txt = "testing the message" html_text = '<h1>Hello</h1>' part_1 = MIMEText(plain_txt,'plain') part_2 = MIMEText(html_text,"html") the_msg.attach(part_1) the_msg.attach(part_2) email_conn.sendmail(from_email,to_list,the_msg.as_string()) email_conn.quit() except SMTPException as sm: print(sm) Here is my code. I am trying to send a mail when my Staff models gets updates or created. The same mail is working fine incase of email verification in case of login or register. but, throwing error in the signal @receiver. Can't we send mail in @receiver method. Or is there any way to achive that ? … -
Displaying fields according what the user select in the previous fields in Django
I am new to django, I want to create fields that will be changed according to the user choice in the previous field i.e when user choose 2 in first field then 2 different fields will appear below to that first field. For example: if he chosed 2 in Number of subjects field then 2 different fields will appear stating Subject 1 Name and Subject 2 Name. Any help will be appreciated. Here is the front end of the page on how it will look like -
Django REST Framework the field was declared on serializer but not included
I think this is a relation issue between django default user and app. First of all, I have this project structure. foo_project - foo_project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - apps - board - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py - accounts - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py Board, # models.py class Board(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') title = models.CharField(blank=False, max_length=255) body = models.TextField(blank=False) image = models.ImageField(upload_to='time_line_photo') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Meta: ordering = ['-created'] # serializers.py from rest_framework import serializers from .models import Board from django.contrib.auth.models import User class BoardSerializer(serializers.ModelSerializer): class Meta: model = Board fields = ('id', 'author', 'title', 'body', 'image', 'created','updated') # views.py from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import generics from .models import Board from .serializers import BoardSerializer class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer class BoardDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Board.objects.all() serializer_class = BoardSerialize Accounts, # serializers.py from rest_framework import serializers from django.contrib.auth.models import User from ..board.models import Board class UserSerializer(serializers.ModelSerializer): board_field = serializers.PrimaryKeyRelatedField( many=True, … -
hex literal too big in sqlite
So I wanted to convert msyql query to sqlite where in it has images in hex code,when I run the same query in sqlite browser it is giving me an error, what is the correct way of doing it. Result: hex literal too big: 0x73616666726f6e2e6a7067 At line 1: INSERT INTO `test` (`id`, `yeild`, `image`, `city`, `info`, `fertilizer`) VALUES (9, 'Wheat', 0x77686561742e6a7067, 'Bangalore', 'Weather that is comfortable for humans is also good for wheat. Wheat needs 12\r\nto 15 inches (31 to 38 centimetres) of water to produce a')