Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I return information from a single form from a django modelformset, getting validation error
I am trying to use django modelformset to display and collect information on the webpage. I want to use the submitted form information elsewhere in the application. However, when I submit the form it won't validate. I am getting the this error message: ValidationError: ['ManagementForm data is missing o$ has been tampered with'] I think what is happening is that I am using the modelformset incorrectly and I am submitting a single form instead of the formset. To build my page I loop over each form within the formset and create subforms with their own submit buttons. Is this a misuse of a modelformset? The behavior I would like to have is the user enters new values for new_field and clicks submit on the form. Then field1 and new_fieldfor only that row are submitted back to views.py. Any help or suggestions would be greatly appreciated views.py def query_page(request): PipelineFormset = modelformset_factory(Pipeline, form=PipelineForm) if request.method == "POST": form = PipelineFormset(request.POST) print('form recieved') if form.is_valid(): print('valid') # further processing and redirect formset = PipelineFormset() return render(request, 'lio/query.html', { 'formset': formset}) forms.py class PipelineForm(ModelForm): new_field = forms.CharField(max_length=2) class Meta: model = Pipeline fields = '__all__' template.html <table class="table table-striped"> <thead> <tr> <th scope="col">Field1</th> … -
How does a database one-to-many lookups get optimized?
sorry for this question, searched far and wide but found no answers. How does a one-to-many lookup in the database get optimized? For example: I am creating an app using Django and Postgresql that works like a copy of Google Calendar. There's a table for days and each day has a number of tasks. I will want to search for tasks in each day pretty often for many users. (Each user has many days, each day has many tasks) Does the lookup search a giant list of tasks for tasks that have a given day ID? Or is it somehow optimized (for example each day has in reality an additional hidden field containing an array of all tasks)? If it is not optimized would it not be a better idea to just add such an array field to my days table? Thank you so much for your help. -
Django ManyToManyField referring to other application returns "app.model.None"
I'm trying to get a model ManyToManyField from another app and make a list, but it returns "app1.Model.None" when trying to call it in the template. app1.models class Illness(models.Model): title = models.CharField(max_length=255) app2.models class Client(models.Model): illnesses = models.ManyToManyField('app1.Illness', blank=True) client.html <p>{{ client.illnesses }}</p> app2.views.py class TheDetailView(generic.DetailView): template_name = 'client.html' model = Client The HTML rendering returns only "app1.Illness.None" for that part. I understand I would do a {% for %} loop to list them, but when I try that the section just stays blank. What am I doing wrong? Thanks for all the help in advance. -
500 Server Error after deployment Django in App Engine
I am trying to deploy a django website for sharing notes using app engine. Everything works fine until i try to upload file to my database either through app interface or admin interface it results in 500 Server error. As i have gone through similar question i know error is not because of app engine. but i am really confused because it works fine locally. i was able to upload file to database connecting it through cloud proxy. I tried to check log and debug but didn't give any clue. additional info I'm using django 3.0.3 here is my views.py: from django.shortcuts import render, redirect from .models import notes from .forms import upload import datetime # Create your views here. def home(request): context={} context["dataset"] = notes.objects.all() return render(request, "noteitdown/home.html", context) def upload_view(request): context = {} date = datetime.date.today() if (request.method == 'POST'): form = upload(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data entry = notes(author_name=data["author_name"], date_of_pub=date, department=data["department"], file=data["file"]) entry.save() return redirect('home') else: print(form.errors) form = upload() context["form"] = form return render(request, "noteitdown/upload.html", context) def about(request): return render(request, "noteitdown/about.html") and here is my Models.py: from django.db import models # Create your models here. class notes(models.Model): author_name = models.CharField(max_length=20) date_of_pub = models.DateField() department … -
Django including Redis To Go on Heroku
I have spend the last couple of days trying to set this up for my website and have been failing to understand this particular error. I used the Django Cookiecutter boiler tamplate for my project. I have added Celery locally with Redis to perform tasks, this works great. I have deployed my project to Heroku. I am now trying to implement the same tasks in my production environment but instead of Redis, I am now using a heroku add-on named Redis To Go. I did so as followed; In my settings: I have copied this from the redis to go tutorial. No adjustments have been made other than changing urlparse import to meet Python 3 standards. production.py import os from urllib.parse import urlparse redis_url = urlparse(os.environ.get('REDISTOGO_URL', 'redis://localhost:6959')) CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'DB': 0, 'PASSWORD': redis_url.password, } } } Procfile I've added the following line to my Procfile and added a second dyno for my worker. worker: celery -A appname worker --beat The worker seems to be working. State changes and then it closes. It obviously can't connect, see error. Heroku Log 2020-05-16T02:07:58.647226+00:00 app[worker.1]: [2020-05-16 04:07:58,647: ERROR/MainProcess] consumer: Cannot connect to … -
Printing some medical receipt from django
So, i'm working in a Django Project for a Doctor, in which i need to print the medical receipt based on the values inserted into a ModelForm through a UpdateView, there are two conflicts i am facing. I would like that the success_url to redirect me to the same page, something like hitting the 'Save' or 'Submit' button from the form and not sending me to other page just stay in the same. I would like to know how can i create a pdf to be printed but based on the values inserted in that updateview, i've seen some tutorials in the internet but they just render some random text into a html template and use xhtml2pdf to create it to PDF and showing the content using a generic View, but i don't know what path to take so i can use those specific values to create a pdf. As you can see in my html i have a button with an anchor tag that holds 'Imprimir', so what i mean with all this is entering the update view, filling all the required fields, saving the content and redirecting me to the same page with the content saved, so that … -
How to use URL regexp to match exact date of a post in Django?
I'm developing a website and blog for myself using Django. I'm using Python 3.8 and Django 3.0 and I've been having a lot of trouble trying to include the date of post creation in the URL. While I was finally able to get my URL to look something like: "mywebsite.com/blog/2020/mm/dd/.html", I am not getting a 404 if I change any part of the date. For example if I manually change the URL to: mywebsite.com/blog/2021/mm/dd/.html, the webpage still loads without presenting an error. Can someone help me figure out where I can edit the code to correct this issue? Something where I can issue a 404 if the URL isn't exactly what is pulled from the datetime field? My models.py, views.py, and URLs.py are attached below: Models.py class Blog(models.Model): title = models.CharField(max_length=500, help_text='Title of the Blog Post') author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True) **created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField(help_text='Content of the Blog Post') topic = models.ManyToManyField(Topic, help_text='Topic of this Blog Post') slug = models.SlugField( null=False, unique=True, max_length=500, editable=False, ) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): kwargs = { 'year': self.**created_on.strftime("%Y"), 'month': self.**created_on.strftime("%m"), 'day': self.**created_on.strftime("%d"), 'slug': self.slug, } return reverse('blog-detail', kwargs=kwargs) def save(self, *args, **kwargs): … -
H14 error upon Django app deployment on Heroku
I tried today to deploy my Django app on Heroku. I first had success and got the message that it is deployed. However upon Heroku open I had a screen informing me that an error occurred and that I should check the logs which look as follows: 2020-05-17T21:01:16.000000+00:00 app[api]: Build succeeded 2020-05-17T21:01:23.528711+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=wsb-project.herokuapp.com request_id=4ea57e57-b230-4d49-99d6-f5f17856b589 fwd="85.221.138.216" dyno= connect= service= status=503 bytes= protocol=https 2020-05-17T21:01:23.897006+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=wsb-project.herokuapp.com request_id=59fc1c4d-330c-4084-8e9e-1a3d7d8ed292 fwd="85.221.138.216" dyno= connect= service= status=503 bytes= protocol=https 2020-05-17T21:09:45.484945+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=wsb-project.herokuapp.com request_id=f1cd7d3d-8781-49b8-80e0-278ca06139ce fwd="85.221.138.216" dyno= connect= service= status=503 bytes= protocol=https 2020-05-17T21:09:45.885362+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=wsb-project.herokuapp.com request_id=64c1d78c-8e75-47d0-b748-9ffbf239c545 fwd="85.221.138.216" dyno= connect= service= status=503 bytes= protocol=https Heroku ps tells me that no dynos are on my app. I tried this tutorial: and when scaling dynos I was informed that "couldn't find that process type(web)" So I tried to clear and add the buildpacks again using this link And still nothing works. Thanks in advance in any of you know where I could find a solution as I am slowly running out of options here :) Cheers. -
Can only help me fix a 405 error with Django form submission?
I'm having an issue when submitting a form within a class-based view. I'm using the FormMixin in a detail view, and when I submit the form I get a 405 error. I've tried chopping and changing the code in views, but nothing seems to be working. Models class Bid(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) tender = models.ForeignKey(Tender, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100) specification = models.TextField() timeline = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) price = models.IntegerField() def __str__(self): return self.title def get_absolute_url(self): return reverse('bid-detail', kwargs={'pk': self.pk}) Views class TenderDetailView(FormMixin, LoginRequiredMixin, DetailView): model = Tender template_name = 'it_me/tender_detail.html' form_class = BidForm def get_success_url(self): return reverse('tender-detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(TenderDetailView, self).get_context_data(**kwargs) context['form'] = BidForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(TenderDetailView, self).form_valid(form) forms class BidForm(forms.ModelForm): class Meta: model = Bid fields = ('title', 'specification', 'timeline', 'price') Templates <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Post Bid </button> </div> </form> </div> {% for bid in tender.bids.all %} <div class=" col-md-12 comment"> <div class="date">{{ bid.date_posted|date:"F d, Y" }}</div> <strong>{{ bid.author }}</strong> … -
Can you use a django app in an asp.net project
So I currently have a web app developed in ASP.NET MVC framework and deployed on a domain through azure app service. This app has three main types of user roles: Student, Team and Partner. Through this web app partners and students after authentication can do a certain set of tasks. For eg, partners and students can fill a form and submit the response. These responses are received and reviewed by the team user role. Obviously there is a lot more functionality available to the authenticated user than just filling a form. While developing this application, due to business requirements more priority was given to the development of partner and team user roles. So the interface and features available to both these roles is fairly developed and being used by about 2000 users. The student role amidst this development time of 1 year has been left quite behind. So now due to new requirements we would like to build the student role interface and features in the same application but by using the django framework. The student role will still interact with the team role. As in a form submitted by a student will be received by the team role. We … -
how to solve 'AnonymousUser' object has no attribute '_meta' error in django
I am trying to make a login interface. but after submitting form this error ' AnonymousUser' object has no attribute '_meta' occurs. how to solve this issue? I can not find any solution. i have also tried to get data using form._cleaned_data.get() method. still it does not work. my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from diabetes.models import UserSignupModel class UserSignupForm(UserCreationForm): email=forms.EmailField(max_length=60,help_text="add a valid email address",required=False) name=forms.CharField(max_length=15,help_text="add a valid name") age=forms.CharField(max_length=15) class Meta: model=UserSignupModel fields=('email','name',"username",'age',"password1","password2") class UserLoginForm(forms.ModelForm): password=forms.CharField(label="password",widget=forms.PasswordInput) class Meta: model=UserSignupModel fields=("email","password") my models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email,age,name, username, password=None): #if not email: #raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,age,username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60,blank=True,null=True) age = models.CharField(max_length=15) name = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff … -
Replace objects in a django database (Python 3.8.2)
I'm adding the edit function to my Todo list web app, but I don't know how to write it. Can someone help me? <form action = 'edit_task/' method = 'POST'>{% csrf_token %} <input type="text" name = 'content_2' class="form-control" placeholder="Edit Task" style = 'box-shadow: none; border-color: transparent;' autofocus wrap required> <button type="submit" class="btn btn-dark mt-2 mb-2" name = 'edit'>Edit Task</button> </form> This is the link for the other issue I resolved: How can I show/hide a HTML <form> with a python (django) function? -
Authorized Signature Creation in Django models to know Created_by, modified_by [closed]
from django.db import models from django.contrib.auth import User created_by =models.ForeignKey(User,on_delete=models.CASCADE) modified_by =models.ForeignKey(User,on_delete=models.CASCADE) created_on =models.DateTimeField(auto_now_add=True) Modified_on =models.DateTimeField(auto_now=True) -
Are Django model forms are required by default and how to set required to false for whole form?
models.py: class Venue(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2) created_date = models.DateTimeField(default=timezone.now) approved_venue = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return f"{self.title}" forms.py class VenueForm(forms.ModelForm): class Meta: model = Venue fields = [ 'title', 'content', 'city', 'address', 'phone', 'email', 'site', 'facebook', 'instagram', ] def __init__(self, *args, **kwargs): super(VenueForm, self).__init__(*args, **kwargs) self.fields['title'].label = "Име" self.fields['content'].label = 'Описание' self.fields['city'].label = 'Град' self.fields['address'].label = 'Адрес' self.fields['phone'].label = 'Телефон' self.fields['email'].label = 'E-mail' self.fields['site'].label = 'Сайт' html render: <form method="post" id="dialog_addVenue_part" enctype="multipart/form-data"> {% csrf_token %} {% for hidden in postForm.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form %} <div class="fieldWrapper"> <div class="errorcode{{field.html_name}}"> {{ field.errors }} </div> {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} <div id="map" style="height: 500px;"> </div> <div class="utf_addVenue_form"> <button type="submit" value="Изпрати">Изпрати</button> </div> </form> Part of HTML with required fields: <div class="fieldWrapper"> <div class="errorcodesite"> </div> <label for="id_site">Сайт:</label> <input type="text" name="site" maxlength="100" required="" id="id_site"> </div> <div … -
Implementing social authentication in Django Rest Framework using dj-rest-auth alongside django-allauth in a mobile app
I'm working on a django project that will contain a standard web application and expose an API to a mobile app built using Flutter. I would like my users to be able to authenticate using OAuth2 providers (Facebook, Google etc) both in the web application and the mobile app. They would be able to upload data using the mobile app and then view it in the web application. Here's my stack: django-allauth django-rest-framework dj-rest-auth OAuth app setup in Github I've got social authentication working properly in the web application using django-allauth and some API views setup using DRF. I'm using Github as a OAuth2 provider for the moment with the redirect URL pointed to the appropriate django-allauth Github provider view. They use the authorization code grant type. Which means that after the user has been authenticated by Github the request is redirected to a URL on the application that handles the user authentication. Right now it ends up in the django-allauth view that handles social logins. The problem I'm having is authenticating users using OAuth2 providers using the authorization code grant type in the mobile application so that they can query my API using their assigned token. The endpoint that … -
Django email validate
Good Evening, the client has asked me to create a second field like a dummy field for the email, so as to use this field to check the email inserted by the user.something like we have with password1 and password2. Is that realistic? Thank you -
Can't import local module in Django
I have a directory structure like this: |-- top-level-directory/ |-- django-app/ |-- some-app/ |-- models.py |-- ... |-- some-other-app/ |-- ... |-- local-module/ |-- __init__.py |-- ... |-- other-directory-with-scripts/ |-- file-where-import-works-fine.py In some-app/models.py, I have an import local-module statement. However, I get an error saying ModuleNotFoundError: No module named 'local-module'. I can import the module in other scripts outside the django directory without any problems. Any idea why this could be happening or how I can fix it? -
How can I update the content in the page without using other html files
I'm learning Django now and everytime I use an UpdateView or anything that changes the content of a form I always have to use other html files that have the form like author_update_form, is there a way to edit directly on the same page like how on youtube comments I can press on edit and I dont get directed to a different page? -
Plotly, multiple parameter sliders on plot
I am choosing between Plotly and Bokeh as framework to use when create some interactive graphs on my html template which is a Django app. I'd like to replicate below Bokeh example but with Plotly. I can find Plotly examples with one slider but not with several sliders/input boxes for more than one parameter. A similar question was raised on Plotly's forum in 2017, at that time however, it was not possible to have more than one slider on a html template. Is it possible today, and in such case, how? If not, is it fair to assume that I will have more flexibility in regards to simple interactions (such as described here) if I would choose Bokeh to start with? -
HttpResponseRedirect Reverse not working Django
I am trying to redirect my page after submitting a like button to the same page but I keep getting a NoReverseMatch at /score/like/2 Here is the urls urlpatterns = [ path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('', PostListView.as_view(), name='score'), path('<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('like/<int:pk>', LikeView, name='like_post'), Here is the views def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(reverse('post-detail', args=[str(pk)])) <-----Error highlighting here here is the templates <form action="{% url 'score:like_post' post.pk %}" method='POST'> {% csrf_token %} <button type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button> </form> <strong>{{post.total_liked}} Likes </strong> -
Permission error when deleting an uploaded file in Django
In my Django app, users can upload files and store them or view them or delete them. I have come to know that in newer versions of Django, it does not handle the deletion of the actual file if the Model instance is deleted. But I was also quick to find that calling .delete() method on FileField() does the job. So I have modified the delete() method of my Model class. But I receive some PermissionErorr that apparent resists the deletion of the file. This is my code class Attachments(models.Model): content = models.FileField(null=True, blank=True, upload_to=get_attachment_dir, help_text="Add important documents or pictures") parent_task = models.ForeignKey(ToDo, on_delete=models.CASCADE) uploaded_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Attachments of {self.parent_task.title}" def delete(self, *args, **kwargs): self.content.delete() super(Attachments, self).delete(*args,**kwargs) The error states that PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\User\\Desktop\\Python Development\\Django_ToDo_App\\media\\users\\arafat_ar13_1\\task_attachments\\257\\Calculator.py' How should I fix this error and actually delete file so that it doesn't clutter up my server space after the user is done with that file? Thanks for any help in advance. -
Django admin only on page filtering
I`m trying to add some functionality to django-admin. I need to create a "filter" or something like the one that would apply on a particular page. Specifically, I need to reduce the maximum size of objects on the page and exclude some objects from the output. And this is normal if each page will contain a different number of objects. "Page" refers to the page of the pagination mechanism. How to implement a similar "filter". Google did not give a any solutions (maybe I was looking badly) and I decided to ask a question here. -
X-axis values of chart don't match Y-axis values using Chart.js
I am trying to visualize the data from my MySQL database using Chart.js and Django. I have a result and it's almost what I want but not quite yet. I need timestamps (column "received_on" in database) on the x-axis and the values (column "message" in database) on the y-axis (Screenshot of my database). As can be seen on the picture of my database, I have 4 different data types so I need 4 different plots (like on the screenshot of my Chart). The Chart I am getting looks like this: Chart result I get. But the time of the point with value 88 like shown in the picture doesn't match with the correct or expected value on the x-axis according to the database. The value 88 as shown on the picture should have "2020-05-17 17:53:52.542578" as x-value but here it is "2020-05-17 17:53:50.217023". I think this problem might be because I have more values on the X-axis than data points/values per data type (I hope it makes sense). How can I get the data points / Y-values to match with the correct X-values for every graph? My code is below: <script> $(document).ready(function(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new … -
How to validate unique constraint on django rest framework?
How can i validate an unique constraint with a key that is not on the request payload? The key that i need to validate are user_id and sku but the request does not contain the user_id key. Example of payload: {'sku': '123', data: []} The serializers: class ProductConfiguration(serializers.Serializer): min_quantity = serializers.IntegerField(required=True) price = serializers.DecimalField( required=True, decimal_places=2, max_digits=10, coerce_to_string=False ) class ProductSerializer(serializers.ModelSerializer): sku = serializers.CharField(required=True) data = ProductConfiguration(many=True, required=True) class Meta: model = WholeSale # the "id" and "user_id" columns should not be included on the response exclude = ['id', 'user'] I need to validate that the user and sku key already exist. By default if the two keys user_id and sku were on the payload drf could take care of Unique error, how can i validate this two keys if one of them are not on the payload? -
Fill DropDown list from data in database - Django
I would like to be able to add and remove items from LANGUAGES, instead of them being hardcoded like this. Now I get what I need, which is DropDown with 'English', 'German' and 'Italian' choice. Now i need them to be in a SQLite database and retrived from there, with option to add new languages and remove/edit existing. Thanks in advance... LANGUAGES = [ ("1", "English"), ("2", "German"), ("3", "Italian"), ] language = models.CharField(max_length=50, choices=LANGUAGES, default=1, null=False)