Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST API best practice for views
I am trying to write a REST API with Django Rest Framework using the following models:- class Group(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() users = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Player) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="groups_owned", on_delete=models.PROTECT ) class Player(models.Model): group = models.ForeignKey(Group, related_name="players", on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="players", blank=True, null=True, on_delete=models.SET_NULL, ) slug = models.SlugField() class Game(models.Model): slug = models.IntegerField() group = models.ForeignKey(Group, related_name="games", on_delete=models.CASCADE) date = models.DateField() venue = models.ForeignKey(Venue, null=True, on_delete=models.PROTECT) The frontend that is going to consume this API is going to have pages like this:- * Group Details * Group Players * Group Games ... I know how to use a ModelViewSet to expose a view that can be used to return serialized data from a particular group but I'm not sure whether to create different actions to cover each separate page that's going to be required in the front end. I seem to have two options:- A single view (/api/groups//) which returns everything that any consumer might need - so the group name, owner etc. as well as all of the details of all of the games and players of that group. This seems more like the "proper" way to me. But it means that the … -
Pass value to uWSGI from Django application
How can I pass the request.user.username to the uWSGI logger from Django? I want to generate the below log: [pid: 1|app: 0|req: 2/38] **REQUEST.USER.USERNAME** Also, I'm using Nginx as the webserver. -
How to find the difference in multipolygon geometric area in geodjango?
I have two mulitpolygons (say a state and a district) and I want to find the difference in these two polygons and plot the difference in map as a vector layer in openlayer6. How can I calculate the difference using geodjango and return the geometry. Example code is : state = StateBoundary.objects.filter(id=1) dist = DistrictBoundary.objects.filter(id=10) I want something like this diff_area = state - dist I found the geodjango difference query here https://docs.djangoproject.com/en/3.2/ref/contrib/gis/functions/#django.contrib.gis.db.models.functions.Difference but dont get any example on how to do it using 'difference'. -
django app :shopping list with items taken from dropdown list and sum of items
I'm trying to develop new app in django. I'm really beginner. I have a little experience with django and python and very little, almost zero with java-script. Description of project: My first basic concept we can compare to shopping list. I want to create a dropdown list, which takes arguments(items) from database (model in django). this argument should be passed over to window below, where i can choose amount of items. _______________________________________________________________ | _________ | | item: |________| <:amount of item | | | |_____________________________________________________________| Next "item" and "amount of items" should be passed over to list below for example: item1 : amount of item1 item2 : amount of item2 item3 : amount of item3 item4 : amount of item4 sum of all amounts At the bottom o list i want to show sum of all items. I don't know where to start and I need help. Any ideas? -
DRF 3 - Making an Endpoint for Many to Many Table
I'm new to django rest framework and i am trying to understand how to make an endpoint to create and update a many to many relation table. models.py class OnlineClass(models.Model): ... teacher = models.ForeignKey(to=User, related_name='online_class', on_delete=models.CASCADE) students = models.ManyToManyField(to=User, through='Enrollment') ... class Enrollment(models.Model) online_class = models.ForeignKey(OnlineClass, on_delete=models.CASCADE) participant = models.ForeignKey(User, on_delete=models.CASCADE) For the user model i was extending it from the base user model from django. serializers.py class OnlineClassSerializer(serializers.ModelSerializer): participants = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),many=True) class Meta: model = OnlineClass fields = [ ... 'participants', ] extra_kwargs = {'participants': {'required': False,},} class EnrollmentClassSerializer(serializers.ModelSerializer): online_class = OnlineClassSerializer(many=True) participant = UserSerializer(many=True) class Meta: model = Enrollment fields = ['id','online_class','participant'] views.py class OnlineClassListAPIView(ListCreateAPIView): serializer_class = OnlineClassSerializer queryset = OnlineClass.objects.all() permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): return serializer.save(owner=self.request.user) def get_queryset(self): return self.queryset.all() class OnlineClassDetailsAPIView(RetrieveUpdateDestroyAPIView): serializer_class = OnlineClassSerializer permission_classes = (permissions.IsAuthenticated, IsOwner,) queryset = OnlineClass.objects.all() lookup_field = "id" def get_queryset(self): return self.queryset.all() Now what i would like to do is make an endpoint to add participants to the OnlineClass Table by adding data to the Enrollment Table, i have been looking other solutions but all i got was adding participants when the OnlineClass is created, but what i would like to do is adding the participants when the … -
Django Edit after Running like Webflow
I am working on a website which needs to be able to be edited after it is hosted. Thus it needs functionality where for example the text elements can be changed after it is hosted, just like this can be done with Webflow ?edit. Is there a way to do this besides giving all elements a variable name and editing them inside of the Django Admin dashboard? I have tried Django CMS but it only seems to work with websites build using Django CMS itself and not when I import existing templates. Is there anyone who has suggestions how this could be done? Thanks in advance -
Error running wsgi application: ModuleNotFoundError
I am trying to host my local web app on pythonanywhere. [Beginner to Django and web-development] I am facing the following error while launching the app: Error running WSGI application 2021-04-26 21:46:32,020: ModuleNotFoundError: No module named 'myapp' 2021-04-26 21:46:32,020: File "/var/www/username_pythonanywhere_com_wsgi.py", line 16, in <module> 2021-04-26 21:46:32,020: application = get_wsgi_application() 2021-04-26 21:46:32,020: 2021-04-26 21:46:32,020: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-04-26 21:46:32,020: django.setup(set_prefix=False) 2021-04-26 21:46:32,020: 2021-04-26 21:46:32,020: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2021-04-26 21:46:32,021: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-04-26 21:46:32,021: 2021-04-26 21:46:32,021: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-04-26 21:46:32,021: self._setup(name) 2021-04-26 21:46:32,021: 2021-04-26 21:46:32,021: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup 2021-04-26 21:46:32,021: self._wrapped = Settings(settings_module) 2021-04-26 21:46:32,021: 2021-04-26 21:46:32,021: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ 2021-04-26 21:46:32,021: mod = importlib.import_module(self.SETTINGS_MODULE) File locations: The settings.py file is located at: /home/username/WebDev/Website/Django/MyApp/myapp/myapp I have modified '/var/www/username_pythonanywhere_com_wsgi.py' file as: """ WSGI config for myapp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os import sys sys.path.append("/home/username/WebDev/Website/Django/MyApp/myapp") os.environ('DJANGO_SETTINGS_MODULE', 'myapp.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I have looked at the similar question on stackoverflow but still cant figure out what is wrong at my end. Any pointers/help would be appreciated. -
Field 'doors' expected a number but got ''
Error: Traceback (most recent call last): The above exception (invalid literal for int() with base 10: '') was the direct cause of the following exception: File "/home/andres/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/andres/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./wallacar_app/views.py", line 124, in getDoors doors = Coche.objects.exclude(doors__isnull=True).exclude(doors__exact='').order_by('doors').values_list('doors').distinct() File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/query.py", line 949, in exclude return self._filter_or_exclude(True, args, kwargs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/query.py", line 966, in _filter_or_exclude_inplace self._query.add_q(~Q(*args, **kwargs)) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1396, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1418, in _add_q split_subq=split_subq, check_filterable=check_filterable, File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1350, in build_filter condition = self.build_lookup(lookups, col, value) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1196, in build_lookup lookup = lookup_class(lhs, rhs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/lookups.py", line 25, in __init__ self.rhs = self.get_prep_lookup() File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 117, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1827, in get_prep_value ) from e Exception Type: ValueError at /wallacar_app/ajax/doors/ Exception Value: Field 'doors' expected a number but got ''. models.py class Coche(models.Model): doors = models.ForeignKey('CocheDoors', on_delete=models.CASCADE) class CocheDoors(models.Model): doors = models.IntegerField(verbose_name="Puertas", primary_key=True, validators=[RegexValidator(regex='^[0-9]{1}$',message="Las puertas solo pueden tener una cifra")]) def __str__(self): return str(self.doors) views.py def getDoors(request): if request.method == "GET" and request.is_ajax(): doors = Coche.objects.exclude(doors__isnull=True).exclude(doors__exact='').order_by('doors').values_list('doors').distinct() doors … -
list all active Sessions when using django-user-sessions
I'm currently working on a django project and I'm using the django-user-sessions library. This library overrides the django contrib Sessions and offers possibilities for user session management. What I want to do is to list all active sessions, with the default django Session it would be something like this : Session.objects.filter(session__expire_date__gt=datetime.now()) The problem is I can't do it when I use django-user-sessions because we have to turn off the use of the default Sessions. All I could do with it is list a user's sessions user.session_set.filter(expire_date__gt=datetime.now()) Please, if you are familiare with this library can you guide me? Already checked the documentation but it doesn't tell how. -
How to get the values of dynamically input fields and process them in Django views
I have an input field that can be added dynamically in my template html file. Now, I want to get all those values to process them in the views. However, I am getting only the last value Any idea on how to grab all the values? Thank you and here is my code Html file <div class="form-group col-md-6"> <label>Required Skills</label> <div class="input_skills_wrap"> <div> <input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-primary add-more-skill" type="button"><i class="glyphicon glyphicon-plus"></i></button> </div> </div> </div> <script> $(document).ready(function(){ //EMPLOYMENT SKILLS $(".add-more-skill").click(function(e){ e.preventDefault(); $(".input_skills_wrap").append('<div><input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-danger remove-skill" type="button"> <i class="glyphicon glyphicon-minus"></i></button></div>'); }); $(".input_skills_wrap").on("click", ".remove-skill", function(e){ e.preventDefault(); $(this).parent('div').remove(); }); </script> views.py def post_internship(request): if request.method == 'POST': skills = request.POST['internship_skills[]'] print(skills) return render(request, 'post_internship.html') -
what is select_related attribute in dajngo generic class,can someone explain what this implies?
class PostDetail(SelectRelatedMixin,generic.DetailView): model=models.Post select_related=('user','group') This is the snippet and the instructor told its for associating user with post and the group with post. what exactly does this implies and how its get associated? -
image not getting uploaded in django via model form but getting added from the admin panel
So in my django project , I have a page where user can fill details about his profile via a form. The form is as follows : class VendorProfileForm(ModelForm): class Meta: model = Vendor fields = ['name', 'address', 'pincode', 'phone', 'email', 'image1', 'image2', 'image3', 'image4'] The model 'Vendor' to which the form is referring to is as follows : class Vendor(models.Model): name = models.CharField(max_length=255) email = models.EmailField(blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) phone = models.CharField(blank=True, null=True, max_length=20) address = models.CharField(blank=True, null=True, max_length=200) image1 = models.ImageField(upload_to='shop_images/', blank=True, null=True) image2 = models.ImageField(upload_to='shop_images/', blank=True, null=True) image3 = models.ImageField(upload_to='shop_images/', blank=True, null=True) image4 = models.ImageField(upload_to='shop_images/', blank=True, null=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) The view used is as follows: @login_required def vendor_profile_details(request): if request.method == 'POST': form = VendorProfileForm(request.POST) if form.is_valid(): vendor = form.save(commit=False) vendor.created_by = request.user vendor.save() return redirect('vendor_admin') else: form = VendorProfileForm() return render(request, 'vendor_profile_details.html', {'form': form}) And the template used for the frontend part 'vendor_profile_details.html' is as follows: {% extends 'base.html' %} {% block title %}Profile details | {% endblock %} {% block content %} <h1 class="title">Finish your profile</h1> <form method="post" action="." method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="field"> <div class="control"> <button class="button is-dark is-uppercase" … -
How to use django-ckeditor in my template
I want to use RichTextField in my template.They can post own blog content who log in my site. So they can type in RichTextField. -
No reverse match error in Django getting error
enter image description here enter image description here enter image description here enter image description here enter image description here -
How to create interactive user interface in django?
I am working on a python project using the framework Django. I want my code to display a popup window for the user with a question and different options to choose from, then the user get to choose one or multiple options, and the code continues according to the choices made by the user. How can i do this with Django ? -
Search bar in Django does not redirect correctly (website like wikipedia)
I am programming a website that works like wikipedia using Django. I have already make it able to show an entry by putting the title of the entry in the url (like, for example, http://127.0.0.1:8000/wiki/Django). Now I'm doing a search bar but introducing the name of the entry in the searchbar results in the url http://127.0.0.1:8000/wiki/?q=Django, which doesn't work. This is the form I'm using(in layout.html): <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form> <input class="search" type="search" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'create' %}">Create Page</a> </div> Those are the paths I am using in urls.py: urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entry, name="entry"), path("q", views.search, name="search") ] And this is the file views.py: from django.http import HttpResponseRedirect from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry (request, title): return render(request, "encyclopedia/entry.html", { "info": util.get_entry(title), "title": title }) def create (request): return render(request, "encyclopedia/create.html") def search (request, q): q = request.GET.get('q','') return render ("encyclopedia/entry.html", { "info": util.get_entry(q), "title": q }) I also have de file util.py with some functions: import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): """ Returns a … -
DateTime Picker is not saving Date
I am building a BlogApp and I am implementing a Feature of DateTime Picker using bootstrap BUT post is not adding. It is showing DateTime Picker perfectly BUT when i try to post it then page refresh BUT post is not saving. forms.py class PostForm(forms.ModelForm): date = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput()) class Meta: model = Post fields = ('post_title','date') widgets.py class BootstrapDateTimePickerInput(DateTimeInput): template_name = 'mains/bootstrap_datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = 'datetimepicker_{name}'.format(name=name) if attrs is None: attrs = dict() attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context create_post.html {{ form.date|as_crispy_field }} <!-- I have also loaded all the bootstrap links --> Whe i click on save post then it refresh and again it redirect on create_post page. I have no idea, what am i doing wrong. Any help would be Appreciated. Thank You in Advance. -
How to print the objects created last month instead of using datetime.timedelta(days=30)
I am making a Django app to print the expenses made each month I have been searching since a long time how to print the objects(expenses) created in a specific month(or may be last month) I checked across many stack overflow questions similar to this but was not able to find an appropriate answer. Many people use datetime.timedelta(days=30) But how can this method be proper to print the expenses of a particular month. I want to use a method like datetime.timedelta(previous month) Is there any possible way to do this? -
Django Order QuerySet based on ManyToManyField value
I have a business model as follows: class Business(models.Model): class Meta: verbose_name_plural = "Businesses" name = models.CharField(max_length=60, null=False, verbose_name="Title") about = models.TextField(max_length=5000, null=True, verbose_name="Description", blank=True) upvote = models.ManyToManyField(Account, verbose_name="Upvote Count", blank=True) The Account model is as follows: class Account(models.Model): CHOICES = [('Male', 'Male'),Female', 'Female'),] class Meta: verbose_name_plural = "Accounts" name = models.CharField(max_length=60, null=False, verbose_name="Title") gender= models.CharField(max_length=6, null=True, verbose_name="Gender", choices=CHOICES) I am trying to get a QuerySet that will be sorted by gender of the Account. How do I achieve this? So far I have achieved sorting by the upvote count. Business.objects.all().order_by("upvote") -
django: __init__() missing 1 required positional argument: 'user'
I'm trying to add a PasswordChangeForm into my project, but i gean error: "init() missing 1 required positional argument: 'user'" How can i fix it? My View: def password_change_view(request): if request.method == 'POST': pass_form = PasswordChangeForm(request.POST, instance=request.user) if pass_form.is_valid(): pass_form.save() return redirect('users/login') else: pass_form = PasswordChangeForm(instance=request.user) return render(request, 'users/change_password.html', {'password_form': pass_form}) and my html file: {% extends 'main/layout.html' %} {% block title %} Изменение пароля {% endblock %} {% block content %} <div class="user_content"> <form method="post"> {% csrf_token %} {{ password_form.as_p }} <center><button type="submit">Сохранить</button></center> </form></div> {% endblock %} I think, my mistake is somewhere in view, but i cant find it. -
HTML POST a text to Django
I need to make a form in HTML for a global search (just some selects in mysql) but I'm struggling in making the form work. I created the view: class GlobalSearch(View): template = "name.html" def post(self, request): global_json = {} if "global_search" in request.POST: global_val = request.POST["global_search"] global_json = get_all_elements(global_val) return render(request, self.template, global_json) and gave the URL in the urls.py path('global-search', views.GlobalSearch.as_view(), name='global-search'), indeed i can properly reach my view. HTML form is this: <form class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0" action="/global-search" method="POST" id="global-search">{% csrf_token %} <div class="input-group"> <input class="form-control" type="text" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2" name="global_search" id="global-search"/> <div class="input-group-append"> <button class="btn btn-primary" type="submit" name="global_search" id="global-search"><i class="fas fa-search"></i></button> </div> </div> </form> but when i submit the form, the global-search field is empty (''). What am i missing? -
channels restrict message sending based on permissions
So I have models called lockers. class Locker(CoreModel): # PLAN CHOICES BASIC = 0 BEGINNER = 1 STANDARD = 2 BUSINESS = 3 PLAN_CHOICES = ( (BASIC, 'Basic'), (BEGINNER, 'Beginner'), (STANDARD, 'Standard'), (BUSINESS, 'Business') ) PLAN_MAPPING = { settings.BEGINNER_PLAN_ID: BEGINNER, settings.STANDARD_PLAN_ID: STANDARD, settings.BUSINESS_PLAN_ID: BUSINESS } SPACE_MAPPING = { BASIC: settings.BASIC_MAX_SPACE, BEGINNER: settings.BEGINNER_MAX_SPACE, STANDARD: settings.STANDARD_MAX_SPACE, BUSINESS: settings.BUSINESS_MAX_SPACE } topic = models.CharField( verbose_name=_('topic'), help_text=_("locker description"), null=True, max_length=1024 ) icon = models.ImageField( verbose_name=_('icon'), help_text=_("locker icon"), max_length=512, validators=( MaxFileSizeValidator( max_size=settings.MAX_LOCKER_ICON_SIZE ), ), upload_to='icons/', ) name = models.CharField( verbose_name=_('name'), help_text=_("locker name"), max_length=100, validators=( MinLengthValidator(2), ) ) owner = models.ForeignKey( to=settings.AUTH_USER_MODEL, related_name='owned_locker_set', verbose_name=_('owner'), on_delete=models.CASCADE ) plan = models.SmallIntegerField( verbose_name=_('plan'), help_text=_('billing plan'), default=BASIC, choices=PLAN_CHOICES ) multiple users can join lockers. class GatewayEventsConsumer(AsyncWebsocketConsumer): """ An ASGI consumer for gateway event sending. """ # OPCODES FOR GATEWAY # COMMANDS AND EVENTS DISPATCH = 0 HEARTBEAT = 1 IDENTIFY = 2 READY = 3 HELLO = 4 HEARTBEAT_ACK = 5 def __init__(self): super(GatewayEventsConsumer, self).__init__() self.connection = None self.last_heartbeat = 0 # handlers for gateway commands self.opcode_receivers = { self.IDENTIFY: self.identify, self.HEARTBEAT: self.heartbeat } def authenticate_scope(self, token): """ sets the scope's user to the token's user object after validating the same. We need to do this explicitly without and token-authentication-middleware because … -
How to pass model fields to a signal receiver method?
I have a Founder(models.Model) with some fields like name=models.charfield; I want to execute post_save signal to a receiver function "generate" which will run a custom "management.call_command" function which takes "name" as an argument. To my understanding, this receiver "generate" function should be a method of a Founder for it to be able to take it's name field as an argument ? but when I'm creating a founder in admin, I get an error in console saying TypeError: generate() missing 1 required positional argument: 'self' -
Cross-project iframe testing on localhost with different ports
I am relatively new to iFrame, and what I try to do is to load project A in an iframe that is in project B. Project A is running as a Django project on localhost:8000, and project B as a separate Django project on localhost:8001. Inside the project B, I have a Django template with the following content: <iframe src="http://127.0.0.1:8001" height="500px" width="500px"></iframe> The problem is that instead of seeing the content of project A home page, I see error message stating that: 127.0.0.1 refused to connect Is there anything I am terribly missing? -
Nested if in Django Rest API [closed]
Want to update details in two models,so here using curresponding serializers and the out: first key value is updated but remaining is still not updating Help to solve this