Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get all items with all properties using django multi-table inheritance and django rest framework
I'm using Django multi-table inheritance: class Parent(): common_property = ... class Child1(Parent): child1_specific_property = ... class Child2(Parent): child2_specific_property = ... And want to expose the list of all items on the same endpoint. If I make a basic serializer and view for the Parent model, I would just get the common properties (the ones living on that model), but in this case I want to get all child-specific properties for every item. Ideally something like this: items { type_1: { common_property child1_specific_property } type_2: { common_property child2_specific_property } } Am I missing any trivial way to do this? -
How To Get Rid Of "Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)" in Pychar+Django
When I run my test suite using pycharm for a django app in my local machine, at certain test I got: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) If I run that test in isolation using pycharm, it succeeds, which means there's not a problem in the app or test. If I disable that particular test, down the line I get the same error, in a different test, this one a dummy test! This seems to indicate that it's a problem with pycharm itself. The full test suite succeeds in the CI environment. I tried some suggestion from other stackoverflow questions, which didn't solve the issue: Unticking the Qt box in PyCharm Settings (Build, Ex... -> Python Debugger) Uninstalling python3-pyqt5 (same link as above): Pyqt is not installed in my local machine. Ticking gevent compatible in Pycharm Settings My Environment: python 3.7.3, djando 2.2.8, Pycharm 2019.2.4 (professional edition) -
django.core.exceptions.ImproperlyConfigured: i get this erro after i include path('", include('calc.urls'))
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] -
How to perform full text search in django?
For example i have a title How to use User Model in Django and I search with keyword only django then it returns all the titles which has django which is fine but when i enter a keyword like django user model then it returns none.How can I solve this Any help would be appreciated views.py def search_blogs(request): q = request.GET.get('q') if q: blogs = Blog.objects.filter(title__icontains=q).order_by('-created') return render(request,'blog/search_blogs.html',{"blogs":blogs,'q':q}) else: messages.error(request,'Please enter some keyword to search') return redirect('blog:blogs') template <form action="{% url 'blog:search_blog' %}" class="search-form"> <input type="text" name="q" placeholder="Search blogs" align="center" > <input type="submit" value="Search" class="btn-sm btn-info > </form> -
gunicorn + django - https requests get stuck
I use gunicorn as HTTP server and Django as the app behind. I didn't set up SSL at all. When I make a https request to my app the process seems to be waiting for something and the request is stucked. Since the app runs in a single thread and single worker other requests get blocked until I cancel my https request. How can I forbid https at all in gunicorn? I don't/can't use nginx at all to filter incoming requests. -
How to get a user to register only after admin accepts it in django?
I want to make a user, when registering in my application, have to choose a group (if it does not already exist, that he can create one and become admin automatically) and, when choosing a particular group, wait for admin accept it. How can I do this using django? Thanks in advance! -
TypeError: expected string or bytes-like object although datetime field not used Django
I'm trying to migrate my datas, but django returns me TypeError: expected string or bytes-like object error, although I just tried using datetime once, then deleted it, but still it returns an error. 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) is_accepted = models.BooleanField(default=False) photo = models.FileField(upload_to='static/applicant_photos') def __str__(self): return self.name an error: Operations to perform: Apply all migrations: admin, auth, ccapp, contenttypes, sessions Running migrations: Applying ccapp.0003_applicant_birth_date...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 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards … -
Django gettext and gettext_lazy both imported with same name
In Django source code, gettext() and gettext_lazy() are both imported as _: from django.utils.translation import gettext, gettext_lazy as _ How does that import method work, and which kind of function benefits from it? -
Django creating database entries without model defined
I am writing a small application. I will have two endpoints: /generate - Accepts only POST /exercise - It has GET, and PUT I have the following model: class Exercise(models.Model): created = models.DateTimeField(auto_now_add=True) question = models.TextField(default='') answered = models.BooleanField(default=False) answer = models.TextField(default='',blank=True) class Meta: ordering = ['created'] def __str__(self): return self.question Here are the simple things I want to do on each endpoints. On /generate I want to generate 10 exercises. On /exercise - GET I want to return unanswered question/s On /exercise - PUT I want to update "only the answer" and set "answered" field. Here's my serialiser # snippets/serializers from rest_framework import serializers from .models import Exercise class ExerciseSerializer(serializers.ModelSerializer): class Meta: model = Exercise fields = ('id', 'question', 'answer') class GenerateSerializer(serializers.ModelSerializer): class Meta: pass model = None model = Exercise exercise = Exercise() fields = ('id', 'question', 'answer') Finally the view: from django.shortcuts import render # Create your views here. # snippets/views.py from rest_framework import generics from .models import Exercise from .serializers import ExerciseSerializer, GenerateSerializer class ExerciseList(generics.ListAPIView): queryset = Exercise.objects.all() serializer_class = ExerciseSerializer class ExerciseDetail(generics.RetrieveUpdateAPIView): queryset = Exercise.objects.all() serializer_class = ExerciseSerializer class GenerateExercise(generics.CreateAPIView): # TODO: check if I need query set for create only method # queryset = … -
HTML Checkbox just returns None as value to my Django views
I have a very basic question. I created a checkbox form in HTML and I want to pass the Checkbox data to my Django views. Now I have the problem, that i just get returned None as a value and i don't know why. HTML code: <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" name="checkbox" id="bb1"> <label class="form-check-label" for="bb1"> </label> </div> </div> checkbox_input = request.GET.get("bb1") print(checkbox_input) should't the output be something like "True", "False" or "on"? If I render my homepage and submit something, the link looks like this: 127.0.0.1:8000/?value=Hous&checkbox=on Why can't I grab the value "on"? I'm sorry I'm so sloppy about the way I phrase things here. I hope you guys can still help me :) -
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?