Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to post manytomany field by value not by id in django rest framework
I have a tow classes , the relationship between them many to many field , i wont to post data in this way {"first_name":"mohammad", "last_name":"alqudah", "motivate":[ "Stay Fit","Look Younger" ] } instead of this way {"first_name":"mohammad", "last_name":"alqudah", "motivate":[ 1,2 ] } my Serializers class MotivateSerializers(serializers.ModelSerializer): class Meta: model = Motivate fields = ['name'] class UserSerializers(serializers.ModelSerializer): class Meta: model = User fields = ['lat','long','first_name','last_name','mobile_number','email','date_of_birth', 'gender','height','weight','relationship','number_of_household','number_of_pets','kind_of_pets','motivate'] my views.py @api_view(['POST', ]) @permission_classes([IsAuthenticated]) def userdata(request): user = request.user serializer = UserSerializers(instance=user, data=request.data,many=False) if serializer.is_valid(): serializer.save() return Response("Data has been updated successfully") else: # print (serializer.errors) return Response(serializer.errors) -
how to show liste filtre admin django ManyToOne
how to show liste filtre admin django ManyToOne in this case : in models.py ----------- class Personne(models.Model): name= models.CharField(max_length=50,blank=False) def __str__(self): return self.name class Project(models.Model): title= models.CharField(max_length=50,blank=False) note= models.CharField(max_length=50,blank=False) def __str__(self): return self.title class Task(models.Model): title= models.CharField(max_length=50,blank=False) projecttasktask= models.ForeignKey(Project, on_delete=models.CASCADE) personnetask= models.ForeignKey(Personne, on_delete=models.CASCADE) def __str__(self): return self.title in admin.py --------------- ProjectAdmin(admin.ModelAdmin): list_filter = () How can i filtre in Project by tasks and specialy by Personne liste dropdown of personne and show me liste of projects ? best ragards -
Adding POST request via Vue component and Fetch API to add object to Django backend
SPA: VueJS Backend: Django default Although I am focusing on POST for the moment, this is what I am working on: seeing a list of all elements in model (my list fetched via a GET request as soon as the page loads) add a new element to a list via Vue (POST) update the details of single elements (PUT) delete an element (DELETE) requests from my client to my server being done via Ajax requests using the fetch API. So after the first page loads, I do not want further page refreshes. I am looking to add a simple form which upon submission will make a post request and add an object or new recipe to my backend database. I currently have a GET request method that uses fetch. I would like to know how form data could be passed into a data list, but more importantly, result in an object being created (perhaps parsing as a JSON file). App.vue <template> <div> <button @click="fetchRecipes">Fetch Recipes</button> <div> <ul> <li v-for="recipe in recipes"> {{ recipe.name }} <span v-if="!recipe.popular">(Not very popular!)</span> </li> </ul> </div> </div> <form> where I would like my form </form> </template> <script> export default { data() { return { recipes: … -
ImportError: cannot import name 'portfolioapp' from 'portfolio'
How do i fix that error, is it a case or circular ImportIMPORT ERROR -
Lightning LND Rest API in Django API Handling POST requests when encoding/decoding
I am trying to make a Django API for handling lightning payments, and I need to implement some functionalities such as unlocking wallet, changing password etc. I am getting "Incorrect padding" and I don't know how to fix it.This is my view.py: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.parsers import JSONParser import os import base64, codecs, json, requests class ChangePassword(APIView): def post(self, request): url = "https://localhost:8080/v1/changepassword" cert_path = "/Users/user1/Library/Application Support/Lnd/tls.cert" data = { "current_password": base64.b64decode( request.data["current_password"] ).decode("utf-8"), "new_password": base64.b64decode(request.data["new_password"]).decode( "utf-8" ), } r = requests.post(url, verify=cert_path, data=json.dumps(data)) if r.status_code == 200: data = r.json() return Response(data, status=status.HTTP_200_OK) return Response({"error": "Request failed"}, status=r.status_code) I am using the LND Rest documentation https://api.lightning.community/#v1-changepassword. Thanks in advance for your help :) -
Django: IntegrityError at /accounts/accounts/myprofile UNIQUE constraint failed: accounts_userprofile.user_id
When I am trying to update my userprofile i get this error, IntegrityError at /accounts/accounts/myprofile UNIQUE constraint failed: accounts_userprofile.user_id I have searched for solutions, but it does not work for me. model: class UserProfile(models.Model): is_deligate = models.BooleanField(default=True) is_candidate = models.BooleanField(default=False) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=200) stud_id = models.IntegerField(primary_key = True) course_year_and_section = models.CharField(max_length=200) def __str__(self): return self.name Form: class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = ['name','stud_id','course_year_and_section'] view: def UserProf(request): user = request.user ls2 = UserProfile.objects.get(user_id=user.id) form = UserProfileForm() if request.method == 'POST': form = UserProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() context = {'form':form,'ls2':ls2} return render(request,"accounts/myprofile.html", context) def UpdateUserProf(request): form = UserProfileForm() try: prof = request.user except UserProfile.DoesNotExist: prof = UserProfile(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST,instance=prof) if form.is_valid(): form.save() return redirect("myprofile.html") else: form = UserProfileForm(instance=prof) context = {'form':form} return render(request,"accounts/myprofile.html", context) -
Add a contact form to an existing contact page view using class based views in Django
I'm trying to add a "contact us" form to my existing "contact us" page using a model form and class based views. First I've created the model below: class ContactUsForm(models.Model): first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False) email = models.EmailField(blank=False, null=False) subject = models.CharField(max_length=250, blank=False, null=False) message_body = models.TextField() def __str__(self): return self.subject Then I've created my form in forms.py as below: class ContactForm(ModelForm): class Meta: model = ContactUsForm fields = "__all__" My previously existing contact page view is as below: class ContactUsPageView(ListView): """ In this view we are fetching site data from database, in a function named get_context_data. In this function, we filter the model for objects that contains the word 'تماس', therefore fetching data referring to the about page only. After that the context list is sent to the template, and there with a for loop and an if statement, each key, value set is chosen for the proper place. """ model = SiteDataKeyValue template_name: str = "core/contact-us.html" def get_context_data(self, **kwargs): context = super(ContactUsPageView, self).get_context_data(**kwargs) context["contact_page_data"] = self.model.objects.filter(key__icontains="تماس") return context Now, I have no idea how to proceed. How am I supposed to add this form to my view, then send it along with the … -
Django - How to dynamically load generated SVG
I am trying to load an SVG graphic during runtime to my Django webpage. The graphic will be generated on request and depends on different user inputs. If I use templates like this: {% extends "app/base.html" %} {% block content %} <h1>Internal Requirements Tree</h1> <div> {{ svg }} </div> {% endblock content %} with the corresponding view: def internal_reqs(request): with open("some/path/to/graph.svg") as f: base_image = f.readlines() # remove XML header while '<svg ' not in base_image[0]: base_image.pop(0) context = { 'title': 'Title', 'svg': '\n'.join(base_image), } return render(request, 'app/graph.html', context) the SVG source will be printed but not rendered. But if I put the same string from the svg directly into the template like this: {% extends "app/base.html" %} {% block content %} <h1>Internal Requirements Tree</h1> <div> {{ svg }} </div> <div class="center"> <svg width="570pt" height="100pt" viewBox="0.00 0.00 570.00 100.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 96)"> .... </g> </svg> </div> {% endblock content %} it will be rendered just fine. How to do it correctly? -
how can i define default value for urlls parameters in django?
views.py from django.views.generic import ListView from .models import Staff class StaffListView(ListView): model = Staff template_name = 'staff/staff_list.html' def get_queryset(self): return Staff.objects.filter(websites__path=self.kwargs['web']) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('<str:web>/staff/', include('staff.urls')), # I want to set web=chemical, if url is http://127.0.0.1:8000/staff ] -
how to do bug fix without resetting database
I have hosted my Django app in Heroku with Github. So when I do a bug fix and I re-deploy my page. My database resets. I know that my database reset because Heroku is just deploying my GitHub branch and my GitHub database is not updating with my Heroku database. So what can I do to keep my database same and I can also do modifications? and if I need how can I download or store my main Heroku database in somewhere else? note: I'm using Django default database sqlite3 -
show existing file path using javascript and django
when a user update his info the existing data should be displayed in input fields.In my problem resume file name not displaying on the right place. i want to display the file name in No file chosen place with javascript. Any way??? The Code is tooo big so i can't copy the entire code this is update resume input field <div class="form-group"> <label>Resume</label> <span style="color:#ff0000">*</span> <br> <span id="resid"></span> <input type="file" name="resume" id="resume_Id" class="form-control" required> </div> in here passing the database value to update field <a href="#editCorporateTrainers" class="edit" title="Edit" data-toggle="modal" onclick="editCorporateTrainersdetails( name = '{{ i.Name}}', email = '{{ i.Email}}', phone = '{{ i.Phone_Number}}', rate = '{{ i.Rate}}', skills = '{{ i.Skill.all}}', description = '{{ i.Description}}', resume = '{{ i.Resume}}', trainer_Id = '{{i.id}}' );" > <i class="fa fa-edit" style='color:#8773b3' data-toggle="tooltip"></i></a> </td> this is the function currently calling in script tag function editCorporateTrainersdetails(name ,email, phone ,rate ,skills ,description ,resume ,trainer_Id){ document.getElementById('name_Id').value = name; document.getElementById('email_Id').value = email; document.getElementById('phone_Id').value = phone; document.getElementById('rate_Id').value = rate; document.getElementById('skillId').value = skills; document.getElementById('description_Id').value = description; document.getElementById('trainer_Id').value = trainer_Id; document.getElementById('resid').innerHTML = resume; } -
Should I use two Postgres databases for Django on Heroku - dev & prod?
I'm quite new to Django. I'm building a Django app and want to deploy it to Heroku with Postgres database. I already installed a Postgres app on Heroku, and have my credentials. Should I have two databases - one Postgres database with its own settings locally for dev, and one that is on Heroku? The app is quite simple, so I don't necessarily need two databases, but maybe it is needed for deployment. -
Aggregate makes extra queries
In my model, I have a book and review class and I want to calculate the average rating. I use aggregate and Avg for that models.py class Book(models.Model): author = models.ManyToManyField(Author, related_name='books') title = models.CharField(max_length=200) description = models.TextField(max_length=3000) price = models.DecimalField(max_digits=6, decimal_places=2) publisher = models.CharField(max_length=200) language = models.CharField(max_length=200) pages = models.PositiveSmallIntegerField() isbn = models.CharField(max_length=13, validators=[validate_isbn(), MaxLengthValidator(13)]) cover_image = models.ImageField(upload_to='books/images') publish = models.BooleanField(default=True) @property def average_rating(self): avg_rating = Review.objects.filter(book_id=self.id).aggregate(Avg('rating')) return avg_rating['rating__avg'] def __str__(self): return self.title class Review(models.Model): RATING = [ (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), ] book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField() rating = models.PositiveSmallIntegerField(choices=RATING, default=5) date_added = models.DateField(auto_now_add=True) objects = ReviewManager() def __str__(self): return f"{self.user.username} {self.book.title}" Now for each book, I have one extra query How can I fix this issue? -
Heroku Application Error while Deploying Django application
enter image description here Please help me with this error -
How do I set uploaded image back to default image when deleted?
I have a simple blog app, when I update an article and remove photo I want it to use default photo. it selects that image on create but when updating it throws an error. here's my Models.py code. image = models.ImageField( upload_to="uploads/articles/", null=True, blank=True, default="uploads/articles/noimage.png", ) the error I get when I remove image during update. Error during template rendering The 'image' attribute has no file associated with it. <img class='article-img' src="{{article.image.url}}" alt=""> -
How to pass JavaScript array to Django views
Background: I am trying to build a small web application, where I need to show data based on checkboxes checked by the user. I am very new to coding and somehow decided to start with Django. I did the following: I used HTML form for checkbox that does nothing on submit JavaScript for checkbox validation and to collect user input in an array. I want to pass this array variable to Django views.py so I can try to filter the data and then display to the user and I am stuck. I tried Jquery (see result_output function) but I am not able to make it work. Below are the codes. Any help will be highly appreciated. JavaScript: function nextPrev(n) { // This function will figure out which tab to display var x = document.getElementsByClassName("tab"); //exit the function if any checkbox is not checked if(n==1 && !validateFrom(currentTab)) return false; //console.log(all_filter_value[0]) //console.log(all_filter_value[1]) // Hide the current tab: x[currentTab].style.display = "none"; document.getElementsByClassName("step")[currentTab].className += " finish"; // Increase or decrease the current tab by 1: currentTab = currentTab + n; // if you have reached the end of the form... : if (currentTab >= x.length) { //...the form gets submitted: document.getElementById("questbox").style.display="none"; result_output(); return false; … -
Django filter ManyToManyField
There is a Django filter problem with ManyToManyField that bothers me. I have a task that I want the creator and selected members of the creator to view. Now I have a problem that the specified member can be viewed normally, but when the creator views it, there will be the same number of duplicate tasks as the specified member. I can't understand this problem, it is not what I expected. #views class TaskView(LoginRequiredMixin, View): def get(self, request): projecttask_all = ProjectTask.objects.filter(Q(owner=request.user.username) | Q(task_member=request.user)) print(projecttask_all) #print results <QuerySet [<ProjectTask: user1>, <ProjectTask: user1>]> // My understanding should be like <QuerySet [<ProjectTask: user1>]>, because the owner is not in projecttask_task_member,but it is not. #model class ProjectTask(models.Model): title = models.CharField(max_length=100, verbose_name='title', default='') owner = models.CharField(max_length=30, verbose_name='owner') task_member = models.ManyToManyField('UserProfile',related_name='task_member', blank=True, null=True) #mysql projecttask | id | title | owner | | -- | ----- | ----- | | 1 | test | user1 | projecttask_task_member | id | projecttask_id | userprofile_id | | -- | -------------- | -------------- | | 1 | 1 | 8 | | 2 | 1 | 9 | -
How to pass an image path to setAttribute in Django?
test.addEventListener('click',function(e){ console.log("click"); var targetElement = event.target || event.srcElement; clickedVal = targetElement.innerText; targetElement.innerText=""; input = document.createElement("input"); input.value = clickedVal; targetElement.append(input); img = document.createElement("img"); // It's not working here // "{% static 'images/confirm.svg' %}" is incorrect. Then how to correct it? img.setAttribute("src", "{% static 'images/confirm.svg' %}"); input.parentElement.append(img); }) "{% static 'images/confirm.svg' %}" is incorrect. Then how to correct it? Thanks -
I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch
I want to add like unlike feature to my blog site, everythin is okay there, like and unlike objects are being created.. But I'm getting NoReverseMatch when I'm clicking the Like and Unlike..and the problem is I can't figure it out why I'm getting this...my models.py, views.py, urls.py, blog_page.html...all are attatched here.. plz try help me solve this **models.py** from email.policy import default from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200, verbose_name="Put a Title") blog_content = models.TextField(verbose_name="What is on your mind") blog_image = models.ImageField(upload_to="blog_images", default = "/default.png") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_comment" ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_comment") comment = models.TextField() comment_date = models.DateField(auto_now_add=True) def __str__(self): return self.comment class Like(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_liked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_liked") class Unlike(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_unliked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_unliked") **views.py** from django.shortcuts import render from . models import Blog, Comment, Like, Unlike # Create your views here. def home(request): blogs = Blog.objects.all() context = {'blogs': blogs} return render(request, 'blog_app/home.html', … -
How to pass an image path to setAttribute method in the template of Django?
In the template file, I need to pass the image path "{% static 'images/confirm.svg' %}" to setAttribute method. // js test.addEventListener('click',function(e){ var targetElement = event.target || event.srcElement; clickedVal = targetElement.innerText; targetElement.innerText=""; inpt = document.createElement("input"); inpt.value = clickedVal; targetElement.append(inpt); inpt.setAttribute("images", "{% static 'images/confirm.svg' %}") }) But this didtn' work. How should I do? Thanks. -
Uploading File Failed to message the error in the website
I am using Django and would like to upload a file which will then save it to the database. I have an HTML where the user can upload the file. How can you successfully caught errors or message the error in the website like: If it is not csv format If the columns are not found or incorrect columns Date causes validation format - should be YYYY-MM-DD when the choices are unavailable View def simple_upload(request): data = None try: if request.method == 'POST': data = request.FILES['myfile'] if not data.name.endswith('.csv'): messages.warning(request, 'The wrong file type was uploaded') return HttpResponseRedirect(request.path_info) data = pd.read_csv(data, header=0, encoding="UTF-8") for index, rows in data.iterrows(): userid = rows["User ID"] generalid = rows["User ID"] date = rows["Date"] if rows["User ID"] else datetime.date.today() description = rows["Description"] if rows["Description"] else " " address = rows["Address"] if rows["Address"] else " " latitude = rows["Latitude"] if rows["Latitude"] else " " longitude = rows["Longitude"] if rows["Longitude"] else " " status = rows["Status"] if rows["Status"] else " " weather = rows["Weather"] if rows["Weather"] else " " light = rows["Light"] if rows["Light"] else " " accident_factor = rows["Accident Factor"] if rows["Accident Factor"] else " " collision_type = rows["Collision Type"] if rows["Collision Type"] else " " … -
django ModelChoiceField returns invalid form
I'm new to django and this is my first project. I'm having trouble with a form which I use to have the user pick an entry from a database table in order to redirect to another form to edit said entry. The ModelChoiceForm renders well when loading the view and the options from the database show up correctly but when I submit the form I get a UnboundLocalError saying the form is invalid and the form.errors prints <ul class="errorlist"> <li>group <ul class="errorlist"> <li>This field is required.</li> </ul> </li> <li>group_name <ul class="errorlist"> <li>This field is required.</li> </ul> </li> </ul> Here is the relevant part of my models.py: class Groups(models.Model): group = models.IntegerField(primary_key=True) group_name = models.CharField(max_length=80) def __str__(self): return self.group_name forms.py: class GroupForm(forms.ModelForm): class Meta: model = Groups fields = '__all__' labels = {'group':"ID", 'group_name':"name"} class SelectGroupForm(forms.Form): group_id = forms.ModelChoiceField(queryset=Groups.objects.all(), \ to_field_name='group', \ empty_label="Select group") views.py: if request.method=="POST": form = GroupForm(request.POST) if form.is_valid(): selected_group = form.cleaned_data['group'] redir_url = '../groupform/' + str(selected_group) + '/' return redirect(redir_url) else: print(form.errors) else: form = SelectGroupForm(request.POST) return render(request,'regular-form.html', {'form':form}) The error list suggests that the form requires all the fields from the model to be entered but I only want the one specified on the form. -
DJango fill existing formset from View
I understand that you can fill a form from a view with: initial_data = { 'box0': 'X', 'box1': 'O', 'box2': 'X' } form = myform(initial=initial_data) But, how do you do it for a formset? The below causes error "TypeError: formset_factory() got an unexpected keyword argument 'initial'" initial_data = [] for i in range(rowCount): xy = getRandomXY(3) initial_data.append({ 'box0': xy[0], 'box1': xy[1], 'box2': xy[2] }) formSet = formset_factory(myform, extra=rowCount, max_num=10, initial=initial_data) -
Django complicated grouping count
I have the models below: class Company(models.Model): .... cases = models.ManyToMany('Case') is_active = models.BooleanField(default=True) class Case(models.Model): .... is_approved = models.BooleanField(default=False) product = models.ForeignKey('Product') class Product(model.Model): .... I want to get all the products (that are linked with an approved case) grouped by companies' active status. So, the result should be like: [ {'product': 1, 'active_companies': 12, 'inactive_comapnies': 10}, {'product': 3, 'active_companies': 2, 'inactive_comapnies': 33}, {'product': 7, 'active_companies': 5, 'inactive_comapnies': 6} ] I have tried some queries starting with Company and others starting from Product, but I failed. -
Auth0 Authentication Flow (Mismatching State)
I hope whoever's reading this is having a good day! My question is as follows, I've got this specific authentication flow in my mind that is causing an exception when executing it. Given FrontEnd is hosted on domain FE (React Client), backEnd on domain BE (DJango Server) and Auth0 on A0. I need the user to land on FE, gets redirected to login form of A0 by the help of a BE endpoint, gets redirected to FE again which in turn calls BE with the state and auth code returned from A0, authenticates and saves token in the request session. def callback(request): ''' Extracts state and auth code from url, authenticates with auth0, extracts token and saves it within the request session for future calls. ''' token = oauth.auth0.authorize_access_token(request) request.session["user"] = token return {"Authenticated":True} def login(request): ''' Redirect to auth0 login screen with a callback url to frontend that extracts the given state and auth code sent by both BE and Auth0 ''' return oauth.auth0.authorize_redirect( request, "http://FrontEnd.com/authenticate") What happens when doing so is that the backend receives the state and raises a Mismatching state error request and response states do not match (state is null) Why do I want to …