Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access AWS Cognito forms Django/Python
I'm trying to display the Cognito login/signup forms in my Django app. After googling for a while, i have not found any answer. I'm using django-warrant python lib. -
Django Convert Normal Queryset to Iterator
I have a Django view: def object_search_list(request): if request.user.get_username() in ['username']: objects = MyModel.objects.filter(some_field='filter value').select_related('another_field').prefetch_related('a_third_field') else: objects = MyModel.objects.filter(some_field='a different filter value').select_related('another_field').prefetch_related('a_third_field') return render(request, 'objects/object_list.html', {'objects':objects}) My backend, SQL Server, has a limitation of 2100 paramaters in a query. Therefore, the prefetch_related is causing an error because it is putting more than 2100 parameters into the IN statement of the SQL Server query. How would I use iterator() (if possible) to replace prefetch_related? I understand that it will look something like this: objects = MyModel.objects.filter(some_field='filter value').select_related('another_field').iterator() for o in objects: #do something But I'm not sure how to directly convert rendering a queryset to a template into rendering an iterated queryset to a template. How would I make that conversion? -
Django and changing server times
Is there any library in Django framework that acts like the Moments.js to change the server time with addition or subtraction! -
how can i using hits(views) conter in django
Django-Hitcount allows you to track the number of hits (views) for a particular object Anyone has a way for knowing the number of visitors to the page I find it difficult to do so Any Help I want a useful lesson -
Upgrading to Wagtail 2.3 and Django 2.1 causes migrations and login to freeze
I upgraded our existing site to Wagtail 2.3 from Wagtail 2.1, everything went smoothly and it works fine. I saw support for Django 2.1 was included, so I upgraded Django - it successfully applied the migrations but froze before script completion. I had to close the terminal window to stop it (cntl-c didn't work). I also could not login to the site - runserver would freeze up the same way. I tried this with Django 2.1, 2.1.1, 2.1.2, 2.1.3, 2.1.4 - all with the same results. I've downgraded to Django 2.0.9 and everything is working fine. I'm not sure if this is a Django bug, a Wagtail bug, or a project bug. There is no output when running migrate or runserver. I did look at my Postgres processes - it looked like it was freezing up while trying to read permissions for a user or something related to the content types. I'm looking for ideas on what else I can check to debug this. -
Form does not prevent duplicate creation of a compound primary key
I'm trying my first Django project right now and have encountered the problem that my app reacts strangely when I try to create an object with duplicated compound primary keys. The following starting situation: In order to be able to clearly determine my result, I use a composite primary key consisting of a unique student id (matriculation_number) and a unique exam id (exam_id). Here is the corresponding model in my models.py file: class Result(models.Model): # No student should be able to be deleted as long as there are still results to show. matriculation_number = models.ForeignKey(Student, on_delete=models.PROTECT, verbose_name='Matrikelnummer') # No student should be able to be deleted as long as there are still results to show. exam_id = models.ForeignKey(Exam, on_delete=models.PROTECT, verbose_name='Prüfungsnummer') grade = models.DecimalField(max_digits=3, decimal_places=2, default=None, validators=[MaxValueValidator(6), MinValueValidator(1)], verbose_name='Note') # Workaround for composite primary-key # Get Data using Result.objects.get(matriculation_number=”10”,exam_id=”125”) class Meta: unique_together = (('matriculation_number', 'exam_id'),) verbose_name = 'Ergebnis' verbose_name_plural = 'Ergebnisse' To get a composite primary key at all, I use the workaround with unique_together. The following views.py and forms.py parts also belong to it: views.py class ResultCreateView(generic.CreateView): form_class = CreateResultForm template_name = 'studentmanager/result/result_create_form.html' success_url = reverse_lazy('studentmanager:result') forms.py class CreateResultForm(forms.ModelForm): class Meta: model = Result fields = ['exam_id', 'matriculation_number', 'grade'] widgets … -
What to use django restful api
I want to know if i use django restful api in existing project inorder to use serializer i have to remove django default forms or not? even though it sounds stupid but i'll be grateful if you help me out -
Django Admin List Filter Remove All Option
As you can see from the screenshot bellow, When using and customizing django admin filters like so: class DealExpiredListFilter(admin.SimpleListFilter): title = 'expired' parameter_name = 'expired' def lookups(self, request, model_admin): return ( ('yes', 'yes'), ('no', 'no'), ) def queryset(self, request, queryset): if self.value() == "yes": return queryset.filter(end_date__lt=timezone.now()) elif self.value() == "no": return queryset.exclude(end_date__lt=timezone.now()) Django will insert an "All" option at any case (which is great for %99 of the times). I want to rename or remove that "All" option as can bee seen in the screenshot -
Django - count up timer
Hey I want to implement a timer which starts if I go to this template: {% block content %} <h3>C-Test</h3> <p>In the following text, some of the word endings have been replaced by a gap. The gap is approximately half of the word, e.g. if you see 3 letters, you need to add another 3-4 letters to complete the word. Try your best.</p> <form action="results" id=results method="POST"> <input type="hidden" name="cTestFormat" value="{{ text }}"> <div class="ctest"> {% csrf_token %} {{ forms }}{{ ende }} </div> <div class="command"> <button type="submit" name="ctest_submit">Submit solution</button> </div> </form> {% endblock %} and ends if I click on the Submit solution button. I want it saved into the POST request so I can return the time in my results.html. This is my results.html: {% block content %} <h3>C-Test</h3> {% csrf_token %} <p>You got {{ richtige }} right!!!!!!</p> <p>But {{ falsche }} wrong :(</p> <p> {{ testresult|safe }}</p> {% endblock %} Ive read that you need some scripting language for a timer but I dont have any experience with it. Is there any other method with django to do this or do I need something like javascript? -
How to deploy a Django app locally on a windows xp machine?
I've got a small python 3 application which I'd like to use on a Windows XP machine. Now, the python shell is not that user-friendly, so I decided to build a GUI for it. I've tried using PyQt (with Qt designer) and TkInter, but I don't like working with them. In search for alternatives, I thought about Django. I've worked on a project with Django once and I like the fact that I can use HTML to format the way the app looks. Oh, and I'm in love with how easy it is to implement the admin functionality. However, it looks like deploying a Django application locally on a Windows XP machine isn't even possible. I've read the most recent Django documentation and it states nothing about doing such a thing. If my question is still vague: I'd like to deploy a Django web app locally to use in a browser like Internet Explorer on a Windows XP machine. The installation should be 'plug-and-play'. The application relies on a csv database, so nothing too fancy there. I don't want the user to have them install Python or other dependensies himself. Ultimately, the user should only have to click on the … -
Django Getting User based on AuthToken
I am setting up friend relationships on a social-media style project. When a user goes to the /add_friend endpoint I want Django to automatically know who the user is trying to add a friend based on the AuthToken they are using. I cannot figure out how to do this. Models: class Friend(models.Model): #static variables for friend_status attribute FORMER_FRIENDS = 0 FRIENDS = 1 A_REQUESTS_B = 2 B_REQUESTS_A = 3 friend_A = models.ForeignKey(User, related_name='friend_A') friend_B = models.ForeignKey(User, related_name='friend_B') friend_status = models.IntegerField def __str__(self): return '%s and %s friendship' % (self.friend_A, self.friend_B) class Meta: unique_together = (('friend_A', 'friend_B'),) URL: url(r'^friend_request/(?P<username>[\w.@+-]+)', AddFriend.as_view(), name = 'add_friend'), Class-Based View: class AddFriend(APIView): def get(self, request, username): user = Token.objects.get(key='token string').user friend = User.objects.get(username=username) #check for friendship instance new_friend, created = Friend.get_or_create(friend_A=user, friend_B=friend) I'm almost certain the trouble is this line: user = Token.objects.get(key='token string').user I don't know what value to enter for the key. The key is unique for each token, and I obviously don't want to hard code a key in there. I have tried removing the key entirely like this: user = Token.objects.get.user But in that case I get the error: AttributeError at /friend_request/brian 'function' object has no attribute 'user' Can someone please advise … -
Unable to Escape \? in Python Regex
This question has been asked many times before. And the answer is all the same: If searching for a literal question mark r'?' then the question mark should be escaped with a backslash r'\?' The problem is that I keep getting this Django Error when I run the command: nothing to repeat at position 0 (line 1, column 1) What have I done wrong in my code? rawcontent = "Im Ron Burgandy? I saw that! Brick killed a guy. Did you throw a trident? San Diego..." # This line works fine. rawcontent = re.sub('!\r\n([a-zA-Z])',r"!\r\n#Stuff-To-Insert#\1", rawcontent) # This line causes the error, although it should catch the ? on the 1st and 2nd lines rawcontent = re.sub('?\r\n([a-zA-Z])',r"\?\r\n#Stuff-To-Insert#\1", rawcontent) I've tried: Googling like crazy, multiple backslashes \? & \\? & \\\?, and cursing & squinting really hard at the screen, but nothing works. Note: I'm using Python 3.7 & Django 2.1 - Similar Posts Question1, Question2, Question3 - -
How to define a foreign key based on name when extending a django-oscar model?
I have forked the django-oscar catalogue app to have an additional model, Collection. This is for a furniture site, so the idea is that several products will be part of a collection, which has a name in common with all products. For example, a Bedroom collection might have a nightstand, chest of drawers and bed, all named 'Denver'. My goal in doing this is so that I can display a page showing different collections, and for each collection show all the products associated with that collection. Also that when deleting a collection all associated products are deleted, but not the other way around. This is the model I am using in my forked version of the django-oscar catalogue app: from django.db import models class Collection(models.Model): name = models.CharField(max_length=50) prod_category = models.CharField(max_length=50) description = models.TextField() manufacturer = models.TextField() num_products = models.PositiveIntegerField() image_url = models.URLField() from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) multiplier = models.DecimalField(max_digits=2, decimal_places=1, default='2.2') from oscar.apps.catalogue.models import * My concern is that, by setting the foreign key as I have, django automatically creates a collection_id field, but each product is not tied to a collection based on any criteria. I would like to use the … -
Is it possible to pass an argument to a celery task in django settings?
I have the following entry in my settings.py file: CELERYBEAT_SCHEDULE = { 'exec-task-every-hour': { 'task': 'app1.tasks.task1', 'schedule': crontab(hour='0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23', minute='0') } } And int works perfectly. Is it possible to add an argument, and pass it through this settings entry, to the task being called (task1)? -
How to add emotion detection to Django website?
I want to add machine leaning(like emotion detection or face recorgination) to my python(django) based website.Do I need to use Rest Api for it? How this gonna work? I am new to it so help please! How Json can help?? -
Where is django installed windows?
I am trying to find the file Django admin but I can't find it. What command can I use to find where this is located? Thanks. P.S I am using windows 10 -
POST Request Method not working in Django Rest Framework
Whenever I try a post request, this is the error I get: TypeError at /api/ Direct assignment to the forward side of a many-to-many set is prohibited. Use project_team.set() instead. Request Method: POST Request URL: http://127.0.0.1:8000/api/ Django Version: 2.0 Exception Type: TypeError Exception Value: Direct assignment to the forward side of a many-to-many set is prohibited. Use project_team.set() instead. Exception Location: C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py in set, line 509 Python Executable: C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.3 Python Path: ['C:\Users\Siddhesh\Desktop\TechForSocial\backend', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\python36.zip', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib\site-packages', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib\site-packages\pytz-2018.5-py3.6.egg'] Server time: Mon, 17 Dec 2018 17:57:57 Code: Models.py class DummyPeopleModel(models.Model): person_name = models.CharField(max_length=45) def __str__(self): return self.person_name class ActiveProject(models.Model): project_name = models.CharField(max_length=30) project_abstract = models.CharField(max_length=1000) project_paper = models.CharField(max_length=1000) project_team = models.ManyToManyField(DummyPeopleModel, help_text='Team that works on this Project' ) project_join_us = models.CharField(max_length=1000) def __str__(self): return self.project_name serializers.py from rest_framework import serializers from .models import ActiveProject class ActiveProjectSerializer(serializers.ModelSerializer): class Meta: model = ActiveProject fields = ('id', 'project_name', 'project_abstract', 'project_paper', 'project_team', 'project_join_us',) def create(self, validated_data): return ActiveProject.objects.create(**validated_data) views.py class ProjectList(generics.ListAPIView): queryset = ActiveProject.objects.all() serializer_class = ActiveProjectSerializer def post(self, request): serializer = ActiveProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ProjectDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ActiveProject.objects.all() serializer_class = ActiveProjectSerializer -
celery workers unable to connect to dockerized redis instance using Django
Currently have a dockerized django application and intended on using Celery to handle a long-running task. BUT Docker-compose up fails with following error: [2018-12-17 17:25:59,710: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379//: Error -2 connecting to redis:6379. Name or service not known.. There are some similar questions concerning this on SOF but they all seem to focus on CELERY_BROKER_URL in settings.py, which I believe I have set correctly as follows CELERY_BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' My docker-compose.yml : db: image: postgres:10.1-alpine restart: unless-stopped volumes: - postgres_data:/var/lib/postgresql/data/ networks: - dsne-django-nginx django: &python restart: unless-stopped build: context: . networks: - dsne-django-nginx volumes: - dsne-django-static:/usr/src/app/static - dsne-django-media:/usr/src/app/media ports: - 8000:8000 depends_on: - db - redis - celery_worker nginx: container_name: dsne-nginx restart: unless-stopped build: context: ./nginx dockerfile: nginx.dockerfile networks: - dsne-django-nginx volumes: - dsne-django-static:/usr/src/app/static - dsne-django-media:/usr/src/app/media - dsne-nginx-cert:/etc/ssl/certs:ro - /etc/ssl/:/etc/ssl/ - /usr/share/ca-certificates/:/usr/share/ca-certificates/ ports: - 80:80 - 443:443 depends_on: - django redis: image: redis:alpine celery_worker: <<: *python command: celery -A fv1 worker --loglevel=info ports: [] depends_on: - redis - db volumes: postgres_data: dsne-django-static: driver: local dsne-django-media: driver: local dsne-nginx-cert: networks: dsne-django-nginx: driver: bridge init.py : from .celery import fv1 as celery_app __all__ = ('celery_app',) celery.py : from __future__ import absolute_import, unicode_literals import os from celery … -
No display list of products django
After login we should see a list of products. But the list didn't display. models.py from django.db import models from django.urls import reverse class Product(models.Model): name = models.CharField(max_length=50, db_index=True) price = models.DecimalField(max_digits=10, decimal_places=2) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return self.name def get_absolute_urls(self): return reverse('shop:product_list') -
Getting formula while fetching data from excel sheet in python
I am using openpyxl to deal with the excelsheets on my app. I have a case where I have to manipulate row data for the number of scenarios. e.g:- =SUM(2,4) whose value is 6 for the perticular row. I want to get data from this row. But when I am using:- wb = load_workbook(filename = 'new_1.xlsx') x = wb['Sheet1'] x['A1'].value _________________ Output:- '=SUM(2,4)' But I am expecting output to be 6 not the formula of the cell. -
Deploy django with Heroku issue, ERR_CONNECTION_REFUSED
I deployed with Heroku, and I can see my template and everything. But when I register/login.. it gives me Failed to load resource: net::ERR_CONNECTION_REFUSED I believe it is a problem with wsgi.py not doing manage runserver because when I run manage runserver on my VS code, and refresh the website.. then I have connection to the database. I am stuck as to where the error is coming from. Is it gunicorn,settings.py, or something I'm missing in Procfile? wsgi.py import os import sys from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() application = DjangoWhiteNoise(application) Profile release: python manage.py migrate web: gunicorn mysite.wsgi:application --log-file - Settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = ['django-react-.herokuapp.com', '127.0.0.1'] INSTALLED_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'corsheaders', 'rest_auth.registration', 'rest_auth', 'rest_framework.authtoken', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'form', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = … -
Wagtail streamfield on frontend (architecture question)
I'm about to start a little side project and discovered wagtail cms. The main idea is to create a web project which is about sharing information with others. I thought i could use the wagtail streamfield on the frontend, to make it easy for all users to create content. But it appears to me that streamfields were not designed for this purpose. The alternative would be a text area with tinymce. Users would hand in submissions for review. In the wagtail backend I would convert the submitted text to streamfield input. But this would generate too much overhead. Would it be wise to use plain django for this? The site is going to rely heavily on user generated content. Maybe I'm missing something but is wagtail designed for what I intend to do? Any advice would be much appreciated. -
Displaying images as MultipleCheckBox in django
I am currently working on project in which user can select Category and Industry and based on these two condition i want to show related images, then user select some images and these images are associated with order.SampleImages model has following code. class SampleImages(models.Model): image = models.ImageField(upload_to='images/tile_images/') category = models.ManyToManyField(Category) industry = models.ManyToManyField(Industry) order_detail = models.ForeignKey(OrderDetail, on_delete=models.SET_NULL, null=True, blank=True) class Meta: verbose_name_plural = 'Sample Images' def __str__(self): return '{}'.format(self.id) Can any one suggest how to show images as multiple select checkbox? -
Replace in a string with unicode dango and python3.7
so i have this charfield in django: class Rue(models.Model): created = models.DateTimeField(null=True, blank=True, editable=False) modified = models.DateTimeField(null=True, blank=True) name = models.CharField(blank=True, null=True, max_length=200) Here is my script : print(rue.name) rue.name = rue.name.replace("Ã%Coles","Ecoles") print(rue.name) rue.save() I want to correct the error of an imported file, and clean the database. I would like to replace the "Ã%Coles" by "Ecoles". but the output is : Rue Des Ã%Coles Rue Des Ã%Coles How to clean this ? i want to replace "Ã%Coles" by "Ecoles" -
Can't connect to /home/ubuntu/env/Project/Project.sock
Am trying to host a we application using gunicorn and nginx. But I cant start the gunicorn service. everytime am getting the error message. This is the error am getting (env) root@ip-172-31-21-54:/home/env# sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2018-12-17 14:59:42 UTC; 488ms ago Process: 14160 ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - -- workers 3 --bind unix:/home/ubuntu/env/Project/Project.sock Project.wsgi:application (code=exited, status=1/FAILURE) Main PID: 14160 (code=exited, status=1/FAILURE) Dec 17 14:59:36 ip-172-31-21-54 systemd[1]: Started gunicorn daemon. Dec 17 14:59:37 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:37 +0000] [14160] [INFO] Starting gunicorn 19.9.0 Dec 17 14:59:37 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:37 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:38 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:38 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:39 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:39 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:40 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:40 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:41 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:41 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:42 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:42 +0000] [14160] [ERROR] Can't connect to /home/ubuntu/env/Project/Project.sock Dec 17 14:59:42 ip-172-31-21-54 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Dec 17 14:59:42 ip-172-31-21-54 systemd[1]: gunicorn.service: Failed …