Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: Where to put readonly_fields?
I defined my model as following: from django.db import models class Books(models.Model): name = models.CharField(max_length=100) author = models.CharField(max_length=100) def __str__(self): return str(self.name) The problem is that when I want to make the author field readonly in admin.py as following: from django.contrib import admin from core.models import Books class Books(admin.ModelAdmin): readonly_fields=('author',) admin.site.register(Books) I get the following error upon running server: -
raise MultiPartParserError in Django2.2
I'm trying post the form data using 'XMLHttprequest' to the django views and i'm getting 'A server error occurred. Please contact the administrator.' in the browser console, and i'm getting following error raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary.decode()) AttributeError: 'NoneType' object has no attribute 'decode' in my terminal. The following is my code snippet. <html><head><tile></title> <body> <form> {% csrf_token %} <input type="text" id="in" name=""> <input type="button" id='' value="submit" onclick="myfunction()"> </form> <script type="text/javascript"> function myfunction() { var emailId = document.getElementById('in').value; var csrfToken = getCookie("csrftoken"); var myform = new FormData(); myform.append("email", emailId); var xhttp = new XMLHttpRequest(); xhttp.open("POST", '{% url "log" %}', true); xhttp.setRequestHeader('X-CSRFToken', csrfToken ); xhttp.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8"); xhttp.send(myform); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) } }; } </script> <body> </html> -
Django template convertion error when a number with thousand separator
I have some decimal values with thousand separator passed into a Django template as a list. It should be interpreted as a float value to do some JavaScript calculations. However due to the thousand separator it causing problems in the list iterations. See the code below as interpreted in the template. I have highlighted the values that have problems. Also note that I want thousand separator for other places, so it can not be turned off globally. I used the floatformat filter but no luck. data: [0.00, 0.00, 35,200.23, 2,910.36, 1,677.00, 0.00,], -
"'Template' object has no attribute 'strip'"
I am using python 3.6 on my local and jinja2 template code is working fine ,But on sever python version is 3.7 so while i am trying to update a resource then getting error "'Template' object has no attribute 'strip'" -
How to make Unlike with django-likes package?
I'm using django-secretballot and django-likes to make a simple like button. My problem with django-likes package that there is no example show how to make unvote / unlike after you liked an object.. I found this function 'remove_vote' in 'django-secretballot' but really I don't know how to use it with django-likes I will be glade if there is any example of how to use it. thanks -
File in PostgreSQL composite type in Django
I want to save file, which is in PostgreSQL user defined composite field. When saving file which is not in custom field, in save_form_data() setted attribute becomes FieldFile and that's probably what I want to happen with composite field too. When saving composite field however, I get the error "can't adapt type 'TemporaryUploadedFile'", since tuple element representing file, stays TemporaryUploadedFile. How do I save file in composite field? This is my composite field (models.py): class MyType(models.Field): name_in_field = models.CharField(max_length=100) file_in_field = models.FileField( upload_to=file_path, storage=OverwriteStorage() ) def db_type(self, connection): return "custom_field" def save_form_data(self, instance, data): # I want attribute to become tuple (CharField, FieldFile) # just like it happens with the file outside of MyType # but attribute becomes (CharField, TemporaryUploadedFile) # what is identical to data and throws error when saving # Default behavior: setattr(instance, self.name, data) # I suppose I should write something like below, but what exactly? # setattr(getattr(instance, self.name), "name_in_field", data[0]) # setattr(getattr(instance, self.name), "file_in_field", data[1]) I've prepared repo for testing. -
How to match specific word in url.py in django?
I am new to dJango. I got the following url address http://127.0.0.1:8000/polls/%7B%25%20url%20'main'%20%25 but my app didn't find the address when looked up my urls.py as below. from django.urls import path from . import views urlpatterns = [ path('main', views.main, name='main'), path('pageA',views.pageA,name='pageA') ] I know that it can be resolved by applying the regular expression but I failed to get the right solution. -
Django Default value for a custom user field is not added into the db tables
I'm working on a project using Python93.7) & Django(2.2) in which I have extended the user model to add a custom filed for the user. I have defined a default value for that field in the model but when I leave it empty on the form sibmission the default is not added into the DB. Here's my model: From models.py: class CustomUser(User): team = models.CharField(max_length=255, default='NotInGroup', blank=True) Here's my view: From views.py: if form.is_valid(): print('form is valid') print(form.cleaned_data['team']) if not form.cleaned_data['team'] == '': form.team = form.cleaned_data['team'] else: form.team = 'Default' print(form.team) user = form.save() If I leave it empty for form.team it prints out the Default' but not saved in DB. Here's my form: **Fromforms.py`:** class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('first_name', 'last_name', 'email', 'username', 'team', 'password1', 'password2') -
Google font not displaying
I am trying to get a Google font to load from css to my html template for my application. Can't get the "Upload schtuff" to assume the Bangers font. Here's the base.html: {% load static %} <!doctype html> <html> <title>{% block title %}Upload Schtuff{% endblock %}</title> <head> <link href="//fonts.googleapis.com/css?family=Bangers&display=swap" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> </head> <body> <div> <h1><a href="/">Upload schtuff </a></h1> </div> </body> </html> Here's the static/uploader/style.css: ''' h1 a, h2 a { color: #714D91; font-family: 'Bangers', cursive; } ''' I've also tried importing the font to the style sheet with @import url('https://fonts.googleapis.com/css?family=Bangers&display=swap'); Also tried importing it to the .html file <style> @import url('https://fonts.googleapis.com/css?family=Bangers&display=swap'); </style> It's got to be my link href lines, right? Thanks in advance! -
Django models making with with multiple condition
I am developing a app for cinema show seat booking and going through a trouble to design my models this is my current models: from django.db import models from django.contrib.auth import get_user_model class Seats(models.Model): seat_choice = ( ('AA', 'AA'), ('AB', 'AB'), ('BA', 'BA'), ('BB', 'BB'), ('CA', 'CA'), ('CB', 'CB') ) name = models.CharField(choices=seat_choice, max_length=2) def __str__(self): return self.name class Show(models.Model): show_choice = ( ('MORNING', 'MORNING'), ('NIGHT', 'NIGHT'), ) show_schedule = models.CharField(choices=show_choice, max_length=10) movie = models.CharField(max_length=50) def __str__(self): return self.show_schedule class Booking(models.Model): seat = models.OneToOneField(Seats, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) show = models.ForeignKey(Show, on_delete=models.CASCADE) I am trying to achieve like If a seat booked of a show, it can't be booked again later but it can be booked by later for another show. But my current models problem is: If i book a seat for a show, i cant book the same seat for another show (which is i dont want) My Requirement is simpe: If i book a seat for a show, later i should able to book the same seat for another different show but it cant be booked again for the same show... I know i can achieve it removing the show and using created like below: class … -
Using custom mixins in serializers
I am kind of new to Django and currently I am working on an endpoint which aggregates data. I have the mixin which returns user ID, timestamp and token: import cent class CentMixin(object): def get_cent_data(self, user_id=''): cent_timestamp = calendar.timegm(datetime.now().timetuple()) token = cent.generate_token(settings.CENTRIFUGE_SECRET, str(user_id), str(int(cent_timestamp))) return user_id, cent_timestamp, token I have written a serializer: class CentEndpointSerializer(serializers.Serializer): cent_user_id = serializers.IntegerField() cent_timestamp = serializers.DateTimeField() cent_token = serializers.CharField() And now I am wondering how to write a View for the serializer. Any suggestions? -
How to get weekly data from database
Now I'm making django crm app and i have a question. My question may be related to datetime() class. I'm gonna to show all data according to the date. For example,when a user logged in the site,I want to show all leads (which saved in database) separately according to the date,weekly,monthly,yearly. So my question is how can i select the week,month or year which today in. -
How to define which input fields the form has by pressing different buttons?
I have a form and a few buttons as below: <form method="GET" novalidate id="my_form"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> </form> <input name="page" type="hidden" form="my_form" value="1" id="submit"> <button type="submit" class="btn btn-success" form="my_form">Submit</button> <input name="page" type="hidden" form="my_form" value="1" id="1"> <button form="my_form" role="button" class="btn btn-link">1</button> <input name="page" type="hidden" form="my_form" value="2" id="2"> <button form="my_form" role="button" class="btn btn-link">2</button> <input name="page" type="hidden" form="my_form" value="3" id="3"> <button form="my_form" role="button" class="btn btn-link">3</button> As you see, I have four submit buttons. What I need is that if I pressed the submit button, the form that contains the first name and last name and the input field that adds page=1 to the GET be submitted. If I pressed, as an example, the button 3 (the last one), the form and only the input that has page=3 be submitted not the other inputs with page=1, page=2, page=3 . I am using this to solve a pagination problem. How can I do this? I prefer not using JavaScript, or if I have to, only a very simple script be used in the solution. -
Scrolling index.html to #contact after form submission (django)
index.html <section id="contact"> <form id="contactForm" method="get" action="{% url 'contact-form' %}"> ... <button class="btn btn-common" id="submit" type="submit">Submit</button> </form> </section> where {% url 'contact-form' %} expands to contact-form/ After submitting this form, I want the page to scroll to #contact where the form is located(if there are form validation errors). I've tried $("#contactForm").submit( function() { $('html, body').animate({ scrollTop: $("#contact").offset().top }, 2000); return false; }); But the scroll doesn't work. -
Docker-compose cannot start my Django app
I am new from Docker and i would to run my Django app on it, so i do this: -My Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ My docker-compose.yml version: '3' networks: mynetwork: driver: bridge services: db: image: postgres ports: - "5432:5432" networks: - mynetwork environment: POSTGRES_USER: xxxxx POSTGRES_PASSWORD: xxxxx web: build: . networks: - mynetwork links: - db environment: SEQ_DB: cath_local SEQ_USER: xxxxx SEQ_PW: xxxxx PORT: 5432 DATABASE_URL: postgres://xxxxx:xxxxx@db:5432/cath_local command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db well on my docker shell i point to Dockerfile directory, if i run an ls command from y path i see the manage.py file, but if i run: docker-compose up i get this error: web_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory core_web_1 exited with code 2 Why my app don't find manage.py file that is in the same position as the "docker-compose up" command is? PS: No /code folder is created when i run docker-compose command. Is it correct? So many thanks in advance -
How to register Django 2.x
How to register, log in and log out on Django 2.x.In my country, little information on this topic, dogs don't read, because I already tried to do something on them and spent a lot of time .Sorry for bad english -
Django ORM: How can I sort by date and then select the best of the objects within a foreign key?
I realize my title is kind of complex, but please allow me to demonstrate. I'm on Django 2.2.5 with Python 3. Here are the models I'm currently working with: from django.db import models from django.db.models import F from django.contrib.postgres.indexes import GinIndex from django.contrib.postgres.search import SearchVectorField, SearchVector, SearchQuery, SearchRank class Thread(models.Model): title = models.CharField(max_length=100) last_update = models.DateTimeField(auto_now=True) class PostQuerySet(models.QuerySet): _search_vector = SearchVector('thread__type') + \ SearchVector('thread__title') + \ SearchVector('from_name') + \ SearchVector('from_email') + \ SearchVector('message') ### # There's code here that updates the `Post.search_vector` field for each `Post` object # using `PostQuerySet._search_vector`. ### def search(self, text): """ Search posts using the indexed `search_vector` field. I can, for example, call `Post.objects.search('influenza h1n1')`. """ search_query = SearchQuery(text) search_rank = SearchRank(F('search_vector'), search_query) return self.annotate(rank=search_rank).filter(search_vector=search_query).order_by('-rank') class Post(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) timestamp = models.DateTimeField() from_name = models.CharField(max_length=100) from_email = models.EmailField() message = models.TextField() in_response_to = models.ManyToManyField('self', symmetrical=False, blank=True) search_vector = SearchVectorField(null=True) objects = PostQuerySet().as_manager() class Meta: ordering = ['timestamp'] indexes = [ GinIndex(fields=['search_vector']) ] (There's some stuff in these models I've cut for brevity and what I believe is irrelevance, but if it becomes important later on, I'll add it in.) In English, I'm working with an app that represents the data in an email listserv. … -
Django Rest Framework: Serialize multiple images to one post in
I am trying to be able to serialize and upload multiple images to associate with each post. This is my models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save from .utils import unique_slug_generator class Painting(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default="", on_delete=models.CASCADE) title = models.CharField(blank=False, null=False, default="", max_length=255) slug = models.SlugField(blank=True, null=True) style = models.CharField(blank=True, null=True, default="", max_length=255) #need to figure out why there is problem when this is False description = models.TextField(blank=True, null=True, default="") size = models.CharField(blank=True, null=True, default="", max_length=255) artist = models.CharField(blank=True, null=True, default="", max_length=255) price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=20) available = models.BooleanField(default=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ["-timestamp", "-updated"] class PaintingPhotos(models.Model): title = models.ForeignKey(Painting, default="", on_delete=models.CASCADE) image = models.ImageField(upload_to='uploaded_paintings') def pre_save_painting_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(pre_save_painting_receiver, sender=Painting) my serializers.py from django.contrib.auth import get_user_model, authenticate, login, logout from django.db.models import Q from django.urls import reverse from django.utils import timezone from rest_framework import serializers from .models import Painting, PaintingPhotos User = get_user_model() class UserPublicSerializer(serializers.ModelSerializer): username = serializers.CharField(required=False, allow_blank=True, read_only=True) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', ] # # add PaintingImagesSerializer with the images model here … -
From where this models.Model coming from in django?
As I was creating Django project want to create Models for storing in database later. But in the video the person types : from django.db import models class Post(models.Model): title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User) Okay, I understand that we are inheriting models class so we can use its properties like CharField, TextField but why we are writing models.Model while inheriting. Can't we just write models? Why he is importing the class method -> Model? Am I missing something in OOPS? -
Error deploying app on google app engine - can't find information on error
I have a Django app which works just fine on my local server. I am now trying to deploy it on GAE, and I'm getting this error ERROR: (gcloud.app.deploy) Your application does not satisfy all of the requirements for a runtime of type [python3]. Please correct the errors and try again. Unfortunately I can't find much information on what the error message is referring to, or whether there is a log that I can look at? Any help would be MUCH appreciated! -
How to include validate_email package into django UserCreationForm?
I downloaded a email validator package from PyPI, link is: https://pypi.org/project/validate_email/ and using pip install validate email and pip install py3dns (since my python is version 3.6.7) into my django project. The problem is I cant seem to get the validate_email function to work on my django project, just wondering what code should I be writing on my django's forms.py and views.py. (not using models.py yet). Please tell me what did I do wrong and what changes should be made to my current code in forms.py. I included "from django.core.validators import validate_email" as seen in forms.py below to try to validate the email entered by any user but it seems that the validate_email works differently from the validate_email from "from validate_email import validate_email". The validation that I need is from PyPI as it is more accurate in validation (e.g. can check if an email is existent or not) whereas the validate_email form django.validators only checks for invalid format and thats it. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import validate_email from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', … -
App Crashed on my Django app using Heroku
These are all of the error messages: 2019-09-17T01:27:59.832820+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=ab1e197e-ab72-4d03-bec2-8ba06c3db870 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:28:00.339514+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=cad19ccd-31d0-46d1-a31a-891068cc7c87 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:44.241612+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=43785608-8070-4b01-8543-fb7bc84c985e fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:44.744082+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=70e0e3a6-fe27-41fb-924d-c99960303953 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:46.607921+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=52842cc3-1869-411a-936c-92b3cae86329 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:47.003348+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=1253c722-5c0e-42f3-8679-f51dad8622e9 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https Could Somebody please help me? -
In my django app, how to show all posts of similar category if that category is selected?
I'm new to Django so bear with me please. I'm creating an app for posting jobs, and it's based on Corey Schafer's social media tutorial. Each post/job in my app has a category field (NGO, Engineering, Oil&Gas, etc...) My goal is if I select a category, then all jobs of the same category are listed. Corey did the same with the "all posts of a selected author " approach, but I couldn't do similar thing with my category goal. I appreciate all help for guidance. If the pics aren't enough, a general guidance is fine, thanks! urls.py views.py model.py -
Rewriting a Django application from ground-up, is it possible to migrate user model?
I have a web app that I developed while learning back-end web development. I deployed it a while back and ended up getting some real users registered. Unfortunately, I wrote some smelly code and it is becoming very difficult to implement any new features without having to refactor large portions of the code base, so I am planning to rewrite the back-end. The main issue I'm facing is whether there is a way to migrate the CustomUser model I've created to a new PostgreSQL database. Is this possible by simply recreating the same model in the new backend, then doing a pg_dump and restore? -
How to use ajax to link views to form? Django
views.py def contact_form(request): if request.is_ajax(): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("django.contrib.staticfiles.urls")), path("single-post/", single_post, name="single-post"), path("contact-form/", contact_form, name="contact-form"), path("", index), ] index.html <form id="contactForm" method="get" action="{% url 'contact-form' %}"> <input type="text" class="form-control" id="name" name="name" placeholder="Name"> <input type="text" placeholder="Subject" id="msg_subject" class="form-control" name="subject"> <input type="text" class="form-control" id="email" name="email" placeholder="Email"> ... <button class="btn btn-common" id="submit" type="submit">Submit</button> </form> When I submit my form I get: The view app.views.contact_form didn't return an HttpResponse object. It returned None instead. How do I use ajax to link the form to contact_form?