Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am not being redirected to the page i want to be redirected to while making a website using django
This is my views.py from django.shortcuts import render, redirect from django.conf.urls import url from .models import Category,Product from django.contrib.auth.models import User, auth def signup(request): if request.method == "POST": first_name=request.POST['first_name'] last_name=request.POST['last_name'] email=request.POST['email'] mobile=request.POST['mobile'] password=request.POST['password'] cpassword=request.POST['cpassword'] user=User.objects.create_user(first_name=first_name,last_name=last_name,email=email,mobile=mobile,password=password) user.save(); return redirect('/') else: return render(request,"signup.html") This is the form i am using in the html page <form class="row contact_form" action="signup" method="post" novalidate="novalidate"> When i enter data in the form and click on submit it redirects me to /signup/signup (Page not found) instead of index.html(home).Also the user data is not being saved in postgresql auth_user. -
Rendering data of ManyToMany relationship in templates in django
I'm trying to render the name of all the products in templates. How do I do that in dashboard.html in the code given below? It is simple in ForeignKey but i cannot figure it out in ManyToMany Relationship.Please help Models.py CATEGORY=(('INDOOR','Indoor'),('OUTDOOR','Outdoor')) name=models.CharField(max_length=100) category=models.CharField(max_length=20, choices=CATEGORY, blank=True, default='INDOOR', help_text='Item Category',) date_created=models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Order(models.Model): STATUS=(('PENDING','Pending'),('OUT FOR DELIVERY','Out For Delivery'),('DELIVERED','Delivered')) customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL) date_created=models.DateTimeField(default=timezone.now) product=models.ManyToManyField(Product) status=models.CharField(max_length=20, choices=STATUS, blank=True, default='PENDING', help_text='Delivery Status',) def __str__(self): return self.customer.first_name views.py def home(request): order=Order.objects.all() context={ 'order':order, } return render(request,'accounts/dashboard.html',context) dashboard.html <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {%for i in order%} <tr> <td>{{i}}</td> //in this line <td>{{i.date_created}}</td> <td>{{i.status}}</td> <td><button>Update</button> </td> <td> <button>Update</button></td> </tr> {%endfor%} -
How can I use two different functions in one HTML page Django
I wanted to create a website where I can List all created forms and also create forms in the same page. But I could'n figure it out. Firstly I tried it with two classes which linked to the same HTML file but then I read that this is wrong then I tried to write the two classes in one with the get post and get_queryset functions. However now I can only create forms and if I am deleting the get function the I can list the created forms. Thank You very much and here are my views.py and HTML. views.py from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from django.views import generic from .models import PostModel from .forms import PostForm # Create your views here. class PostList(generic.ListView): template_name = 'home.html' form_class=PostForm def get_queryset(self): return PostModel.objects.order_by('-created_on') def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self,request,*args, **kwargs): form=self.form_class(request.POST) if form.is_valid(): form.save() return redirect('home') return render(request,self.template_name,{'form':form}) class PostDetail(generic.DetailView): model = PostModel template_name = 'post_detail.html' home.html {% extends "base.html" %} {%block content%} <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-6 mt-3 left mx-auto"> {% for post in postmodel_list %} <div class="card mb-4 block"> <a class="overlay" … -
django queryset get all foreignkey data filtered from model object
I have a models like class File(models.Model): user = models.ForeignKey(User) name = models.CharField() file = models.FileField() class Data(models.Model): file = models.ForeignKey(File, related_name"datafile") name = models.CharField() email = models.EmailField() Here I want to get all the Data uploaded by user on File. User uploads a file which contains data. I need to get all the Data form a query. How to do tha ?? -
How to show filtered items only after adding to cart on home page in django?
i am practicing django by making an ecommerce app. I also share the video so that you can also check the problem. https://youtu.be/crYlZ7Bo8y4 Application is working perfectly but when i filter the product according to selected category and press add to cart button then it will show all products of all categories instead of showing selected products under that category. Can you please help me out in this. index.html page: {% extends 'base.html' %} {% block content %} {% load cart %} {% load custom_filter %} <!-- body --> <div class="container-fluid mt-3"> <div class="row"> <!-- filter --> <div class="col-lg-3 mx-auto"> <div class="list-group"> <a href="/" class="list-group-item list-group-item-action">All Products</a> {% for category in categories %} <a href="/?category={{category.id}}" class="list-group-item list-group-item-action">{{category.name}}</a> {% endfor %} </div> </div> <!-- all products --> <div id='products' class="col-lg-9 mx-auto"> <div class="row mx-auto"> {% for product in products %} <div class="card mx-auto mb-3" id={{product.id}} style="width: 18rem;"> <img class="card-img-top" src="{{product.image.url}}" alt="Card image cap"> <div class="card-body"> <p class="card-title">{{product.name}}</p> <p class="card-text"><b>{{product.price|currency}}</b></p> <!-- {{product | is_in_cart:request.session.cart }} --> </div> <div class="card-footer p-0 no-gutters"> {% if product|is_in_cart:request.session.cart %} <div class="row no-gutters"> <form action="/#{{product.id}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="text" name='product' value='{{product.id}}'> <input hidden type="text" name='remove' value='True'> <input type="submit" value=" - " class="btn … -
Trying to send a post request getting error message - 'invalid json'
I'm trying to send a post request using django, and I'm getting the following error. The request is invalid. Details: parameters : Invalid JSON. A token was not recognized in the JSON content This is my function def uploaddd(request): url = "https://service.com/indexes/hotels/docs/index?api-version=2020-06-30" data = { "value": [ { "@search.action": "upload", "HotelId": "17", "HotelName": "Secret Point Motel", "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York.", "Category": "Boutique", "Tags": [ "pool", "air conditioning", "concierge" ], "ParkingIncluded": 'false', "LastRenovationDate": "1970-01-18T00:00:00Z", "Rating": 3.60, "Address": { "StreetAddress": "677 5th Ave", "City": "New York", "StateProvince": "NY", "PostalCode": "10022", "Country": "USA" }, "Location": { "type": "Point", "coordinates": [ -73.975403, 40.760586 ] }, "Rooms": [ { "Description": "Budget Room, 1 Queen Bed (Cityside)", "Description_fr": "Chambre Économique, 1 grand lit (côté ville)", "Type": "Budget Room", "BaseRate": 96.99, "BedOptions": "1 Queen Bed", "SleepsCount": 2, "SmokingAllowed": 'true', "Tags": [ "vcr/dvd" ] }, { "Description": "Budget Room, 1 King Bed (Mountain View)", "Description_fr": "Chambre Économique, 1 très grand lit (Mountain View)", "Type": "Budget Room", "BaseRate": 80.99, "BedOptions": "1 King Bed", "SleepsCount": 2, "SmokingAllowed": 'true', "Tags": [ "vcr/dvd", "jacuzzi tub" ] } ] } ] } headers = {'Content-Type': 'application/json', 'api-key': … -
How to introduce html button inside text area of an email?
I am trying to build an django app, and added forgot password functionality to my login. Though django handles everything very swiftly with bulidin modules but the email it sends to user's email address is very blunt. It sends content of html file password_reset_email.html to the user to reset the password. first image mentioned below is the django's default email template and second image is the result i want to achieve, can anyone guide me how to do that. django's default reset image This is the final result i want. -
django-import-export skip if the record is duplicated
I have an xlsx file with over 5 thousand records, there is one unique cell_id field. How to make it so that when importing if the record is duplicated just skip? Sorry for my bad english) models.py: class BaseStation(models.Model): cell_id = models.CharField(max_length=20, unique=True, verbose_name=_('Cell ID')) site_name = models.CharField(max_length=20, verbose_name=_('Site name')) sector_name = models.CharField(max_length=20, verbose_name=_('Sector name')) resources.py: class BaseStationResource(ModelResource): class Meta: model = BaseStation import_id_fields = ('cell_id',) skip_unchanged = True use_bulk = True exclude = ('id',) admin.py: class BaseStationAdmin(ImportMixin, admin.ModelAdmin): resource_class = BaseStationResource list_display = ('cell_id', 'site_name', 'sector_name') -
Customizing Django Oauth Toolkit Exceptions
Is there any way to customize all Django OAuth Toolkit's exception messages and formatting without overriding all its views? For reset_framework exceptions, this can be easily done by implementing your own exception handler. The problem is, Django OAuth Toolkit's exceptions don't seem to get caught by my own exception handler. This is an example of how Django OAuth Toolkit's exceptions look like by default: { "error": "invalid_grant" } And This is how I want my exceptions to look like: { "code": "E_INVALID_GRANT", "message": "blah blah blah" } Any help would be greatly appreciated. -
fail to translate variable in Django/js with ‘gettext’
my code: function load_local_storage(item) { let title; if (item == "history") { title = "<h3>Recent Searches</h3>"; } else if (item == "favourites") { title = ""; } let parsed_data = JSON.parse(localStorage.getItem(item)); if (parsed_data) { // create string to hold unordered list html let parsed_list = gettext(title) +"<ul>"; I want to translate Recent Searches to Chinese. when I run django-admin.py makemessages -d djangojs -l zh_Hans in terminal, the djangojs.po file doesnot change. other field works well for gettext ,like: favourites ? $("#favourites_list").html(favourites) : $("#favourites_list").html(gettext("You have no favourites saved!")); and the djangojs.po file like: #: .\favourites.js:71 msgid "You have no favourites saved!" msgstr "你还没有收藏哦!" How could I translate a variable 'title' in Django? -
Django CreateView Issue
I am using Django Generic View - CreateView to add new post without the use of admin, so that the random user can post a blog on to the site. But when I submit the form it simply refreshes the form and do not redirect me to blog-detail page. How to fix this. Here's my model.py from django.contrib.auth.models import User from django.urls import reverse from ckeditor.fields import RichTextField class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to="post_images", null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Here's my views.py from django.shortcuts import render from django.views.generic import CreateView from .models import Post class PostCreateView(CreateView): model = Post fields = ['title', 'image', 'content'] Here's my urls.py from django.urls import path from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView ) from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/create/', PostCreateView.as_view(), name= 'post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('search/', views.search, name='search'), ] Here's my post_form.html {% extends "blog/base.html" %} {% block content %} <div class="container"> <form method="POST"> {% csrf_token %}' {{ form.media }} {{ form.as_p }} <button type="submit">Post</button> … -
Why am I receiving a PartialCredentialsError here
I've been trying to deploy my django app using heroku. I'm handling uploaded files using aws s3. When I run the site I keep getting the following error. I have added the aws_access_key_id etc. in environment variables. I don't understand why I am still getting this error message. PartialCredentialsError at / Partial credentials found in explicit, missing: aws_access_key_id I have read that env variables take precedence over the AWS cli config. I don’t really understand the connection though If anyone has ideas, I would be very grateful :) I’m a total newb and appreciate any advice. Also will gladly add any information needed to solve this issue -
Want to return response from middleware after every view call in django rest framework
Hi I have created middleware for checking user authentication User Authentication is been checked on another server, therefore, I have to call every time a request comes on view call class CheckUserMiddleware: """Check User logged-in""" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): """code to be executed every time view is called""" response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): """ checks weather user is valid or not """ token_info = request.headers['Authorization'] # request._result = get_user(token_info, url) result = get_user(token_info, url) if result.status_code == 200: return None else: status_code = status.HTTP_401_UNAUTHORIZED message = "Token is invalid or expired" token_type = "access" detail = "Given token not valid for any token type" result = { 'message' : message, 'token_type': token_type, 'detail' : detail, 'status' : status_code, } result = json.dumps(result) return HttpResponse(content=result, content_type='application/json') def process_template_response(self, request, response): """return template response""" token_info = request.headers['Authorization'] result = get_user(token_info, url) status_code = status.HTTP_200_OK json_response = result.json() email = json_response['email'] user_id = json_response['user_id'] user_type = json_response['user_profile'][0]['user_type'] middle = { 'eamil' : email, 'user_id' : user_id, 'user_type' : user_type, } return HttpResponse(content=middle, content_type='application/json') Now after every call, I need to return user_id in the response I have created middle JSON and am … -
Is it possible to write to a Firestore Real Time Database with Django?
I don't want to use Firestore as my primary data store, rather I want to write information to the Firestore and for that information to be then parsed/used by an iOS app. Example: I create a Django app that allows me to submit forms containing information that is saved to the Firestore DB. I save a copy of this form submission in my Django relational database, and a copy is submitted and saved to my Firestore DB. That data is then picked up by my iOS app which is using Firestore as it's primary data store. Is this something that's easily done? Will I face any problems in attempting to create this? Thanks -
Having trouble in saving forms using Django
Well, I am building a blogging website, where I want users to register themselves and then post their articles. But I am having trouble in saving the article. When I click "Send" button the post doesn't get submitted. I have used django forms.py for the purpose. After investigating I found out that the form is not getting validated. form.is_valid() is returning false. How to get it done? Here is my code: models.py: class Writer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.TextField() username = models.CharField(max_length=15, unique=True) email = models.EmailField(unique=True) profile_pic = models.ImageField(upload_to = 'Bloggers') bio = models.TextField() locality = models.TextField() state = models.TextField() country = models.TextField() instagram = models.URLField(unique=True, null=True) linkedin = models.URLField(unique=True, null=True) facebook = models.URLField(unique=True, null=True) def __str__(self): return self.name + ' , aka, ' + self.username class Post(models.Model): blogChoice = ( ('Sneak Peek', 'Sneak Peek'), ('Events', 'Events'), ('Lifestyle', 'Lifestyle'), ('Trends', 'Trends'), ) blogType = models.CharField(max_length=25, choices=blogChoice,null=True) title = models.CharField(max_length=25) cover = models.ImageField(upload_to='Blog Image') content = models.TextField() author = models.OneToOneField(Writer, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, blank=True) approve = models.BooleanField(default=False) recommend = models.BooleanField(default=False) time = models.IntegerField() def __str__(self): return self.title + ' by ' + self.author forms.py: class PostForm(ModelForm): class Meta: model = Post fields = '__all__' exclude = … -
Creating a bar chart with Plotly on Django
I have managed to integrate a scatter plot into my Django application following the very helpful steps laid out here. I would now like to do the same for a bar chart but I have not been able to get the data to render on the page. Can someone explain where I am going wrong? Here is my views.py: import plotly.offline as opy import plotly.graph_objs as go class Graph(TemplateView): template_name = 'graph.html' trace = go.Figure( data=[ go.Bar( name="Original", x=data[1,2,3,4], y=data[1,2,3,4], offsetgroup=0, ), ], layout=go.Layout( title="Bar Chart", yaxis_title="y axis values" ) ) bar_div = opy.plot(trace, auto_open=False, output_type='div') context['bar_div'] = bar_div return context Thanks! -
How to configure template to route to a different object id from DetailView?
Here is a very simple reference of my django app.. # models.py class Person(models.Model): name = models.CharField(max_length=20) address = models.ManytoManyField(Address) def get_absolute_url(self, **kwargs): ... class Address(models.Model): address = models.CharField(max_length=200) Here is my DetailView of Doctor model: #views.py class PersonDetailView(DetailView): model = Person WITHIN my HTML template of PersonDetailView, how can I access the url and object ID for Address? Currently, if I try something like {% url 'address_detail' object.id %}, the object id is referencing the Person model and not the Address. I am trying to access a url for the address model because I want to the user to be able to access Address's class-based UpdateView FROM the PersonDetailView. -
Cannot assign SimpleLazyObject: django.contrib.auth.models.AnonymousUser : \"Link.posted_by\" must be a "User" instance
asking for help . I'm a beginner in GraphQl and Django, I have an error than I can't find the solution. the error : Cannot assign \"<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x11115cd90>>\": \"Link.posted_by\" must be a \"User\" instance." My code : link/models.py from django.db import models from django.conf import settings class Link(models.Model): url = models.URLField() description = models.TextField(blank=True) posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True,on_delete=models.CASCADE) link/schema.py import graphene from graphene_django.types import DjangoObjectType from users.schema import UserType from .models import Link class LinkType(DjangoObjectType): class Meta: model = Link class Query(graphene.ObjectType): links = graphene.List(LinkType) def resolve_links(self, info, **kwargs): return Link.objects.all() class CreateLink(graphene.Mutation): id = graphene.Int() url = graphene.String() description = graphene.String() #relation with user posted_by = graphene.Field(UserType) class Arguments: url = graphene.String() description = graphene.String() def mutate(self, info, url, description): user = info.context.user or None link = Link( url= url, description= description, #Where there is error posted_by = user, ) link.save() return CreateLink( id=link.id, url=link.url, description=link.description, posted_by = link.posted_by, ) class Mutation(graphene.ObjectType): create_link = CreateLink.Field() The package I'm using for GraphQL is graphene-django THANKS TO HELPING ME -
macOS terminal doesn't create files in right directory
I wanted to use virtual Django environment with pipenv. I created a file named djangotest in my desktop. I accessed it in terminal using cd ~/Desktop/djangotest then I ran pipenv install django and it says it installed successfully. I opened the djangotest folder and didn't see pipfile and pipfile.lock . Then I saw that pipfile and pipfile.lock was created on my Desktop instead of the directory I wanted them to install on. So is there a problem here or is it the thing that was supposed to happen? -
Django order_by on custom model method
I have the following model: class Transactions(models.Model): transaction_amount = models.DecimalField(max_digits=65, decimal_places=0, default=0) decimals = models.PositiveSmallIntegerField("Decimals", null=True, blank=True) def amount_convert(self): try: converted = transaction_amount / pow(10, decimals) except Exception: return None Because transaction may contain different currency, each currency has different decimal value I tried to use the query Transactions.objects.filter(...).order_by('-transaction_amount') but realized i have special case with different currencies For example: IN DB: id=1, transaction_amount = 200000, decimals = 4 => amount_convert() = 20 id=2, transaction_amount = 10000000, decimals = 6 => amount_convert() = 10 is id=1 should be on top of id=2 but the transaction_amount i'm querying is wrong So the amount_convert() model method is what i'm looking for when using order_by(), but seems like order_by doesn't support custom model method. Is there a way i can use custom model method for sorting in query? -
my tasks always gets rescheduled in django_background tasks
I am sending mails to the user as soon as he visits my website.my code looks something like this @background(schedule=10) def sender1(userid): print(userid) email = EmailMessage('Subject', 'email body', EMAIL_HOST_USER, [userid]) #email.attach('name.csv', csv_data, 'text/csv') email.send() def sender(request): userid = request.user.email sender1(userid) return HttpResponse('sender triggered') i am using EmailMessage which worked fine normally.But I wanted to run it as a background task .I introduced a print statement to debug so When i run : python manage.py process_tasks it prints the userid and then says tasks rescheduling.(i read about the issues like database locking in sqlite so using postgres) -
Django: ModuleNotFoundError: no module named 'Parser'
In my project, I have an app called pages: apps/pages/experiments Within experiments, the relevant files are: models.py a folder called parser (which includes an empty file init.py (with 4 underscores) The folder called parser has python code that I would like to import in models, and use there. I have a line of code: from parser import Tables However, when I run the command python manage.py runserver I get the following error: from parser import Tables ModuleNotFoundError: No module named 'XML_parser' -
AttributeError: using for loops with InheritanceManager queryset
In my view, I use InheritanceManager to directly retrieve the children of my Element class: registre = {} elements_enfants = Element.objects.all().select_subclasses() for enfant in elements_enfants: registre[enfant] = enfant.to_registre() Then I loop with this queryset with a method that is in my model Element, which returns me a dictionary: class Element(models.Model): genre = models.CharField(unique=True, max_length=200, null=True, blank=True) nom = models.CharField(unique=True, max_length=100) aventure = models.ManyToManyField(Aventure, blank=True) accessible = models.BooleanField(default=True, help_text='Ce champs définit si l\'on peut accéder par défaut à l\'élément ou non.') description = models.TextField('Description de l\'élément en quelques mots', blank=True, null=True, max_length=250, help_text='250 caractères maximum.') objects = InheritanceManager() def __str__(self): return self.genre class Meta: verbose_name_plural = "éléments" def to_registre(self): if isinstance(self, Heros): dic = self.__dict__ a_enlever = ('_state', 'id', 'genre', 'nom', 'description', 'element_ptr_id', 'user_id' ) for k in a_enlever: dic.pop(k, None) print(dic) else: dic = [self.accessible] return dic I then get this dictionary and want to add it to the "registry" dictionary, but I get the following error: 'NoneType' object has no attribute 'attname' aventure <Aventure: La conquête du dragon> aventure_id 4 chapitre <Chapitre: Chapitre : Préparatifs avant de partir> chapitre_id 4 elements_enfants Error in formatting: AttributeError: 'NoneType' object has no attribute 'attname' enfant Error in formatting: AttributeError: 'NoneType' object has … -
render iframe html code from model to django template
I have a django project for showing details of Movie theaters in various location where i want to show the location iframe in template, And I want to save the complete html code for iframe in my model and render it into the template respectively for different theaters. I have created a model where i take the details of theater. models.py class theater(models.Model): name = models.CharField(max_length=200) owner_name = models.CharField(max_length=200) mobile = models.CharField(validators=[phone_regex],max_length=15,unique=True) landline = models.CharField(max_length=15,null=True,blank=True,validators=[phone_regex]) email = models.EmailField(max_length=254, help_text="enter E-Mail address",null=True,blank=True) website = models.URLField(max_length=300, help_text="enter website link",null=True,blank=True) iframe_detail=models.TextField(max_length=5000) In the details page of my theater i am able to render all the details but not the location from iframe, below is my template.html theater_detail.html <h1>Name: {{theater.name}}</h1><br> <h1>Name: {{theater.mobile }}</h1><br> <h1>Name: {{theater.email }}</h1><br> <h1>Name: {{theater.website }}</h1><br> <div class="w-100"> {{theater.iframe_detail|safe}} </div> The iframe data what i am loading in my model is below. eg <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3806.9740157153647!2d78.46347561744385!3d17.413034599999996!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3bcb975afb4afadd%3A0xf89ea8407df6c84!2sPrasads%20Multiplex!5e0!3m2!1sen!2sin!4v1595574993123!5m2!1sen!2sin" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe> -
How to store just single or just two Records/objects instead of multiple in Django Model?
I just want to store a single or may be just two objects in model but not more. And no one can add more objects in that model.How can I do that is there any option in django to use it? Basically I just want to specify the range of objects store in models. Thank You.