Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to put a randomly choice option in Django?
I am writing a web application in Python, using Django. I do have a drop down list of 12 items. With a current functionality, I can choose an item one by one, however, I would like to put an option which selects randomly the items in the interval of [1,12]. For example, by choosing the number 6 in the box, I can have 6 randomly chosen items. any help, hint will be appreciated a lot! thank you. -
save the data in the database by editing the table info - Django
I have a page "EditStudent" that display all absentee's name. This page allows the admin to change their status from absent to present or vice versa, add remarks if needed. The information displayed in the page involved two models. Namelist model.py: Contains all the students information such as studId, studName and more. MarkAtt model.py: save all the attended students that were marked during the class. So this model does not save the absentees name. So to retrieve the absentee's name, i have done a set difference from namelist to MartAtt models. Ive managed to save all the changes made in the EditStudent page except fr the name. Namelist models.py: class Namelist(models.Model): name = models.CharField(max_length=100) program = models.CharField(max_length=10) year = models.IntegerField(default=1) studType = models.CharField(max_length=15) courseType = models.CharField(max_length=15) nationality = models.CharField(max_length=20) VMSAcc = models.CharField(max_length=30) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) MarkAtt models.py: class MarkAtt(models.Model): STATUS=[ ('Present', "Present"), ('Absent', "Absent") ] studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=1) attendance = models.IntegerField(default=100) #100 is present status = models.CharField(max_length=10, blank=True, null=True, choices=STATUS, default="Present") remarks = models.CharField(max_length=100, blank=True, null = True, default = " ") My Views.py: def AbsentStudent(request, id=None): start = None end = None w =1 … -
django: Cant open two different pages when I have two views for an application
I am doing django course from udemy, i did one experiment. Below is my folder structure Project appTwo urls.py ProTwo appTwo/urls.py from django.conf.urls import url from appTwo import views urlpatterns = [ url(r'^$',views.help,name='help'), url(r'^$',views.users,name='users'), ] Now when i try to open the page users by http://127.0.0.1:8000/users it opens the page help.html. For http://127.0.0.1:8000/help it opens help page. When I comment the first entry in urlpatterns in urls.py it opens the users page even if i try to open help page. Can anyone please guide me what wrong I am doing or its working as expected. -
Trying to serialize data from multiple models
I am trying to serialize three django models in a section of my api, but it seems he doesn't like the way I do it .. Im following the documentation of https://www.django-rest-framework.org/api-guide/relations/#nested-relationships I have tried to create 3 serializers one for each model and then put everything together in the fields of the last serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['name', 'user'] class UserCompanySerializer(serializers.ModelSerializer): class Meta: model = UserCompany fields = ['name'] class UserInfoSerializer(serializers.ModelSerializer): profile = UserProfileSerializer companys = UserCompanySerializer(many=True) class Meta: model = CustomUser fields = ['email', 'profile', 'companys'] I thought it would work but it returns the error: ImproperlyConfigured at /user_info Field name profile is not valid for model CustomUser. models.py class UserCompany(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) is_active = models.BooleanField(default=False) companys = models.ForeignKey(UserCompany, on_delete=models.CASCADE, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class UserProfile(models.Model): name = models.CharField(max_length=300, unique=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name -
Saving user data and selecting one instance later on
I am working on a project that requires an image gallery for a website that I am making. I have already made the image upload models and uploaded a couple of images to the server media root. However, I am a newbie in django and can't for the life of me figure out the following problem: The admin should be able to upload images into the server. The admin interface must expose a selector that enables a user to select among the uploaded images to be shown on the website. Among the uploaded images, only one can be selected. In short, I need to store configuration settings from user side on the server but allow only one instance. How can I start? -
How to deploy a django web application on a wamp server step by step method creating a virtual ip
I am trying to deploy my simple dummy "hello world" application on django with wamp server.I have followed many solutions on the internet but not able to work through them.I need simple step by step procedure to deploy the application.I am using python3.7.4 and latest version of wamp server on a 64 bit windows 10 machine.I will paste the code if you need to make out if i have made any error. Thanks for the help ! -
Django Creating a App Inside of a App And Load It Inside of Settings
I want to create a app inside of a app and use it but I seem to can't get it to load in settings.py under INSTALLED_APPS but I can't seem to get it to work I tried account.useprofile.apps.UserprofileConfig - django.core.exceptions.ImproperlyConfigured: Cannot import 'userprofile'. Check that 'account.userprofile.apps.UserprofileConfig.name' is correct." account.userprofile.UserprofileConfig account.apps.userprofile.UserprofileConfig I am trying to get the app inside of the account app called userprofile but I can't successfully get it to load under settings.py files: mysite - * django files * account - userprofile -
Cannot query foreign key field in GraphQL
I'm using graphene-django framework for GraphQL. All fields I can retrieve except foreign key // models.py from django.db import models from django.contrib.auth.models import User from users.models import UserProfile class Video(models.Model): title = models.TextField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) // schema.py class VideoType(DjangoObjectType): class Meta: model = Video My query is like this query { home_videos { title description author } } Following is error message in GraphQLView. Cannot query field author on type VideoType -
Errors running django tests after python 2/3 upgrade, unittest.loader._FailedTest
I'm helping my group upgrade their application from python 2 to 3, and am running into errors with the unit tests. When I run the tests with python3 manage.py test groupapp --settings=settings.deploy_dev I get the errors below. But if I run with python3 manage.py test groupapp.tests --settings=settings.deploy_dev the errors do not occur. Its worth noting that these errors occur even after I deleted all our tests from the tests folder, and as far as I can tell they aren't connected to an actual test case. I don't understand the difference between these two calls in python 3. In python 2 if I run the two calls I get the same result (no test failures). groupapp_v2.groupapp.admin (unittest.loader._FailedTest) ... ERROR groupapp_v2.groupapp.models (unittest.loader._FailedTest) ... ERROR ====================================================================== ERROR: groupapp_v2.groupapp.admin (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: groupapp_v2.groupapp.admin Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/Users/matthew/bitbucket/consortium-website/groupapp_v2/groupapp/admin/__init__.py", line 73, in <module> admin.site.register(Grid, GridAdmin) File "/Users/matthew/virtualenv/groupapp-python3.6/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 110, in register raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model Grid is already registered ====================================================================== ERROR: groupapp_v2.groupapp.models (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: groupapp_v2.groupapp.models Traceback (most recent … -
How do I pull a part of an object and pass it through context to ouput to page. Django
Here is my object: [{'address_components': [{'long_name': '900', 'short_name': '900', 'types': ['street_number']}, {'long_name': 'West Wall Street', 'short_name': 'W Wall St', 'types': ['route']}, {'long_name': 'Janesville', 'short_name': 'Janesville', 'types': ['locality', 'political']}, {'long_name': 'Rock County', 'short_name': 'Rock County', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Wisconsin', 'short_name': 'WI', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}, {'long_name': '53548', 'short_name': '53548', 'types': ['postal_code']}, {'long_name': '3574', 'short_name': '3574', 'types': ['postal_code_suffix']}], 'formatted_address': '900 W Wall St, Janesville, WI 53548, USA', 'geometry': {'location': {'lat': 42.6803769, 'lng': -89.03211}, 'location_type': 'RANGE_INTERPOLATED', 'viewport': {'northeast': {'lat': 42.6817258802915, 'lng': -89.0307610197085}, 'southwest': {'lat': 42.6790279197085, 'lng': -89.03345898029151}}}, 'place_id': 'Eig5MDAgVyBXYWxsIFN0LCBKYW5lc3ZpbGxlLCBXSSA1MzU0OCwgVVNBIhsSGQoUChIJFzIpc5QZBogRoK3T0RxPudkQhAc', 'types': ['street_address']}] I just need the {'lat': 42.6803769, 'lng': -89.03211} part. Here is my view: def home(request): posts = Listing.objects.all().filter(is_live=1) context = {'posts': posts} return render(request, 'home.html', context) Here is my html: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Set the size of the div element that contains the map */ #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <!--The div element for the map --> <div id="map"></div> <script> // Initialize and add the map function initMap() { var … -
How to safely delete a model field?
I have a field in a model in django. Last time I tried to remove it (and ran migrations), it ended up making everything break. How could I go about properly removing a field in a model? # here's an example model class Sheet(models.Model): model1 = models.IntegerField() model2 = models.IntegerField() model3 = models.IntegerField() # here's the same model with a deleted field (what I want to do) class Sheet(models.Model): model1 = models.IntegerField() model2 = models.IntegerField() -
How to update a value with signals in Django
Im trying to update an attribute with a signal with post_save, but im getting an ExceptionType: TypeError "int() argument must be a string, a bytes-like object or a number, not 'Pedido'", and I dont know what is this error. This is my signal: @receiver(post_save, sender=Venta) def update_thread(sender, **kwargs): instance = kwargs['instance'] obj = Pedido.objects.get(pk=instance.pedido) obj.estado = "Finalizado" ob.save() Also check this: What it can be the error? -
Lookup error on heroku app when trying to use stanford NER
Consumers.py import json import os import nltk nltk.download('popular', quiet=True) import pandas as pd from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from . import tasks from nltk.tag import StanfordNERTagger from itertools import groupby from chat.models import Event #from django.contrib.sessions.backends.db import SessionStore from django.conf import settings from importlib import import_module #from channels.sessions import channel_session os.environ['CLASSPATH'] = 'static/stanford-ner.jar' os.environ['STANFORD_MODELS'] = 'static/ner' java_path = 'static/java.exe' os.environ['JAVAHOME'] = java_path stanford_classifier = 'static/ner/english.all.3class.caseless.distsim.crf.ser.gz' st = StanfordNERTagger(stanford_classifier) The stanford-ner.jar, ner, java.exe, english.all.3class.caseless.distsim.crf.ser.gz are located as coded above in the folder structure, Despite this I am facing error as LookupError: NLTK was unable to find stanford-ner.jar! Set the CLASSPATH environment variable. Kindly help with the issue as the app is failing when trying to deploy on heroku. Thanks in advance -
Django - Suspending/deactivating an account for N amount of seconds
In my Django application, If the user enters the wrong password more than 7 times, then I want to suspend/deactivate their account for 10 seconds. I perform an If statement to see if the wrong password has been inputted more than 7 times, and that works fine. Inside the if statement, I want to set user.is_active to False so they cannot login for 10 seconds. After 10 seconds has passed, I want user.is_active to be set back to True so they can attempt to login again. How would I implement this functionality? Thank you. -
How can I display a geocoded Google Maps address as a marker on my map?
I used gmaps.geocode python library to produce this: [{'address_components': [{'long_name': 'Alabaster', 'short_name': 'Alabaster', 'types': ['locality', 'political']}, {'long_name': 'Shelby County', 'short_name': 'Shelby County', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Alabama', 'short_name': 'AL', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}], 'formatted_address': 'Alabaster, AL, USA', 'geometry': {'bounds': {'northeast': {'lat': 33.2717601, 'lng': -86.752692}, 'southwest': {'lat': 33.1672109, 'lng': -86.8732169}}, 'location': {'lat': 33.2442813, 'lng': -86.8163773}, 'location_type': 'APPROXIMATE', 'viewport': {'northeast': {'lat': 33.2717601, 'lng': -86.752692}, 'southwest': {'lat': 33.1672109, 'lng': -86.8732169}}}, 'partial_match': True, 'place_id': 'ChIJU_ollPgliYgRUDCwXEedAQc', 'types': ['locality', 'political']}] Using Django I can spit out this data for every listing saved in my database. What is the best way of having every geocoded address displayed on my map: html: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Set the size of the div element that contains the map */ #map { height: 700px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <body> <!--The div element for the map --> <div id="map"></div> <script> // Initialize and add the map function initMap() { // The location of Uluru var uluru = {lat: -25.344, lng: 131.036}; // The map, … -
Auto assigning 3 types of user roles on sign up in Django
I am new to Django and trying to create a website that has two user roles primary and member. Member (users) are invited to the website via email. Is there any way to auto assign roles by submitting the sign up form. Right now on the website, all users are directed to the same sign up form on the same url path. Is that an issue in accomplishing my goal? Users models.py import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from rest_framework.reverse import reverse from testapp.common.models import BaseModel class User(AbstractUser, BaseModel): USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] email = models.EmailField(verbose_name="email address", max_length=255, unique=True) first_name = models.CharField(_("First name"), max_length=255) last_name = models.CharField(_("Last name"), max_length=255) is_parent = models.BooleanField('parent status', default=False) is_village_member = models.BooleanField('village member status', default=False) def __str__(self): return self.email def get_api_url(self, request=None): kwargs = {"uuid": self.uuid} return reverse("user-detail", kwargs=kwargs, request=request) @cached_property def stripe_customer(self): return self.djstripe_customers.first() @property def stripe_sources(self): if self.stripe_customer is None: return [] return self.stripe_customer.sources def save(self, **kwargs): if self.pk is None: self.uuid = uuid.uuid4() self.username = str(self.uuid) return super().save(**kwargs) Families models.py from allauth.account.signals import user_signed_up from django.db import models from django.db import transaction from django.db.models.signals import … -
Display fields from foreign key linked model django
So I've created an API with the Django rest framework. I have a simple model relationship which is, User -> Posts. Users are linked to the posts because the user is the AUTHOR of a post. All I want to do is display the username associated with a POST in my rest API. How do I reference other fields from a model that I linked as a foreign key? IF I have a user model that has a username, profile picture and email, how can I display those in my Post model??? Here is an example of what I am trying to do with the models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() image = models.ImageField(default='default.mp4', upload_to='video_thumbnails') videoFile = models.FileField(default='default.mp4', upload_to='videos') date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User , #Something to get the username here, on_delete=models.CASCADE) Right now this displays { "title": "HOLROYD SWIPE ACCESS(CS ROOMS)", "content": "Yeet", "image": "http://127.0.0.1:8000/media/video_thumbnails/Screenshot_from_2019-08-03_23-37-50.png", "videoFile": "http://127.0.0.1:8000/media/videos/Screenshot_from_2019-08-03_23-37-52.png", "date_posted": "2019-10-22T21:01:07Z", "user": 1 } All I want it to do is display the name of the user instead of the USER ID which is 1 in this case. I JUST want it to look like this instead { "title": "HOLROYD SWIPE ACCESS(CS ROOMS)", … -
How can I start project on domain using gunicorn and nginx?
I have a domain (example.com). How can I run project on this domain using nginx and gunicorn. I'm use Python 3.6 and Django 2.2. Nginx /etc/nginx/sites-available/example.com server { listen 80; listen [::]:80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/project; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful Gunicorn gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/home/project ExecStart=/home/project/projectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Django /home/project/project/settings ALLOWED_HOSTS = ['example.com', 'localhost'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': '1q2w3e4r', 'HOST': 'localhost', 'PORT': '', } } -
Django: For loop inside href attribute
I am playing around with Django, and I wonder if I have pagination together with a search including multiple checkboxes, how can I can pass both the query and the selected checkboxes to the next page. For example, when I provide the link for the next page I want to have something like: {% if results.has_next %} <a href="?page={{ results.next_page_number }}&q={{ request.GET.q }}{{&c=checkbox for checkbox in request.GET.getlist('c')}}">next</a> {% endif %} Please let me know if I need to elaborate a bit more on what I need. -
Getting Heroku Error H10 (App crashed) when pushing
Here is the logs file: (venv) C:\Users\Wasim Rana\PycharmProjects\website>heroku logs --tail 2019-10-22T20:59:23.053699+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path= "/" host=wasimrana.herokuapp.com request_id=8a232e19-10dd-48c8-841c-0f3ece6f54e1 fwd="103.196.233.9" d yno= connect= service= status=503 bytes= protocol=https -
ModuleNotFoundError: No module named 'crispy_forms'
I have installed crispy_forms on both python2 and python3, however, I am still getting an error... I believe I know what the problem is, I just do not know how to solve it. For some reason, I have python2.7, python3.5, and python3.7 installed. When I install crispy_forms using pip, it installs it for python2.7. When I install crispy_forms using pip3, it installs it for python3.5. However, my Django project uses python3.7, hence the error. How can I get crispy_forms over to 3.7? I have already put INSTALLED_APPS [ . . . 'crispy_forms', ... ] -
Django Conditional Choices
I am new to Django and have been working on a project where I am trying to have choice fields dependent on bool values attached to the current user. I have this in the model user = models.OneToOneField(user_model, on_delete=models.CASCADE) #### I_CAT = models.BooleanField(default=False) I_DOG = models.BooleanField(default=False) I_PAW = models.BooleanField(default=False) I_OPTIONS = [ [('star'), ('Star')], When(I_CAT=True, then=Value([('cat'), ('Cat')])), ] icon = models.TextField(choices=I_OPTIONS, default='star') I am looking to have it so that when the value I_CAT for the current user is set to True it will add that option to our choices list which is used as choices list for icon. I don't really know the best way to approach this. I have tried to use When and if statements in the model file itself and also in the views for this page. I haven't managed to get anything to work yet the closest I got was this if I_CAT: I_OPTIONS.append([('cat'), ('Cat')]) This succeeds in adding something to the options list but it doesn't actually check if I_CAT is true or not and just adds it every time no matter what. I also read on another post that if statements inside a model are a bad idea so idk. Any guidance would … -
Why is the GET request for static files returning 404, except for base.css which returns a 200
I am in the process of deploying a simple website written with Django to AWS Elastic Beanstalk. Everything seems to be working, except for some of my static resources (CSS + image files) returning 404 errors. I have run python manage.py collectstatic to organize all my static resources as follows: -project |-... |-static | |-admin | | |-... | | | |-app1 | | |-style.css | | |-img1 | | | |-app2 | | |-style.css | | | |-project | | |-base.css |-... I have identified two EB logs: "GET /static/project/base.css HTTP/1.1" 200 "GET /static/app1/style.css HTTP/1.1" 404 base.css is served up fine, but when attempting to retrieve app/style.css, I get an error, despite the path matching the structure I have above. Any reason why this would be? -
Django Filter Queries in List by the last x Days with Timedelta shows only Queries of substracted Day, not full Range
i am trying to make a list to show the queries of the last 100 Days. If iam using Timedelta in the filter i can list the queries of the substracted Day. Only the exact Day. But i want to list all Queries between the Date in the Datefield and the Day in Timedelta Filter. What iam doing wrong? class Appointment(models.Model): Appointment_Company = models.ForeignKey(Company, on_delete=models.CASCADE) Appointment_Theme = models.CharField(max_length=200) Appointment_Info = models.TextField() Appointment_Date = models.DateField(default=datetime.today) def __str__(self): return self.Appointment_Theme class AppointmentView(DetailView): template_name = 'timecheck/Appointment_100.html' model = Company def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['Company_list'] = Company.objects.all() context['Appointment_list'] = Appointment.objects.filter(Appointment_Date=datetime.today() - timedelta ( days = 100 )) print (context) return context -
How to send emails to verify users using django-rest-auth
I set up Django custom registration using the Django-rest-auth, I also want to verify the email by sending emails which I heard that Django all auth does out the box. but this doesn't seem to work. I don't know if to install any package or what. I created a custom register which inherits from Django-all-auth, but it doesn't seem to work still. my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' # EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email my custom register views.py from rest_auth.registration.views import RegisterView from django.contrib.auth import get_user_model class CustomRegisterView(RegisterView): def …