Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-auth Custom Serializer or custom Model
Django Rest Framework how can i configure rest-auth to work with custom Serializer or custom model that takes in a name field instead of the default username. -
pre_delete : how to get back to list display after ProtectedError
I need to protect just 1 record from deletetion. I Have : @receiver(pre_delete, sender=HotspotGroup, dispatch_uid='question_delete_signal') def pre_delete_hotspotgroup(sender, instance, using, **kwargs): if instance.is_default : raise ProtectedError('DEFAULT Group can not be deleted', instance) It work in term of 'prevent deletetion'. But not so nice things is it display 'Server Error (505)'. How to just go back to list display? Or more nice : How to Popup/display the warning and getback to list display? Sincerely -bino- -
How to create specific django-model field, contains a date and unique number per day?
Sorry for my english, please!) I create a internet-shop on django and have a next problem. How to create a django model-field for order`s number, contains a date and unique number per day? This option is described in the assignment and others will not suit me. -
Optimize usage of Subquery
I'm using the Django ORM and created the following query. However it takes about 1:20 min to finish. User.objects.annotate( revenue=Sum("payments__total")), first_order_date=Subquery( User.objects.filter( pk=OuterRef("pk"), orders__status="done" ) .annotate(first_order_date=Min("orders__created")) .values("first_order_date"), output_field=DateTimeField(), ), ) Does someone have an idea how to optimize it? -
Django-channels sending message to group
I'm writing an app where I need to use sockets. To handle it I use django channels, but i can't broadcast message to group. class waiting(WebsocketConsumer): def connect(self): self.channel_layer.group_add( 'my_group_name', self.channel_name ) if <condition>: self.channel_layer.group_send( # This does not give any effect. I'm sure the condition is satisfied. 'my_group_name', { 'message' : 'succes' } ) self.accept() self.send(json.dumps({'message' : 'message'})) # This works perfect def disconnect(self, close_code): self.channel_layer.group_discard( 'my_group_name', self.channel_name ) What I have wrong? I alredy read many tutorials and also documentation but I didn't find any solution. What I should change to make this code work as I want? I'm using channels == 2.3.1 and django 2.2.6. -
How to do Log System on Django?
I researched a lot of topics and i read some blogs. But i can't best way to do log system. I want to do log system that it can record users actions such as delete,update and create. Especially, this system should be record before and after changes like django admin in history. For example; -
Django add data to database from HTML page
Every applicant should enter their data from HTML page and this datas must insert to database. I think I did everything right, but datas are not shown in database. Here are my codes. models.py: class Applicant(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=30) phone = models.CharField(max_length=15) email = models.EmailField(max_length=40) motivation_letter = models.TextField(max_length=200) def __str__(self): return self.name views.py: def apply(request): if request.method == "POST": if request.POST.get('motivation_letter'): applicant = Applicant() applicant.name = request.POST.get('name') applicant.surname = request.POST.get('surname') applicant.phone = request.POST.get('phone') applicant.email = request.POST.get('email') applicant.motivation_letter = request.POST.get('motivation_letter') applicant.save() return render(request, 'index.html') HTML: <form method="POST"> {% csrf_token %} <label>Ad</label><br /> <input type="text" name="name"><br /> <label>Soyad</label><br /> <input type="text" name="surname"><br /> <label>Telefon nömrəsi</label><br /> <input type="number" name="phone"><br /> <label>Elektron poçt</label><br /> <input type="email" name="email"><br /> <label>Something else</label><br /> <textarea class="smth-else-textarea" cols="30" rows="10" name="motivation_letter"></textarea><br /> <input type="submit" value="Göndər" class="apply-button"/> </form> -
Dajngo Setting up DigitalOchean Postgre "DATABASES = {" ERORR
I am following https://www.udemy.com/course/the-ultimate-beginners-guide-to-django-django-2-python-web-dev-website/learn/lecture/9517168#overview guide to build aDjango website on a Digital Ocean Server with Postgres database. The guide that the teacher follows is the official Digital Ocean setup guide https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04#creating-and-configuring-a-new-django-project Everything was fine until I am trying to Migrate the project on the server side: 1st syntax that I have run in the terminal python manage.py makemigrations 1st ERROR File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax 2nd syntax that I have run in the terminal python3 manage.py makemigrations 2nd ERROR Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/djangodeploy/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/djangodeploy/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/home/djangodeploy/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/djangodeploy/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/djangodeploy/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/djangodeploy/portfolio-project/portfolio/settings.py", line 137, in … -
django channels and restframework integration
How to use channels or socket.io with django restapi for registration which include the fields such as name, phone, email? Is it necessary to use template to create socket? -
Using Django to send Email to a User at a scheduled time
Currently trying to schedule a mail in django 15 Minutes to the start_time of the meeting, a email notification should be sent to the visitor, i really don't know how to go about this. Are there schedulers i can use and how do i specify 15 Minutes before a time. See my model structure below: #Model for Visitor Table class Visitor(models.Model): visitor_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50 , blank=False, null=True) last_name = models.CharField(max_length=50 , blank=False, null=True) email = models.EmailField(max_length=50, blank=False) company = models.CharField(max_length=50, blank=False) phone_number = models.CharField(max_length=100, blank=False) picture_url = models.ImageField(upload_to='pictures/%Y/%m/%d/', max_length=254, blank=True, default='none', null=True) blacklist = models.BooleanField(default=False) def __str__(self): return '{} {}'.format(self.first_name, self.last_name) #Model for VisitorMeeting table... This holds referencial key to both visitor table and meeting table #Transactional table for Visitor and Meeting Table class VisitorMeeting(models.Model): visitor_id = models.ForeignKey(Visitor, on_delete=models.CASCADE) meeting_id = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name='visitors') arrival = models.DateTimeField(blank=True, null=True) departure = models.DateTimeField(blank=True, null=True) checkin_status = models.BooleanField(default=False, null=True) objects = VisitorQuerySet.as_manager() -
How to use django AppConfig.ready()
I can't seem to get my ready function under my AppConfig to work. Here is my code from apps.py: from django.apps import AppConfig from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete from django.db.models import Max, Count from .models import Player, PlayerStats, TotalLevels class BloxorsConfig(AppConfig): name = 'bloxors' def ready(self): MaxCurrentLevel = PlayerStats.objects.aggregate(max_levels=Max('level_no'))['max_levels'] PlayerCount = Player.objects.aggregate(count_players=Count('player_name', distinct=True))['count_players'] print(MaxCurrentLevel, PlayerCount) I read in the documentation that ready() gets called each time at the beginning of manage.py runserver but then why does nothing happen. Ideally I was expecting it to print the two values MaxCurrentLevel, PlayerCount. Can someone point out what I am doing wrong and help solve this? As always, I greatly appreciate your answers! -
Navbar inherited from base.html using Django templating doesn't render styles properly
I'm implementing a navbar and I wanted to use django templating for the DRY principle. The first picture is its appearance before templating, the second one is after templating. (https://imgur.com/a/FOEqKFB) How do I get the css files to render properly in the inherited html file? I thought it was a case of me not calling the CSS files in base.html (like this one: another similar answer), but I checked the code for base.html and I've already called the Bootstrap CDN for the navbar styles on the header. What went wrong in my code? This is the relevant code for the problem: base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <title>{% block title %}Title{% endblock title %}</title> {% block head_favicon %} <link rel="icon" type="image/x-icon" href="/favicon.ico"> {% endblock head_favicon %} {% block head_meta %} {% block head_meta_charset %} <meta charset="UTF-8"> {% endblock head_meta_charset %} {% block head_meta_contentlanguage %} <meta http-equiv="X-UA-Compatible" content="ie=edge" value="en-US"> {% endblock head_meta_contentlanguage %} {% block head_meta_viewport %} <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0"> {% endblock head_meta_viewport %} {% endblock head_meta %} {% block head_css %} {% block head_css_site %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% endblock head_css_site %} {% block head_css_section %}{% endblock head_css_section %} {% block head_css_page … -
django post_save causing IntegrityError - duplicate entry
I need help to fix the issue IntegrityError at /admin/gp/schprograms/add/ (1062, "Duplicate entry '65' for key 'PRIMARY'") I am trying to insert a row into a table SchProgramForStates (whenever new entry gets added into a model SchPrograms) with two columns state_id (taking it from django session) and program_id trying to take it from SchPrograms model class . It works fine when I only save SchProgram table so I feel problem is with the below code. Please help me to fix this. @receiver(post_save, sender=SchPrograms, dispatch_uid="my_unique_identifier") def my_callback(sender, instance, created, *args, **kwargs): state_id = state_id_filter #its a global variable if created and not kwargs.get('raw', False): pfst_id = SchProgramForStates.objects.create(program_id=instance.program_id, state_id=state_id) pfst_id.save(force_insert=True) -
How to run Object_detection_image.py, which is outside my django project?
I am using windows 10 Django version: 2.1.1 with Python version: 3.5 I have my TensorFlow object detection API, that trained my images which is totally outside of my Django project. However, I created my Django project after that in the same environment that I had my TensorFlow object detection models. Both of them with the same (python version: 3.5). Before creating the Django webpage, I always needed to run my 'Object_detection_image.py' from anaconda prompt line, otherwise, I got an error. My question is: how I can specify my Object_detection_image.py path directory in the setting.py in Django using anaconda prompt line? When I write my directory like this: C:\tensorflow1\models\research\object_detection then how I can use anaconda prompt line in this path? because if I write it like this, it doesn't work. please help me. Thank you. -
Create or Update Update a many-many relationship in Django Graphene
I had an issue of not being able to update Models with foreign keys in python django, below is my rating class class Rating(Timestamp): user = models.ForeignKey(User, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(10)]) def __str__(self): return f'{self.movie} : {self.rating}' class Meta: unique_together = (("user", "movie"),) I was trying to update it via the below mutation class AddEditRating(graphene.Mutation): rating = graphene.Field(RatingType) class Arguments: movie = graphene.ID() user = graphene.ID() rating = graphene.Float() def mutate(self, info, **arg): user = arg.get("user") movie = arg.get("movie") rating = arg.get("rating") obj, created = models.Rating.objects.update_or_create( user=user, movie=movie, defaults={"rating": rating} ) return AddEditRating(rating=obj) When i hit the mutation thought I get a warning that the user must be of UserType mutation { addEditRating(movie: 1, user: 3, rating: 9.7) { rating { id rating } } } Finally This is the error that i am getting "errors": [ { "message": "Cannot assign \"'3'\": \"Rating.user\" must be a \"User\" instance.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "addEditRating" ] } ], Any help on this topic would be highly appreciated. also is there a better way to create update models? -
Why am I getting botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden?
I'm getting this traceback when trying run run manage.py collectstatic as part of an AWS ElasticbeanStalk deploy using an S3 bucket. File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 162, in handle if self.is_local_storage() and self.storage.location: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 216, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/utils/functional.py", line 213, in inner self._setup() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 491, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "/opt/python/bundle/3/app/src/core/storage.py", line 64, in __init__ super(StaticStorage, self).__init__(*args, **kwargs) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 376, in __init__ self.hashed_files = self.load_manifest() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 386, in load_manifest content = self.read_manifest() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 380, in read_manifest with self.open(self.manifest_name) as manifest: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/files/storage.py", line 33, in open return self._open(name, mode) File "/opt/python/run/venv/local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 464, in _open f = S3Boto3StorageFile(name, mode, self) File "/opt/python/run/venv/local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 72, in __init__ self.obj.load() File "/opt/python/run/venv/local/lib/python3.6/site-packages/boto3/resources/factory.py", line 505, in do_action response = action(self, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__ response = getattr(parent.meta.client, operation_name)(**params) File "/opt/python/run/venv/local/lib/python3.6/site-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/botocore/client.py", line 661, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An … -
Display user`s protrait from model in template in django
I want to display the the user protrait of the user in the templates. models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='user/%Y/%m/%d/', blank=True) views.py @login_required def dashboard(request): # Display all actions by default actions = Action.objects.exclude(user=request.user) following_ids = request.user.following.values_list('id', flat=True) if following_ids: # If user is following others, retrieve only their actions actions = actions.filter(user_id__in=following_ids) actions = actions.select_related('user', 'user__profile')\ .prefetch_related('target')[:10] return render(request, 'account/dashboard.html', {'section': 'dashboard', 'actions': actions}) tempate: <img src="{{ Profile.photo.url }} " height="40" width="40"/> -
How to resolve django admin error with 302 problems?
I am continuously getting error while trying to log in to django admin page. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 07, 2019 - 13:53:40 Django version 3.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [07/Dec/2019 13:53:42] "GET / HTTP/1.1" 404 2027 [07/Dec/2019 13:53:47] "GET /admin HTTP/1.1" 301 0 [07/Dec/2019 13:53:47] "GET /admin/ HTTP/1.1" 302 0 [07/Dec/2019 13:53:47] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [07/Dec/2019 13:53:47] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [07/Dec/2019 13:53:47] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [07/Dec/2019 13:53:47] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18052 [07/Dec/2019 13:53:47] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [07/Dec/2019 13:53:47] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [07/Dec/2019 13:53:47] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [07/Dec/2019 13:53:59] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 And after this it is automatically closing. -
Django template object not showing
So I've come across this weird thing. I can't pass data within the template unless it's within the forloop. for example.. I can pretty much print a variable just within a for loop but something outside a forloop is not showing up. {{listings.make}} <<<< This isn't printing {% for listing in listings %} <p>{{listing.make}}</p> <<<< This is printing {% endfor%} def search(request): queryset_list = Vehicle.objects.all() context = { 'listings': queryset_list } return render (request, 'mainapp/new_listing.html', context) class Vehicle(models.Model): year = models.CharField(max_length=4, choices=YEAR) make = models.CharField(max_length=50, default="") model = models.CharField(max_length=50, default="") version = models.CharField(max_length=50, default="") description = models.TextField(max_length=50, default="") def __str__(self): return self.make Any idea what is going on actually. As you can see I m using a function-based view. Thank you -
Comparing value from html to context
I need to compare a value (variable) extracted from a page to context. For example: Color is a dropdown selection. $(document).ready(function(){ $("#color").change(function() { var selected_color = $(this).val() ; {% if context_value == selected_color %} .. do something {% endif %} }); Is this possible ? If not, is there some solution for such case ? -
How can update many_to_many relational fields with bulk_update() method in Django?
How can I update many_to_many fields with the bulk_update method in Django? Code: get_user_model().objects.using('default').bulk_update( User.objects.using('default').all(), ('password','groups') ) Error: {ValueError}bulk_update() can only be used with concrete fields. -
How to display Django BooleanFields selected true in template?
everyone! I created a model object. This object has several boolean fields. # models.py class TeamCharacteristic(models.Model): team = models.ForeignKey('Teams',on_delete=models.CASCADE) power1 = models.BooleanField(null=True, blank=True) power2 = models.BooleanField(null=True, blank=True) power3 = models.BooleanField(null=True, blank=True) power4 = models.BooleanField(null=True, blank=True) power5 = models.BooleanField(null=True, blank=True) class Meta: verbose_name = 'Team style' verbose_name_plural = 'Teams style' def __str__(self): return "{} 's style".format( self.team, ) Some of them are right and others are wrong. I want to show only the fields that have the correct value in the template. How can I do this in a shorter way instead of checking each field individually? # views.py from django.shortcuts import render, get_object_or_404 from .models import Matches from denemee.apps.home.models import TeamCharacteristic def matches_details(request, page_id=None, team=None, **kwargs): m_detail = get_object_or_404(Matches, id=page_id) home_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.h_team) away_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.a_team) payload = { 'm_detail': m_detail, 'home_team_chr': home_team_chr, 'away_team_chr': away_team_chr } return render(request, 'match_detail.html', payload) -
Working with autofield and unique_constraint Django
My models.py of class app: Teacher and StudentInfo will store their respective details. from form.models import StudentInfo from teacherform.models import Teacher class ClassRoom(models.Model): standard = models.CharField(max_length=50) section = models.CharField(max_length=50) teacher = models.OneToOneField(Teacher, on_delete = models.CASCADE) class ClassRoomStudent(models.Model): classRoom = models.ForeignKey(ClassRoom, on_delete=models.CASCADE) rollNumber = models.AutoField() student = models.OneToOneField(StudentInfo, on_delete=models.CASCADE) I want to auto increment 'rollNumber' when I add new row to my ClassRoomStudents, but if the student is from different class then rollNumber count should reset it should start again. As different students can have the same roll number if they are from different classrooms. I am aware of unique constraint. But even after unique_constraint I am still not sure how my rollNumber will increment of different classrooms. Like won't it be continuosly incrementing the rollNumber number which will obviously be unique for different or same class ? -
Is there any way to filtering the queryset dynamicaly in django forms for a foreignkey correct?
I am creating a form for this model class SemAssign(models.Model): staff = models.ForeignKey(User, on_delete=models.CASCADE) semester = models.ForeignKey(Subject, on_delete=models.CASCADE, default=1) def __str__(self): return f'{self.staff.username}' and my forms.py looks like class SemAssignForm(forms.ModelForm): class Meta: model = SemAssign fields = ['staff','semester'] And i made a queryset based on a user-defined filter as in my views.py def assign_sem(request): if request.user.is_staff: dept = request.GET.get('department') sem = request.GET.get('semester') form=SemAssignForm(request.POST) #form.fields['staff'].queryset = User.objects.filter(is_staff=True, profile__Department=dept) #form.fields['semester'].queryset = Subject.objects.filter(sem=sem) if form.is_valid(): SemAssign=form.save() return redirect('dashboard') When the query works perfectly the form is validated as wrong. And if i don't make query the form is validated successfully. I'm sure i missing somewhere in querying the foreignkey set. Can anyone sought me that? My friend suggested me with modelformset, but that is not my scope. I just want to filter the fields of SemAssign models based on a GET request filter. -
How can add multiple database for tests in Django tests
Question: How can I add multiple databases for testing in Django? When I ran my test suits I got this Error: AssertionError: Database queries to 'mig' are not allowed in this test. Add 'mig' to path_to_test_suit.MigrationServiceTest.databases to ensure proper test isolation and silence this failure. Here are my PostgreSQL settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_1_name', 'USER': 'db_1_user', 'PASSWORD': 'db_1_passwd', 'HOST': 'db_1_host', 'PORT': 'db_1_port', }, 'mig': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': db_2_name, 'USER': db_2_user, 'PASSWORD': 'db_2_passwd', 'HOST': 'db_2_host', 'PORT': 'db_2_port', }, } I use Django-nose for running test suits and use Django 2.2