Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to create a model and try to migrate it but facing error such as :AttributeError: module 'django.db.models' has no attribute 'models'
from django.db import models # Create your models here. class Topic(models.Model): top_name = models.models.CharField(max_length=50,unique = True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=256,unique = True) url =models.URLField(unique =True) def __str__(self): return self.name Well i am using django version 3.0.3 and python 3.8.5 and using vs code and i have made environment in anaconda.. Well I am trying to make model and than migrate it but when i try to migrate my models by writing command python manage.py migrate Then compiler show error AttributeError: module 'django.db.models' has no attribute 'models' . -
Django - Create forms with loops
I have a model called comments and I am displaying them using a for loop in the template. I want the users to be able to edit these forms without having to go into a different page but I'm not sure how I will go about creating these forms in a loop and more importantly how to handle the post requests. Thanks in advance. -
How to do a nested loop in Django
I'm trying to loop through my choicefield form and surround every 4 in a <div> </div> so that there are only 4 of the choices per line. The problem is I can't seem to figure out nested loops in django. The documentation on parent-loops is almost nothing and I've also tried creating a template tag counter to no avail. Here's what I'm working with: {{ counter.count }} {% for check in form.pt_medical_condition %} {% if counter.count == 4 %} <div> {% endif %} <label> {{ check.tag }} {{ check.choice_label }} </label> {% if counter.count == 4 %} </div> {% endif %} {% if counter.count == 4 %} {{ counter.count = 0 }} {% endif %} {{ counter.increment }} {% endfor %} Is there a simpler way to do this without template tags seeing as mine don't work anyway? Thanks! -
Django pagination shows the same page twice if the database updates in the background
I am working on a webpage that get images of cars from various sources and stores them in SQLite database and then I display them in an infinite scrolling webpage. Lets say a user goes to my site and the first page gets loaded, then they scroll to the bottom and the javascript then gets the second page. And while scrolling through the second page the database is updated in the background to add more images to the database using code running on the server. If at that moment of the database update, the user scrolls to page three, for some reason page one from before shows up and the user has to scroll through page one, and then two and then to page three. How do I keep track of what images were in the last page and then show them only the images that come after that based on by specified order_by filter in the view function. **Views.py file is given below:** def car (request): category = 'CARS' files_list = Car.objects.all().order_by('-upload_date', '-id') paginator = Paginator(files_list, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'memes/car.html', {'page_obj':page_obj, 'category':category}) **The template file is given below:** {% block content %} <div … -
Django model analytic feature
I am using Django on my website and I have a bunch of moving parts. One of the apps in question is a user flow where they are sent a email and navigate through a set of "steps" on my site. I would like to keep track of all my analytic data such as: When they first clicked on email How long they spent on each page How long it took to complete How many completed How many didn't start Longest page users spend time on etc I can gather all this data easily and store it in a model, but I have no good way of displaying and comparing it over time. I am interested in Django has anything that would work for this? -
variable min_value in a decimal field form
I am trying to set the min_value of a field's form variable. class BidForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bid'] = forms.DecimalField(min_value=50, error_messages={'min_value': 'Price must be greater than the current price'}) self.fields['bid'].widget.attrs.update({'placeholder': 'Place your bid here', 'step': 1}) I have harcoded the 50 value in this case, but what I need is to set it according to the current bid. This is the Bid model: class Bid(models.Model): bid = models.DecimalField(max_digits=5, decimal_places=2) user = models.ForeignKey(User, related_name="bid", on_delete=models.CASCADE) auction = models.ForeignKey(Auction, related_name="bid", on_delete=models.CASCADE) def __str__(self): return f'Bid for ${self.bid} on {self.auction} by {self.user}' This is the view: def detail(request, auction): auction = get_object_or_404(Auction, slug=auction) comments = auction.comments.all() current_bid = auction.bid.last() comment_message = None bid_message = None new_comment = None new_bid = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) bid_form = BidForm(data=request.POST) if request.POST.get("form_type") == 'form_comment': bid_form = BidForm() if not request.user.is_authenticated: comment_message = "You have to sign in to post a comment" else: if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.auction = auction new_comment.user = request.user new_comment.save() return redirect('detail', auction.slug) elif request.POST.get("form_type") == 'form_bid': comment_form = CommentForm() if not request.user.is_authenticated: bid_message = "You have to sign in to place a bid" else: if bid_form.is_valid(): new_bid = bid_form.save(commit=False) new_bid.auction = auction new_bid.user = … -
How to populate data from select dropdown so that data of particular id will be displayed to the main page
I have created a dropdown selector and want data to be fetched from the database according to that.For example I have two models Cuisine and Dish.I have taken all the cuisines in my dropdown selector (eg Indian,British,Frech etc) and want to fetch all the dishes from the database the database accourding to it. For example,when I select Indian then all the dished that are associated to it should be fetched so that I can display it to home page. model.py class Cuisine(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ['-id'] def __str__(self): return self.name class Dish(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='dishes_pics') description = models.TextField() required_time_to_cook = models.CharField(max_length=100) cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE) class Meta: ordering = ['-id'] def __str__(self): return self.name views.py from django.shortcuts import render from django.http import HttpResponse from .models import Cuisine,Dish def select_cuisine(request): dish_id = Dish.objects.get(pk = 1) cuisine_id = Cuisine.objects.filter(cuisine=cuisine_id) return render(request, 'cookbook/base.html', {'cuisine_type' : cuisine_id}) def home(request): context = { 'dishes' : Dish.objects.all() } return render(request, 'cookbook/home.html',context) index.html Select Cuisine {% for type in cuisine_type %} {{ type.name }} {% endfor %} </div> </li> -
Relating two models with same field value?
I'm new to Django, so I apologize a head of time if my verbiage is off. But I'll try my best! I have two models : PlayerProfile - this is updated once a day. PlayerListing - this is updated every 5 minutes. Here are simplified versions of those models. class PlayerProfile(models.Model): listings_id = models.CharField(max_length=120) card_id = models.CharField(max_length=120) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) overall = models.IntegerField() class PlayerListing(models.Model): listings_id = models.CharField(max_length=120, unique=True) buy = models.IntegerField() sell = models.IntegerField() Currently, we just make queries based on the matching listings_id - but I'd like to have a more traditional relationship setup if possible. How do you relate two models that have the same value for a specific field (in this case, the listings_id)? Some potentially relevant information: Data for both models is brought in from an external API, processed and then saved to the database. Each PlayerListing relates to a single PlayerProfile. But not every PlayerProfile will have a PlayerListing. When we create PlayerListings (every 5 minutes), we don't necessarily have access to the correct PlayerProfile model. listings_id's are generated last (as we have to do some extra logic to make sure they're correct). -
Static files: Images are being loaded but not CSS and JS files | Django
I'm trying to load CSS and JS files in my Django templates but it's not working. I could load images succesfully. My settings: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( STATIC_DIR, ) My urls.py: urlpatterns = [ . . . ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + \ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My template: {% extends 'base.html' %} {% load static %} {% block content %} <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <link href="{% static 'card-js.min.css' %}" rel="stylesheet" type="text/css" /> <script src="{% static 'card-js.min.js' %}" type="text/javascript"></script> <img src="{% static 'bag1.png' %}" width="25px"> My file structure: dma - account - cart - dma - home - media - payment - static - - bag1.png - - card-js.min.css - - card-js.min.js The image 'bag1.png' is loaded correctly but not the 'css' and 'js' files. Any help? Thank you! -
Deploying django docker container to elastic beanstalk
I have a django rest framework app configured with nginx + gunicorn. I can run the containers locally using docker-compose up -d --build just fine, but I wish to deploy the docker image to AWS elastic beanstalk. For debugging purposes, I am trying eb local run, butI seem to be getting this error: latest: Pulling from <user>/<repo> Digest: sha256:15cec14272aca0b787c4209e3196b2e61d50732f6f4616f2cf50baa28b82c65c Status: Image is up to date for <user>/<repo>:latest docker.io/<user>/<repo>:latest Sending build context to Docker daemon 316.7MB Step 1/2 : FROM <user>/<repo>:latest ---> eex74e02e4e5 Step 2/2 : EXPOSE 8000 ---> Using cache ---> 094f132e13a7 Successfully built 094f132e13a7 SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories. docker: invalid reference format. See 'docker run --help'. ERROR: CommandError - None Here is my Dockerrun.aws.json: { "AWSEBDockerrunVersion": "1", "Image": { "Name": "j0hnk1m/refridge:latest", "Update": "true" }, "Ports": [ { "ContainerPort": "8000" } ] } Why am I getting th -
Django: How to create enum of classes to define choices
How to subclass models.Choices to define enum of classes? The following code raises TypeError: from django.db.models import Choices class DataTypes(type, Choices): CHAR = str, _('Short string') INTEGER = int, _('Integer') The error message: dynamic_attributes = {k for c in enum_class.mro() TypeError: descriptor 'mro' of 'type' object needs an argument -
django form doesn't go inside post
I am just trying to be able to read the values entered by the user on the form in the server. I have noticed that it never goes inside this part of the view function if request.method == 'POST': Please let me know if I missed anything. I have included my code snippets for views, urls, form, html files: urls.py=> urlpatterns = [ path('create',views.create), path('create/',views.create), path('download', views.download), ] checklistform.py=> class ContactForm(forms.Form): name = forms.CharField() create.html=> <!DOCTYPE html> <html lang="en> <head> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="OK"> </form> </body> </html> views.py => from django.shortcuts import render, HttpResponseRedirect, HttpResponse, redirect from .checklistform import ContactForm def create(request): print("letssee") print(request.method) if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] print(name) form=ContactForm() return render(request, 'create.html', {'form': form}) Output seen in pycharm => (as we can see it never goes inside the if) [15/Aug/2020 23:47:03] "GET / HTTP/1.1" 404 2038 letssee GET [15/Aug/2020 23:47:08] "GET /imschecklist/create HTTP/1.1" 200 364 Thanks, Nick -
Can django do computations in the client?
I am about to design an app that requires to do some medium level of computation (training some small machine learning model). I am thinking about designing the app with django. Was wondering if django can allow that some of these computations can be done in the client‘s browser, i.e. using its memory and cpu. Some initial tips of where to start looking at will be much appreciated. Thanks -
Changing value in Django changes form field in static value
I'm quite new to Django so there might be a simple solution. I try to load a value from Excel and add it as a default/initial value of a form. However, the formfield changes to a static value (can't be changed anymore). See 3 images below. Could you help me get the value from Excel (value in first row and first column) as an initial value in a form which can still be changed? Initial screen: Initial Result after Excel import: After import Preferred result after Excel import: Preferred The code: views.py from django.shortcuts import render from django.template import RequestContext from django.http import HttpResponse from .models import InputForm from .models import InputForm1 from .compute import compute from django.db import models import os import xlsxwriter import io def index(request): os.chdir(os.path.dirname(__file__)) result = None if request.method == 'POST' and 'calculate' in request.POST: form = InputForm(request.POST) form1 = InputForm1() if form.is_valid(): form2 = form.save(commit=False) result = compute(form2.A, form2.B, form2.C) elif request.method == 'POST' and 'calculate1' in request.POST: print(1) form1 = InputForm1() form = InputForm(request.POST) if form.is_valid(): form2 = form.save(commit=False) result = compute(form2.A, form2.B, form2.C) print(2) # create our spreadsheet. I will create it in memory with a StringIO output = io.BytesIO() workbook = … -
Get "raw" string to handle function [duplicate]
I have problem with handling GET responses form HTML. I'm getting selected parameter to handle with: atribute = request.GET.get('parameters') and I want to use this atribute to access specific values from my database and add it to array by: for i in things: my_data.append(i.atribute) But of course this can't work because atribute is a string value, so reference through string will not work. How to manage with such problem? -
django class based CreateApiView author_id is not null?
I have also authenticate it with token but when I create a new post error is alert IntegrityError at /api/create/ NOT NULL constraint failed: core_article.author_id how can I valid data with request user in serializer? model.py from django.contrib.auth.models import User from django.db import models class Article(models.Model): title = models.CharField(max_length=255, help_text="Short title") content = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=True) def __str__(self): return self.title serializer.py from rest_framework import serializers from django.contrib.auth.models import User from core.models import Article class NewsSerializer(serializers.ModelSerializer): author = serializers.SlugRelatedField( slug_field=User.USERNAME_FIELD, read_only=True, required=False) class Meta: model = Article fields = [ 'id', 'author', 'title', 'content', 'status', ] views.py class ArticleCreate(CreateAPIView): queryset = Article.status_objects.all() serializer_class = NewsSerializer permission_classes = (permissions.IsAuthenticated, ) -
How to Dockerize a Django + Postgres App with Apache (Instead of NGINX) for production
I'm new to the DevOps world and I have been following this tutorial successfully, my Docker setup is almost identical to the one on the tutorial. I now would like to setup a Docker container with Django and Postgres but with Apache instead of NGINX for production. What commands should I add/modify to the Dockerfile, volumes and configurations to the docker-compose file and what configuration files should I have for the Apache configuration? -
How to authenticate users with HttpOnly Cookie Django-React
I'm trying to understand authentication system for my web app but I'm going nuts. At this point I literally have no idea what I am doing, Anyway I'm developing a Django-React Web App and using JWT tokens for authentication. For security measures I decided not to store JWT tokens in client, this is where my confusion gets start. So I make an axios POST request to login from React => //LOGIN USER export const login = (username, password) => dispatch => { //Headers const config = { headers: { "Content-type": "application/json" } } //Request body const body = JSON.stringify({ username, password }) axios.post("http://localhost:8000/auth/login/", body, config, {withCredentials: true}) .then(res => { dispatch({ type: LOGIN_SUCCESS, payload: res.data }) }).catch(err => { console.log(err) dispatch({ type: LOGIN_FAIL }) }) } and server responses with some cookies => and JSON response => then I want to use the access_token for authentication but since it is HttpOnly I can't access the token from client. Anyway, with some research I found out that I can send csrf-token to authenticate(I could be wrong about that), so I made a request to protected endpoint => import axios from 'axios' axios.defaults.xsrfCookieName = "csrftoken" axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" //ADD POST export const … -
How to get the object of a specific user and make a check?
I need to check for a specific user for the presence of the same link that I just entered from the form. I enter two links in the field, the user is filled in automatically. I want to check if the user has the same link, but I don’t know how to get all the user objects. models.py: class LinksModel(models.Model): user=models.ForeignKey(User,verbose_name="user", on_delete=models.CASCADE) full_link=models.CharField(verbose_name="full_link",max_length=250) short_link=models.CharField(verbose_name="short_link",max_length=250) def __str__(self): return f"{self.short_link}" forms.py: class LinksForm(forms.ModelForm): def __init__(self, *args, **kwards): super(LinksForm, self).__init__(*args, **kwards) self.fields['full_link'].widget = forms.TextInput(attrs={'placeholder': 'full_link'}) self.fields['short_link'].widget = forms.TextInput(attrs={'placeholder': 'short_link'}) class Meta: model=LinksModel fields=["full_link","short_link"] def clean_short_link(self): short_link_list=LinksModel.objects.filter(user=self.) short_link=self.cleaned_data['short_link'] if short_link in short_link_list: raise ValidationError ("error") return short_link here views.py: class LinksPage(LoginRequiredMixin,CreateView): model=LinksModel template_name="News/links.html" form_class=LinksForm success_url= reverse_lazy("links") def form_valid(self,form): form.instance.user=self.request.user return super().form_valid(form) def get_context_data(self, **kwards): ctx = super(LinksPage, self).get_context_data(**kwards) ctx['links']=LinksModel.objects.filter(user=self.request.user) return ctx -
Getting value from looped form
I'm building an ecommerce with django that sells shirts and prints. My idea is showing a form for the shirts so customers can select the desired size. Like this: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row justify-content-center"> {% for product in products %} <div class="col-xs-12"> <img class="thumbnail" src="{{ product.imageURL }}"> <div class="box-element product"> <div class="container"> <div class="row"> <div class="col"> <h4><strong>{{ product.name }}</strong></h4> </div> {% if product.print %} <div class="col" id="size-info"> <h4 style="display: inline-block; float: right"> <strong>size: {{ product.print.size }}</strong></h4> </div> {% endif %} </div> </div> <hr> <div class="container"> <div class="row"> <div class="col-xs-2"> <div class="row"> {% if product.shirt %} <div class="col select-outline"> <select id="size-selector" class="browser-default custom-select"> <option value="" disabled>Size</option> {% for value, text in product.shirt.available_sizes %} <option value="{{ text }}">{{ text }}</option> {% endfor %} </select> </div> {% endif %} </div> </div> <div class="col-8"> <button data-product="{{ product.id }}" data-action="add" data-size="{{ text }}" class="btn btn-outline-secondary add-btn update-cart">Add to Cart </button> <a class="btn btn-outline-success" href="#">View</a> </div> <div class="col"> <h4 style="display: inline-block; float: right"><strong>${{ product.price }}</strong> </h4> </div> </div> </div> </div> </div> {% endfor %} {% endblock content %} </div> All the products are looped, and if the product is a shirt, it will contain this "size-selector" … -
Django: when using a customer user model (AbstractBaseUser), what is the best way to organise the forms across the admin.py and forms.py files?
I'm new to programming and Django, and I'm building a website implementing a custom user model using AbstractBaseUser. I want the forms in the admin site to mirror almost all of the forms being used by clients on the website. For example, creating a user on the live website will require the same data inputs as when creating a user on the admin site, and the same applies to other forms like creating posts. How should I arrange the forms across the admin.py and forms.py files? Should I build them in admin.py and then import them into forms.py? Or the opposite? Or should I keep them completely separate (both inheriting from the same classes and referencing the same models)? Or have I just misunderstood the relationship between admin.py and forms.py? -
Traslate this queryset?
My query is made in MYSQL I would like to know how to translate it to the ORM django tnhanks you SELECT *,(SELECT count(*) FROM tesisnueva.donador_desactivar ds where ds.motivo=1 and ds.donador_id= dd.id and date_add(ds.fecha_desactivar, INTERVAL 90 DAY)<now()) as cantidad FROM tesisnueva.donador_donador dd where dd.genero='F'; -
How to use Rest Framework's default token authentication view?
I am trying to use DRF's builtin TokenAuthentication view, but I can't get it to work. Here is the test: import requests import json data = json.dumps({ 'username': 'test-sandbox-root', 'password': 'password' }) headers = {'Content-Type': 'application/json'} r = requests.post('http://localhost:8000/api/auth', data=data, headers=headers) >>> r.status_code 400 >>> r.text '{"non_field_errors":["Unable to log in with provided credentials."]}' But the user clearly exists: >>> User.objects.get(username='test-sandbox-root', password='password') <User: test-sandbox-root> I've added the DEFAULT_AUTHENTICATION_CLASSES to my settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } And migrated the rest_framework.authtoken app: INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', ... ] And added optain_auth_token to my urls.py: from rest_framework.authtoken import views urlpatterns = [ path('/api/auth', views.obtain_auth_token), ] What am I missing? -
Django - Creating Field that is Product of Other Fields and Access on Querysets and Serializers
I have a model that has two fields hours and hour_cost. I want a field that is named total_cost where total_cost = hours * hours_cost. I thought of creating a new field in the model, but after some browsing on stackoverflow I came to the conclusion that I shouldn't be saving total_cost to database and I need to use the @property. SO 1 or annotate every queryset with total_cost. Models.py class Example(models.Model): hours = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) hour_cost = models.FloatField(blank=True, null=True) @property def total(self): return self.hours * self.rate But I would like for total to be in every queryset when I do Example.objects.all() automatically and for it to also be added to automatically to the serializers(what I mean by that is that I want 'total' included on the API response, maybe I don't need it on serializer, just queryset?). I've been looking on stackoverflow and many of the answers seem outdated 2011, 2012. Some look too complex for what I'm trying to do and some look like they are not following best programming practices. Is there a clean way to add automatically add the @property fields to querysets, admin, and APIs? -
Django Allauth signup form not saving custom fields
I'm trying to do something that should be very simple: adding a field to signup and saving it to my user object. I am using allauth, so the way this is supposed to be done as far as I can tell is by modifying the allauth form for signup. I've followed the instructions here: How to customize user profile when using django-allauth: This is what my forms.py looks like: from allauth.account.forms import SignupForm from django import forms UNASSIGNED = 'NA' CLIENT = 'CL' USER_TYPE_CHOICES = ( (UNASSIGNED, 'Unassigned'), (CLIENT, 'Client'), ) class CustomSignupForm(SignupForm): user_type = forms.CharField( widget=forms.Select(choices=USER_TYPE_CHOICES)) def signup(self, request, user): user.user_type = self.cleaned_data['user_type'] user.save return user and then my custom user: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) UNASSIGNED = 'NA' CLIENT = 'CL' USER_TYPE_CHOICES = ( (UNASSIGNED, 'Unassigned'), (CLIENT, 'Client'), ) user_type = models.CharField(max_length=2, choices=USER_TYPE_CHOICES, default=UNASSIGNED) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) I know that the field that I added to the user works as I can see it in the admin and access it …