Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save files via django serializers after processing them in my views?
I have a excel/csv file that I read using pandas once the user uploads the file. I process the file in my views.py and save them directly using the command df.to_excel("filename.xlsx") or df.to_csv("filename.csv") Is there a way to save the files through django serializer? I've tried df.to_excel("filename.xlsx") directly on the serializer data as shown on the code, but the file ends up writing to my disk directly instead of being saved via the serializer. data = { 'file': df_template.to_excel(output_file_name, index=False), 'created_for': project.id, } outputrecord_serializer = OutputRecordSerializer(data=data) if outputrecord_serializer.is_valid(): #print('Check if serializer is valid') outputrecord_serializer.save() #print('saved') else: print(outputrecord_serializer.errors) -
KeyError for 'id' field when ModelForm CheckboxSelectMultiple choices are 'id'
I am new to Django. I have a form where I want to have list of 'id's of model items as choices of CheckboxSelectMultiple field. Here is my example Models.py class TryDjango(models.Model): name = models.CharField(max_length=120) Views.py class trydjango_view(View): template_name = 'trydjango.html' failed_template = 'generic_error.html' viewContext = { "title" : "Page title ", "columnNames" : ["Name"], "url" : 'trydjango', 'loginInfo' : 'logout', } def get(self, request): self.viewContext['deleteTryDjangoForm'] = \ deleteTryDjangoForm(prefix='delete') login_result = getLogin(request) self.viewContext.update({'loginInfo' : login_result['loginInfo']}) return render(request, self.template_name, self.viewContext) ModelForms.py class deleteTryDjangoForm(forms.ModelForm): myPrefix ='delete-' class Meta: model = TryDjango fields = ['id'] def __init__(self, *args, **kwargs): super(deleteTryDjangoForm,self).__init__(*args, **kwargs) sportSeriesList = listOfSportSeries() print(sportSeriesList) self.fields['id'].widget = \ forms.CheckboxSelectMultiple(choices=[(1,1)]) #<<-- Line 399 in the error Finally the error I am getting KeyError at /trydjango/ 'id' Request Method: GET Request URL: http://127.0.0.1:8000/trydjango/ Django Version: 2.0.7 Exception Type: KeyError Exception Value: 'id' Exception Location: /Users/sbt/dev/trydjango/src/myPrjApp/modelforms.py in __init__, line 399 Where line 399 is the line "forms.CheckboxSelectMultiple(choices=[(1,1)])" from my form. The form doesn't give this error if I change the field from 'id' to 'name'. I have few other models whose primary keys are not the 'id' fields. I can delete those model items using the corresponding primary keys. However, the form fails only if the … -
is there a way to fix a database isssue on django?
I'm not sure if removed some pycache files and it messed my website up or if me pulling some files from git has changed my folders about but I'm getting database connect issues. I have tried makemigrations, migrate and runserver and I'm getting the same error each time. I can't uninstall wagtail or django as it comes up failed to create process. I'm getting the horrible feeling it might be time to scratch the project and start again. Here is the error self.connection = self.get_new_connection(conn_params) File "..\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 194, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "..\threading.py", line 926, in _bootstrap_inner self.run() File "..\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "..\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "..\runserver.py", line 120, in inner_run self.check_migrations() File "..\base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "..\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "..\loader.py", line 49, in __init__ self.build_graph() File "..\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "..\recorder.py", line 73, in applied_migrations if self.has_table(): File "..\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "..\base.py", … -
How to store a table to database in Django 2.1?
I use Django 2, that is why I post similar questions and I am a beginner in Django. Question: I have a table inside html, and I need to save it into database using view and model and form. Here are some part of the code: template.html <form method="post" action="/images/save/" enctype="multipart/form-data"> {% csrf_token %} <table class="table" border="1" id="tbl_posts"> <tbody id="tbl_posts_body"> {% for name, age in lines %} {% with i=forloop.counter0 %} {% with i|add:1|stringformat:"s" as i_id %} {% with id="rec-"|add:i_id %} <tr id={{id}}> <td><span class="sn">{{ i|add:1 }}</span>.</td> <td><INPUT type="text" name="txt1" value=""\></td> <td><INPUT type="text" name="txt2" value=""\></td> </tr> {% endwith %} {% endwith %} {% endwith %} {% endfor %} </tbody> </table> <input type="submit" value="Submit"> </form> model.py: class Names(models.Model): name= models.CharField(max_length=255) age= models.IntegerField() view.py: def save_form(request): template = "template.html" context = {'txt1': "Name", 'txt2': 0} if request.method == 'POST': dname= request.POST.get("txt1") dage= request.POST.get("txt2") names1= Names(name=dname, age=dage) names1.save() return render(request, template, context) Question: So, it works perfectly, but the issue is that It saves only the last row. I think there is a way to enter the whole data. I need to enter all data in the table not only the last row. Can someone help me? Update: lines is a zip a … -
Migrations issue in Cpanel postgresql
I have a query regarding Cpanel, Please help me out. I had created python application with using Django Framework and Postgresql as Database and I am facing issue while migrating the Database, Below is the mentioned error please do the needful. Thanks in Advance -
No phone number record in django admin site
Currently on my own django project at the admin site, I can only see username, email , first name, last name and staff status. The UserCreationForm I am using provided by django has a phone number text field that I included to let users key in their phone number, however, I cant seem to get the admin site to store the phone number record. Please tell me if there are any changes that should be made to my current code so that I can see the phone records. Wondering if there is anything that I should be including to my admin.py or forms.py. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', 'email'] def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, verify=True): raise forms.ValidationError("Invalid email") return email /* views.py */ from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() phone_number = form.cleaned_data['phone'] # do something with phone number?? username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') … -
Chained form fill in django form
I have a django model Models.py class ReceiveDocket(models.Model): sender_parent_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='sender_parent_client') client_location = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_location') received_at_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name='warehouse_list') class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_company = models.CharField(max_length=255, default=0) client_name = models.CharField(max_length=255, default=0) client_shipping_address = models.CharField(max_length=255, default=0) and a form of receive docket: Views.py @method_decorator([login_required, employee_required], name='dispatch') class ReceiveDocketFormView(CreateView): model = ReceiveDocket fields = "__all__" template_name = 'packsapp/employee/docketRecievedForm.html' def form_valid(self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The Docket was created with success!') return redirect('employee:docket_table') How can I change my views such that when I select the sender parent client it automatically fills the client address in client location or at least show the client address in the drop-down ? -
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 …