Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detailview class object not showing data after form is submitted and redirected back to the same page
I'm building a django review app with class based views. I am trying to combine a detailview class with a formview class or form mixin to enable users to submit form in a detail view environment. My form is in a bootstrap modal and included in a base.html template. It works perfectly at first but noticed that when i submit the form and redirected back to the same page, my detailview object data no longer show. Model.py from django.db import models from django.shortcuts import reverse # Create your models here. CATEGORY = ( ('B', 'Bollywood'), ('C', 'Chinese'), ('F', 'French'), ('G', 'German'), ('Go', 'Gollywood'), ('H', 'Hollywood'), ('J', 'Japanese'), ('K', 'Korean'), ('N', 'Nollywood'), ('S', 'Spanish') ) LABEL = ( ('L', 'Latest'), ('R', 'Recently Released'), ('S', 'Coming Soon'), ('T', 'Top Rated'), ) TAG = ( ('N', 'New'), ('SP', 'Season Priemere'), ('SF', 'Season Finale'), ) FORMAT = ( ('MP4', 'Mp4'), ('3GP', '3gp'), ('HD', 'High Definition'), ) class Genre(models.Model): title= models.CharField(max_length=200, unique=True) slug= models.SlugField(max_length=200, unique=True) created_on= models.DateTimeField(auto_now_add=True) updated_on= models.DateTimeField(auto_now=True) # def cat(self): # return self.title class Meta: """docstring for Meta""" ordering = ['-created_on'] def __str__(self): return self.title # def get_absolute_url(self): # return reverse('category:category_detail', args=[self.slug]) class Anime(models.Model): title= models.CharField(max_length=200, unique=True) slug= models.SlugField(max_length=200, unique=True) category = models.CharField(choices=CATEGORY, … -
Django DRF - "hide user" (a mandatory field) in api webview
I have a simple model: class Store(models.Model): name = models.CharField("address", max_length = 128, null = True, blank = True) open = models.PositiveIntegerField("status", default = 1, choices = [(0,0), (1,1)]) user = models.OneToOneField(User, on_delete = models.CASCADE, ) with a simple serializer: class StoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = ["open", "user"] the view: class StateViewSet(viewsets.ModelViewSet): serializer_class = StoreSerializer http_method_names = ['get', 'put', 'head'] authentication_classes = [SessionAuthentication,] permission_classes = [IsAuthenticated,] def list(self, request): usr = request.user stores = Store.objects.filter(user = usr) return Response(stores.values_list("name", flat = True)) def put(self, request): usr = request.user Store.objects.filter(user = usr).update(state = request.data["state"]) return Response("updated") What I want is, to get rid of the user field - only the current user may change the state anyway, so it is already a preset value. I know I omit name, bc its null = True, blank = True, but how can I preset user to request.user and let the dropdown disappear? -
How to add these two elements in a webapp?
I am using django for this webapp I just wanted to know how could i approach to this two element marked in the image using html,css or javascript or is their any other way? -
'WSGIRequest' object has no attribute: can't get a value for a var
I am trying to add a functionality - an inquiry form, everything else works fine, but upon submission I can't get a value for my user_id variable. Any help and/or comments is much appreciated. models.py: from django.db import models from datetime import datetime # Create your models here. class Contact(models.Model): listing = models.CharField(max_length=200) listing_id = models.IntegerField() name = models.CharField(max_length=200) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) message = models.TextField(blank=True) contact_date = models.DateTimeField(default=datetime.now, blank=True) user_id = models.IntegerField(default=0, blank=True) def __str__(self): return self.name views.py: from django.shortcuts import render, redirect from django.contrib import messages from . models import Contact # Create your views here. def contact(request): if request.method == 'POST': listing_id = request.POST['listing_id'] listing = request.POST['listing'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] if 'user_id' in request.POST: user_id = request.POST['user_id'] else: user_id = False #user_id = request.POST['user_id'] realtor_email = request.POST['realtor_email'] # check if already made inquiry if request.user.is_authenticated: user_id = request.user_id # problematic has_contacted = Contact.objects.all().filter(listing_id=listing_id, user_id=user_id) if has_contacted: messages.error(request, "Inquiry already made,") return redirect('/listings/'+listing_id) contact = Contact(listing=listing, listing_id=listing_id, name=name, email=email, phone=phone, message=message, user_id=user_id,) contact.save() messages.success(request, 'Your request has been submitted, a realtor will get back to you soon,') return redirect('/listings/'+listing_id) admin.py: from django.contrib import admin from . models … -
Build Inline Formsets in Django Admin
So I am new to Django and I have been reading a lot of documentation to figure this out, I have a table called "Logs" that has logs of different positions (has FK of table "Position"), each position belongs to a department (has FK to table "Department") Check the image below :1 What I want to do is create a view just like this one : 2 and whenever you click on a department, it extends all the positions in it with their respective logs like this : 3 The Screenshots I have attached are my work in main app (or if you would like to call it front end), I wanted to replicate the same process in the Django Admin page, I keep seeing that I should use inlines but I can't seem to make it work, can someone help or put me in the right direction please ? much appreciated. -
Django - how to go back to previous view with parameters
I am relatively new with Django, this must be a common problem. I have created a view to show a form to input date (using widget that returns separate fields): when date is inserted, I call a function userPage(request, my_date) that filters, processes and renders a page (user.html) showing a list of items. def datePage(request): user=request.user context = {} context['form'] = UserDateForm() if request.GET: date_yr = request.GET['food_date_year'] date_mo = request.GET['food_date_month'] date_day = request.GET['food_date_day'] my_date_string = date_yr+'-'+date_mo+'-'+date_day my_date = datetime.strptime(my_date_string, "%Y-%m-%d").date() return userPage(request,my_date) return render(request, "date.html", context) def userPage(request, my_date): user=request.user # process context using user, my_date context={...:..., 'my_date': my_date} return render(request,'user.html',context) In user.html I include a URL to add an item: </div> <form action="{% url 'My_ItemCreate' %}" method="POST"> {%csrf_token%} <button type="submit" class="btn btn-success"> <span class="glyphicon glyphicon-plus"></span> </button> </form> </div> 'My_ItemCreate' points to a django.views.generic CreateView that creates an item. After creating the item in the CreateView, how do I go back to the user page after I inserted the date? I have lost the date in the new URL. If I use URL resolver to go to userPage, how do I pass a date in the format? It would be nice that I am able to pass initial values in … -
Django: how to use aggregators in this case
I have two tables Parcels parcel_id shop fruit quantity 1 shop1 apple 10 2 shop1 apple 20 3 shop3 mango 10 4 shop4 banana 10 shop id name 1 shop1 2 shop2 3 shop3 4 shop4 fruit id name 1 apple 2 mango 3 banana 4 orange 5 grapes from django.db import models class Shop(models.Model): name = models.CharField(max_length=30) class Fruit(models.Model): name = models.CharField(max_length=30) class Parcel(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, null=True) fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE, null=True) I want to get the list of quantity of each fruit which are getting parcelled like Fruit quantities getting parcelled fruit quantity apple 30 mango 20 banana 10 What i am doing is get all the parcels list and get the distinct fruits then again loop over each fruit and get all the parcels related and calculate the quantity Is there any way to do this, using annotation and aggregators -
i am confused on how to remove repeating value from a but let reside one of them list using a loop..i have tried my best to figure it out but couldn't
unconfirmed=['adeen','shahzaib','zaid','shahzaib','shahzaib','shahzaib'] while 'shahzaib'in unconfirmed: unconfirmed.remove('shahzaib') print(unconfirmed) -
Django URL links
I have encountered a problem , when I create a link it generates properly (viewing in development mode), but on the page it's not clickable. <button herf="{% url 'article-detail' post.pk %}">{{ post.title }}</button> -
Django Regroup how to have an arbitrary order
I have a model formset that contains the model, Items. Each Item is given a category: 'Produce','Grains','Protein/Dairy','Extra Items' and I want it to display in the html in that order. How can I do that? -
Django DecimalField default format
DecimalFied's values displaying different on different machnes on one of them Decimal('0') displays as Decimal('0') on another - Decimal('0') displays as Decimal('0E-7') How I can make behaviour the same? Can I get rid of scientific notation? -
Migrating models of dependencies when changing DEFAULT_AUTO_FIELD
I'm using Django 3.2. I've changed added this line to settings.py: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I then ran these commands: $ python manage.py makemigrations $ python manage.py migrate The makemigrations command creates new migration files for my apps, not just the apps that I have created, but also in my dependencies. For example, I'm using django-allauth, and this file was created in my virtual environment (virtualenv): .venv/lib/python3.8/site-packages/allauth/account/migrations/0003_auto_20210408_1526.py This file is not shipped with django-allauth. When I deploy this application from git, this file is not included. What should I do instead? How can I switch DEFAULT_AUTO_FIELD without the need to create new migration files for dependencies like django-allauth? -
How to install PostGIS for dockerized Django project
Django documentation says that only the instalation of the following libraries are needed: binutils libproj-dev gdal-bin postgresql-postgis Also adding gis app and defining psotigs as DB Backend in your project settings.py I run Postgres and Python in separated containers, so I don´t know if those libraries must be installed in both containers or only in python. And if I need to add other special config to Postgres. These are my Dockerfiles: Python: FROM python:alpine ENV PYTHONUNBUFFERED 1 ENV C_FORCE_ROOT true RUN mkdir /src RUN mkdir /static WORKDIR /src RUN apk update && apk add --no-cache \ postgresql \ zlib \ jpeg \ openblas \ libstdc++ Postgres: FROM postgres:alpine COPY ./compose/postgres/maintenance /usr/local/bin/maintenance RUN chmod +x /usr/local/bin/maintenance/* RUN mv /usr/local/bin/maintenance/* /usr/local/bin && rmdir /usr/local/bin/maintenance -
Django ModelChoiceField: filtering object based on pk in url
I've read many questions about this topic, but none of the methods work for me. There are 3 related models: class Trips(models.Model): lake = models.CharField("Lake", max_length=150) city = models.CharField("City", max_length=100, blank=True) s_date = models.DateTimeField("Starting Date", auto_now=False, auto_now_add=False) e_date = models.DateTimeField("Ending Date", auto_now=False, auto_now_add=False) trip_id = models.AutoField(primary_key=True) class Meta: verbose_name = "Trip" verbose_name_plural = "Trips" def __str__(self): return f"{self.lake}-{self.trip_id}-{self.s_date}" class Fisherman(models.Model): name = models.CharField("Fisherman", max_length=50) trip = models.ForeignKey(Trips, on_delete=models.CASCADE) fisherman_id = models.AutoField(primary_key=True) class Meta: verbose_name = "Fisherman" verbose_name_plural = "Fishermen" def __str__(self): return f"{self.name}-{self.fisherman_id}" class Catch(models.Model): fish_type = models.CharField("Fish Type", max_length=50) catch_id = models.AutoField(primary_key=True) weight = models.DecimalField("Weight", max_digits=5, decimal_places=2) length = models.DecimalField("Length", max_digits=5, decimal_places=2, blank=True, null=True) datetime = models.DateTimeField("Catch Time", auto_now=False, auto_now_add=False) fisherman = models.ForeignKey(Fisherman, on_delete=models.CASCADE) trip = models.ForeignKey(Trips, on_delete=models.CASCADE) class Meta: verbose_name = "Catch" verbose_name_plural = "Catches" def __str__(self): return f"{self.fish_type}-{self.catch_id}" I have a ModelForm to create a new catch. Here I use a ModelChoiceField to list Fishermen, but I don't know how to filter them. I only want display those who belong to the trip. class CatchForm(forms.ModelForm): fisherman = forms.ModelChoiceField(queryset= Fisherman.objects.all()) class Meta: model = Catch fields = ["fish_type", "weight", "length", "datetime", "fisherman"] widgets = { "datetime": forms.DateTimeInput(format='%Y-%m-%d %H:%M', attrs={'class':'datetimefield form-control'}), } views.py I' ve read that get_form_kwargs should … -
How to handle python djangon geocoder osm error if user enter invalid city name
Did anyone know how to handle python geocoder osm error if user enter invalid city name? I am using it in Django. When user input valid city name it saving to my database and showing on map but I can't stop user to put invalid city name and prevent saving to my database. if request.method == 'POST': form = Search(request.POST) if form.is_valid(): form.save() else: form = Search() address = FindDistance.objects.all().last() location = geocoder.osm(address) -
React Formik: initial values of select field does not show up
I am setting the initialvalue fields with the data that comes from my API. This goes well for all fields, but not for my select field. Somehow, it doesn't work for this field. When I enter a string such as "France" it does work as it should. But not with my database value. Now I made sure that the following things were in order: enableReinitialize={true} I tested console.log(project.country) and it displayed the correct value. Does anyone know why the api response does not show up at the select field? This is my Formik code with the initialvalues. The problem arises by the country field. <Formik validateOnChange={true} enableReinitialize={true} initialValues={{ name: project.name, company: project.company, costs: project.costs, country: project.country, description: project.description, }} validationSchema={validationSchema} onSubmit={(data) =>{ const tokens = auth.access console.log(tokens) const requestOptions = { method: 'POST', headers: {'Authorization': `JWT ${tokens}`, 'Content-Type':'application/json', 'Accept': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'name' : data.name, 'company': data.company, 'country' : data.country, 'costs' : data.costs, 'description' : data.description, }), }; fetch('/create-project',requestOptions).then((response) => response.json() ).then((data) => console.log('submit:', data)) setToNext(true) }} This is the form instance of the country field: <FormControl className={classes.formyForm}> <InputLabel id="countrylabel">Country</InputLabel> <Field labelId="countrylabel" name="country" type="select" as={Select} > {ranges.map((option) => ( <MenuItem value={option.name}> {option.name} </MenuItem> ))} </Field> </FormControl> -
Django model 'TypeError: isinstance() arg 2 must be a type or tuple of types' when creating custom users
While attempting to implement a new custom model in Django, the following error keeps occurring when I run makemigrations. (myenv) 14:16 ~/SlayersecFloorPlanner (main)$ python manage.py makemigrations --verbosity 3 Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/contrib/auth/checks.py", line 79, in check_user_model if isinstance(cls().is_anonymous, MethodType): File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/db/models/base.py", line 475, in __init__ val = field.get_default() File "/home/slayersec/.virtualenvs/myenv/lib/python3.8/site-packages/django/db/models/fields/related.py", line 961, in get_default if isinstance(field_default, self.remote_field.model): TypeError: isinstance() arg 2 must be a type or tuple of types I've created a new app named 'users', and here is the relevant managers.py and model.py: managers.py: from django.utils.translation import ugettext_lazy as _ 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, … -
What is the best practice to architect tasks processing using aws?
I'm going to process background tasks such as text transmission and email transmission as lambda. I thought of three ways, which is the best way? The biggest concern is whether to directly invoke Lambda in the app or use task consumer using sqs or sns . Or do you have any suggestions?enter image description here -
Django override QuerySet for pk
I'm using djongo in order to connect my Django Rest Framework project to MongoDB, As MongoDB using _id as its primary key, I changed my models like this: from djongo import models class MyModel(models.Model): _id = models.ObjectIdField(primary_key=True) name = models.CharField(max_length=200) When I query data from database, the type of _id will be bson.objectid.ObjectId So any time I want to query anything, I should do it like this: from bson.objectid import ObjectId from myapp.models import MyModel MyModel.objects.get(pk=ObjectId('606e91bd371197379e9bf919')) # or MyModel.objects.filter(_id=ObjectId('606e91bd371197379e9bf919')) and if I use MyModel.objects.filter(pk='606e91bd371197379e9bf919') it can't find the data in database This additional ObjectId which is required for any query makes many problems because none of the pre-existing classes (like Forms, Views, Django Rest Framework Serializers, ....) act like that, so I should override all of them, and this cause many code duplications, Is there a way to override any of Q/QuerySet/Model/Model Meta Class or a wrapper or anything else to apply the additional ObjectId for querying pk/id/_id field and solve this problem? Is a better way to do this? -
problems when trying to get user's username
When I run this: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login as auth_login def login(request): if request.user.is_authenticated(): username = request.user.username else: username = None return render (request, 'login_success.html', {'username': username}) I get this error: TypeError at /login/success/ 'bool' object is not callable This is my html: {% include 'base.html' %} <text align="center">Sup {{ username }}, you're logged in!</text> What does the error mean, and how do I fix it? -
django AttributeError 'WSGIRequest' object has no attribute 'get'
//id can't found error point, and didn't search solutions AttributeError at /product/3 'WSGIRequest' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/product/3 Django Version: 3.1.6 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'get' Exception Location: C:\Users\vudgh\anaconda3\lib\site-packages\django\forms\widgets.py, line 652, in value_from_datadict Python Executable: C:\Users\vudgh\anaconda3\python.exe Python Version: 3.8.5 Python Path: ['C:\Pytion_WorkSpoace\oto_shop', 'C:\Users\vudgh\anaconda3\python38.zip', 'C:\Users\vudgh\anaconda3\DLLs', 'C:\Users\vudgh\anaconda3\lib', 'C:\Users\vudgh\anaconda3', 'C:\Users\vudgh\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\vudgh\anaconda3\lib\site-packages', 'C:\Users\vudgh\anaconda3\lib\site-packages\win32', 'C:\Users\vudgh\anaconda3\lib\site-packages\win32\lib', 'C:\Users\vudgh\anaconda3\lib\site-packages\Pythonwin'] Server time: Thu, 08 Apr 2021 22:40:36 +0900 Error during template rendering In template C:\Pytion_WorkSpoace\oto_shop\templates\base.html, error at line 0 'WSGIRequest' object has no attribute 'get' 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>{% block title %} {% endblock %}</title> 7 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> 8 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> 9 10 </head> Traceback Switch to copy-and-paste view Environment: Request Method: GET Request URL: http://127.0.0.1:8000/product/3 Django Version: 3.1.6 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'users', 'product', 'order', 'board', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Pytion_WorkSpoace\oto_shop\templates\base.html, error at line 0 'WSGIRequest' object has no attribute 'get' 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : <head> 4 : <meta charset="UTF-8"> 5 : <meta … -
Ignore invalid foreign for django migrations?
I'm migrating an application from an old DB system to django. I've imported a bunch of legacy data. I used a script to convert the table schemas from the old system into Django models, as it had a lots of tables. Then I used another script to write the content of the old db into Django fixtures, which I then imported. That all worked fine, the data is served in the views etc. However, I now noticed that some ForeignKey in the old system were not properly identified as FK and were simply put in as Char/Int fields into the djando models. So I updated a field from IntegerField to ForeignKey, but that being legacy data I had the following issue: django.db.utils.IntegrityError: The row in table 'pickings_detpick' with primary key '17170' has an invalid foreign key: pickings_detpick.fk_ent_id contains a value '30223' that does not have a corresponding value in pickings_entpick.id. So basically, there are a number of (unsure how many yet) foreign key references that point to objects that actually do not exist in the source data (for whatever reason, I don't know the hold system much). Is there a way that I can simply tell Django to ignore those … -
Make URLfield display an error instead of just being red, with invalid validator
I have an URL-field, when I enter an invalid URL (without http) it just displays a red border around the field like so. If I click "submit" it does says "enter a valid url". Since some persons does not know, that http is required to be "valid" I want to add that as a message below, just like when calling clean_link raises an validation error. How can I do that, apart from removing the validation and add that step in clean_field instead? -
Django Redirect back two pages
I have a decorator protecting certain parts of my site. def admin_only(view): @wraps(view) def _view(request, *args, **kwargs): if not Group.objects.get(name='admin') in request.user.groups.all(): return redirect('main:unauthorized') return view(request, *args, **kwargs) return _view So if the user is not in the admin group, they are redirected to a view that renders an 'unauthorized blah blah blah template'. What I want to do is redirect the user back to where they were when they tried to access the forbidden page. I'll then use something like if not Group.objects.get(name='admin') in request.user.groups.all(): messages.error("Unauthorized blah blah blah" **redirect to where they were or home incase they used direct link** -
Django installed but startproject command doesn't work
I just installed django and when I do python3 -m django --version it prints 3.2 but when I do django-admin startproject something it doesn't do anything, neither when I only do django-admin. How can I fix this?