Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use csrf token in Django integrated with vuejs using Django webpack loader?
I am using Vuejs as frontend and Django rest framework as backend, I have some confusions how to use csrf token, my question has 2 part, first I write my configurations. first as Django documentation stated, "If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie()", so this is my view that renders the page which loads webpack bundles. @ensure_csrf_cookie def main_view(request): return render(request, 'index.html') and again as Django documentation I used below configuration to send csrf token along with Axios request. function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); //axios request async createFromCSV(token, data) { const options = … -
Can't override django oscar's styles.css
I'm trying to override oscar's styles.css file in order to change the color of navbar but it doesn't work. I'm using oscar version 1.6 python 3.6.0 and django 2.0. I forked oscar's statics with python manage.py oscar_fork_statics enter image description here enter image description here When I save the color changes for .navbar-inverse and run the server, nothing changes. Can you help? -
django.db.utils.ProgrammingError: relation "masters_user" already exists
I was trying to solve something min my db and mistakenly deleted the django_migrations table. Now when I run the migrate command it says: django.db.utils.ProgrammingError: relation "masters_user" already exists How can I solve this without dropping the entire Database? -
Django raw query gives none value
I have a questionnaire. I like to get the value of a row with raw query but when I loop through in my HTML file it gives me just the first value but the rest 11 gives me none so my addition oft the values also gives me none. I can't understand what am I doing wrong. I made this operation many before on the same way and worked great. I have 12 questions that I made with html input (not Django forms) for certain reasons, but it works well and it posts the values to the database where I have all the positive and negative values. models.py class Vezetoi(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) vezetoi_v01 = models.IntegerField( null=True) vezetoi_v02 = models.IntegerField( null=True) vezetoi_v03 = models.IntegerField( null=True) vezetoi_v04 = models.IntegerField( null=True) vezetoi_v05 = models.IntegerField( null=True) vezetoi_v06 = models.IntegerField( null=True) vezetoi_v07 = models.IntegerField( null=True) vezetoi_v08 = models.IntegerField( null=True) vezetoi_v09 = models.IntegerField( null=True) vezetoi_v10 = models.IntegerField( null=True) vezetoi_v11 = models.IntegerField( null=True) vezetoi_v12 = models.IntegerField( null=True) forms.py class VezetoiForm(forms.ModelForm): class Meta: model = Vezetoi fields = ['vezetoi_v01', 'vezetoi_v02', 'vezetoi_v03', 'vezetoi_v04', 'vezetoi_v05', 'vezetoi_v06', 'vezetoi_v07', 'vezetoi_v08', 'vezetoi_v09', 'vezetoi_v10', 'vezetoi_v11', 'vezetoi_v12' ] views.py - I didn't copied some parts here that are … -
tags for google search in djnago
How can i make tags for google search to my domain name for example this is the domain name: www.BuildSoftApp.ir when some one search like, build soft or make app and etc google find this domain name, in word press when we making a page there is an option for add tags for search engines, i don't know how can i do this in django or it is possible or not, if there is a way to do this please tell me. -
Getting a RelatedObjectDoesNotExist error in Django, would like to make new Object if one does not exist
If I get this RelatedObjectDoesNotExist error, and I want to work around it, I would like to make some "if" statement that produces those related objects in the database so they can exist if they didn't before. In my model: user = models.OneToOneField( User, null=True, on_delete=models.CASCADE) var_1 = models.PositiveIntegerField(validators=[MaxValueValidator( 2000), MinValueValidator(50)], null=True, blank=False) var_2 = models.PositiveIntegerField(validators=[MaxValueValidator( 2000), MinValueValidator(50)], null=True, blank=False) var_3 = models.PositiveIntegerField(null=True, blank=False) var_4 = models.CharField(max_length=254, null=True, blank=True) var_5 = models.CharField(max_length=254, null=True, blank=True) So, the user does exist, but the var_1 - 5 do not. But, they will need those eventually (especially to view the page I am accessing). Therefore, if they access that page, I just want to create those variables in their database attached to their username. I hope this is enough information for this. I am very new to Django and I am finding all the different models/views etc a little confusing. -
In a django project, what all files am I supposed to add in .gitignore?
I am making a Django website project. I decided to push it to my git repo but I am not sure what files I should add in .gitignore I guess all the settings.py files are certainly not supposed to be committed to git. What other files should I ignore? -
Django + React how many requests are too many?
I am creating an app with react frontend and django rest framework backend. It will basically be a fancy form with which the user can create an "order" of many products. The backend has a database of around 10000 products which have the following formating: { "id": 1, "code": "1400", "height": 60, "width": 50 } Many of the products share the same code. There are roughly 20 unique code values equally divided among the whole. So roughly 500 products with each code. The frontend part of the app has a series of dependent dropdown lists that the user can use to specify a combination of code, height and width. The requirement is of course that the desired combination must be a valid one, meaning, it must represent an item that exists in the database. So if for example the user choses the code 1400 from the first dropdown list, the possible "select" values from the second dropdown list must be height values that correspond to items with the code 1400. The frontend uses axios get requests to fetch the data from the backend and then does the required calculations. The problem is, regarding design. How should I balance the amount … -
Why can't i see /Users/Evalyn/folder13/trydjango/src
Evalyns-iMac:trydjango Evalyn$ pwd /Users/Evalyn/folder13/trydjango Evalyns-iMac:trydjango Evalyn$ ls bin lib pyvenv.cfg src Evalyns-iMac:trydjango Evalyn$ pwd /Users/Evalyn/folder13/trydjango -
Get the following error while submitting a form: RelatedObjectDoesNotExist at /agents/create/ User has no userprofile
I'm working on a project and get the following error: RelatedObjectDoesNotExist at /agents/create/ User has no userprofile.I created a form for the user to submit an Agent but when I create an Agent using the form it gives me the above mentioned error but when I try to submit an already created agent it says User with that name already exists. Here is my code: views.py from django.shortcuts import reverse from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from leads.models import Agent from .forms import CreateAgentForm class AgentListView(LoginRequiredMixin, generic.ListView): template_name = 'agents/agent_list.html' def get_queryset(self): return Agent.objects.all() class CreateAgentView(LoginRequiredMixin, generic.CreateView): template_name = 'agents/agent_create.html' form_class = CreateAgentForm def get_success_url(self): return reverse('agent-list') def form_valid(self, form): agent = form.save(commit=False) agent.userprofile = self.request.user.userprofile agent.save() return super(CreateAgentView, self).form_valid(form) models.py from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Lead(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) age = models.IntegerField(default=0) agent = models.ForeignKey('Agent', on_delete=models.CASCADE) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.user.first_name def post_user_profile(instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(post_user_profile, sender=User) urls.py from django.urls import path from .views import AgentListView, … -
Upload multiple images at same time
I have build a Story app, So users can post their stories ( like :- instagram stories ). BUT i am stuck on a Problem. What i am trying to do :- I am trying to build a feature so that Users can upload multiple images at the same time. models.py class ImgModel(models.Model): img = models.FileField(upload_to='status_images',null=True) def __str__(self): return f'[USER] {self.img} [img]' class Story(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) img = models.FileField(upload_to='status_images',null=True) def __str__(self): return f'[USER] {self.user}' views.py def new_image(request,pk): form = NewImageForm(request.POST,request.FILES) requested = request.user if request.method == 'POST': form = NewImageForm(request.POST,request.FILES) if form.is_valid(): new_video = form.save() new_video.user = request.user new_video.save() return redirect('stories') else: form = NewImageForm() context = {'image':image,'form':form,'requested':requested} return render(request, 'new_images.html', context) What have i tried :- I tried many answers like THIS and THIS but nothing worked for me. I also tried ManyToManyField but when i add images separately then it also asks for ManyToMany Field model to save data. I want to add images at same time and upload as stories. Any help would be Appreciated. Thank You in Advance. -
Django - inline formset data not saving with create view
I'm trying to save the ProjectPriority with the Project using the CreateView but can't get it to save. Theoretically it should save the ProjectPriority with the Project when creating a new Project. Models.py: class Project(models.Model): name = models.CharField(verbose_name="Name", max_length=100) details = models.TextField(verbose_name="Description", blank=False) priority = models.ManyToManyField( Priority, through='ProjectPriority', related_name='priority' ) creator = models.ForeignKey(User, on_delete=models.CASCADE) class ProjectPriority(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) priority = models.ForeignKey(Priority, on_delete=models.CASCADE) score = models.CharField(max_length=1000, choices=priority_choices) class Meta: verbose_name = "Priority" verbose_name_plural = "Priorities" Views.py: class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm success_url = '/' def get_context_data(self, **kwargs): ChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('priority', 'score'), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = ChildFormset(self.request.POST) else: data['priorities'] = ChildFormset() return data def form_valid(self, form): form.instance.creator = self.request.user context = self.get_context_data() priorities = context["priorities"] self.object = form.save() if priorities.is_valid(): priorities.instance = self.object priorities.save() return super().form_valid(form) -
How to iterate through classes of file in python?
I have a file called models with few classes and I need to iterate throw them in order to get each class to preform the same task on it. my problem: from django.contrib import admin from . import models # this is very repetetive admin.site.register(models.Myclass) admin.site.register(models.MySecondclass) admin.site.register(models.MyThirdclass) #. #. #... my goal: from django.contrib import admin from . import models for class in models: admin.site.register(class) -
I created a django project. I make models and class and I have some html file also. I want to show 10 post in any categories. I cant write loop here [closed]
please send me easy way to run loop and show my post in categories. when I create post in admin panel my recent post will be show here. -
how to stop create view if already created django
please help me in making this application in django project Here is models.py file code from django.db import models from bio.models import Profile class Question(models.Model): name = models.TextField(max_length=500) def __str__(self): return self.name class Answer(models.Model): question = models.ForeignKey(Question, related_name='question', on_delete=models.CASCADE) profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE) text = models.TextField(max_length=400) created_on = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return "{0} on {1}".format(self.question, self.profile) here is views.py file code class DetailViewMixin(object): details_model = None context_detail_object_name = None def get_context_data(self, **kwargs): context = super(DetailViewMixin, self).get_context_data(**kwargs) context[self.context_detail_object_name] = self.get_detail_object() return context def get_detail_object(self): return self.details_model._default_manager.get(pk=self.kwargs['pk']) class AnswerCreate(DetailViewMixin, CreateView): details_model = Question context_detail_object_name = 'question' model = Answer form_class = NewAnswerForm template_name = "qna/answer.html" success_url = reverse_lazy('qna:list') def form_valid(self, form): form.instance.profile_id = self.kwargs.get('pk') form.instance.question_id = self.kwargs.get('pk') return super().form_valid(form) here is my forms.py code from django import forms from .models import Answer class NewAnswerForm(forms.ModelForm): class Meta: model = Answer fields = ['text',] def clean(self): try: Answer.objects.get(text=self.cleaned_data['text'].lower()) raise forms.ValidationError('Answer exists!') except Answer.DoesNotExist: pass return self.cleaned_data where am I going wrong???? I want that if user answers one question then he couldn't answer it again how can i do form validation if object is already created -
How to repeatedly show additional forms / fields
We are new to Django / Python. We are trying to make a form which allows users to add their itineraries before submission. For example, whenever we press a "+" button, it will show an extra POIFormset models.py class PointOfInterest(models.Model): TYPES = ( ('Food','Food'), ('Sports', 'Sports'), ('Events', 'Events'), ('Accommodation','Accommodation'), ('Sight Seeing', 'Sight Seeing'), ('Shopping', 'Shopping'), ) name = models.CharField(max_length=100, null=True) #structued with google authentication poitype = models.CharField(max_length=100, null=True, choices=TYPES) timespent = models.PositiveIntegerField(null=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() # can use auto_now_add=True for current timep posted date_posted = models.DateTimeField(default=timezone.now) # if user is deleted, the post deleted as well, one-way street, not other way around author = models.ForeignKey(User, on_delete=models.CASCADE) travel_date_start = models.DateField(default=timezone.now, null=True) travel_date_end = models.DateField(default=timezone.now, null=True) poi = models.ManyToManyField(PointOfInterest) # poi = models.ForeignKey(POI, null=True, on_delete = models.SET_NULL) views.py def intinary(request): #formset PostForm = modelformset_factory(Post, fields = ('title', 'travel_date_start','travel_date_end','content', 'author')) POIFormset = modelformset_factory(PointOfInterest, fields =('name','poitype','timespent')) #base code if request.method == 'POST': post_form = PostForm(request.POST) poi_form = POIFormset(request.POST) if post_form.is_valid() and poi_form.is_valid(): post_form.save() poi_form.save() return redirect('blog-home') else: post_form = PostForm(queryset=PointOfInterest.objects.none()) poi_form = POIFormset(queryset=PointOfInterest.objects.none()) #base code context = { 'post_form': post_form, 'poi_form': poi_form, } return render(request, 'blog/frontend.html', context) Thanks guys -
checkboxes added dynamically with django
I am using formsets so add button adds the form but I want to remove them after the delete checkbox has been checked (where i need help), I dont understand much javascript. Here might be the answer but it does not work for me: Can't understand why this error(Uncaught TypeError: $(...).is(...).each is not a function) got on? when I try this code: $("input[class='remove-form']").click(function(){ var n = $( "input[type='checkbox']:checked" ).length; console.log('n here',n) $("input[type='checkbox']:checked").each(function(){ // $(this).parents('.form-row').remove(); console.log('removed'); }) }) only the first checkbox works(which wasn't added dynamically)(or in log case shows the number of boxes checked). The dynamically created checkboxes don't just show any response. The Form which will be appended: <div id="items-form-container" style="display: none;"> .... <div class="col-2"> <label>Delete</label> </div> <div class="col-4"> <div class="input-group"> <input type="checkbox" name="quizz_question-__prefix__-DELETE" class="remove-form" id="id_quizz_question-__prefix__-DELETE"> </div> </div> In short the dynamically added checkboxes doesn't work in my ajax function.Please HElp. -
how to change the user in model after completing wallet the process
new to Django, here is my model.py class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=25, null=True) phone = models.CharField(max_length=12, null=True) class Coin_info(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) coinid = models.CharField(max_length=255, null=True) digit = models.CharField(max_length=18, null=True) ctp = models.FloatField(max_length=100, null=True) transection_id = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=250, null=True, blank=True) date_created = models.DateField(auto_now_add=True, null=True) class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) In view.py, when the customer is logged in, I want to change the user(owner) of Coin_info to the ownership of the sender(customer) and change the value of ctp configured. def buy_c(request, ok): ctp_val = Coin_info.objects.get(id=ok) msg = "Enter Details" if request.method == "POST": try: username = request.POST["username"] amount = request.POST["amount"] senderUser = User.objects.get(username=request.user.username) receiverrUser = User.objects.get(username=username) sender = Balance.objects.get(user=senderUser) receiverr = Balance.objects.get(user=receiverrUser) sender.balance = sender.balance - float(amount) receiverr.balance = receiverr.balance + float(amount) a = Coin_info.objects.change(user=senderUser) ##this is my silly try! if senderUser == receiverrUser: return Exception.with_traceback() else: a.save() sender.save() receiverr.save() msg = "Transaction Success" return redirect("/user") except Exception as e: print(e) msg = "Transaction Failure, Please check and try again" context = {"coin": ctp_val} return render(request, 'coinwall.html', context) Also, I want to know if I can trace the details of total user changed in a particular coinid. … -
Add to serializer data before returning
I have an endpoint which looks like this @api_view(['GET']) def products_view(request): some_data = 123 products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) I want to add the some_data variable to the JSON this endpoint returns. How could I do that? -
Django not updating static css file design in browser when I run collect static command
I wrote css file and then save it all changes happen and when I run collect static command and then I again change css files no changes displayed on browser nothing happen at all. -
Django is deleting my image when i am saving the object app in admin pannel
This is the code that i have used to delete image when i will change the image : def auto_delete_file_on_change(sender, instance, **kwargs): if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).file except sender.DoesNotExist: return False new_file = instance.file if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path)` -
Django invalid password format for Modeform PasswordInput
I have seen a lot of SO answers and official docs for this issue but find no solution yet. forms.py from django import forms from .models import * from django.contrib.auth.models import User class Userform(forms.ModelForm): username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'joeschmoe', 'name': 'username'})) email = forms.CharField(widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'joeschmoe@xyz.com', 'name': 'email'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'name': 'password'})) repassword = forms.CharField(widget=forms.PasswordInput( attrs={'name': 'repassword'})) class Meta: model = User fields = ['username', 'email', 'password', 'repassword'] View.py def register(request): if request.method == 'POST': form = Userform(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] repassword = form.cleaned_data['repassword'] form.save() return render(request, 'base/index.html') else: form = Userform() return render(request, 'base/register.html', {'form': form}) This form is successfully registering but showing Invalid password format or unknown hashing algorithm. Any help will be appreciated -
How to edit the design of admin user permission template in django?
I simply want to take out group editing section from the user permission from the screen. how can i eliminate this part?enter image description here -
Unable to post data using axios to django url
First of all, I am fetching the data from an API and rendering the products. After that, if a user clicks the Add to cart button, I want to post the id of that product to a Django URL, but it's giving me an error saying FORBIDDEN. Here is the image of the error Here is the code import React, { useEffect, useState } from "react"; import "./CSS/Home.css"; import axios from "axios"; function Home() { const [ApiData, setApiData] = useState([]); useEffect(() => { async function getData() { const data = await axios.get("http://127.0.0.1:8000/?format=json"); console.log(data.data); setApiData(data.data.Product); return data; } getData(); }, []); function buttonClicked(id) { axios.post("http://127.0.0.1:8000/update_item/", { id: `${id}` } return ( <> <div className="container"> {ApiData.map((obj, index) => { let x; for (x in obj) { return ( <div className="card"> <div className="top-half"> <img className="store-img" src={obj.image} alt="shoes-images" /> </div> <div className="store-info"> <span className="txt-style">{obj.name}</span> <span className="txt-style">${obj.price}</span> </div> <div className="buttons"> <button className="btn-style" style={{}}> View </button> <button className="btn-style" onClick={() => buttonClicked(obj.id)} > Add to Cart </button> </div> </div> ); } })} </div> </> ); } export default Home; -
How to allow users to submit a get request to a class View and order item?
<form action=""> Sort By: <select name="ordering"> <option value="price">Price:Highest to Lowest</option> <option value="-price">Price:Lowest to Highest</option> </select> <button type="submit">submit</button> <form> trying to submit these values in a get request. Tried doing a get_ordering function on a class List View: class GarageListView(ListView): model = Vehicles template_name = 'garage/garage.html' context_object_name = 'cars' ordering = ['-price'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = VehicleFilter( self.request.GET, queryset=self.get_queryset()) return context def get_ordering(self): self.ordering = self.request.GET.get('ordering','-price') return self.ordering When users select and submit any sort option, it should refresh the page and sort by value