Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Model Draft, Published, Revisions
I have a model that I use for creating project budgets. They approve one budget, but later on as they execute hours the budget might need to be revised and a user has to create a draft budget based on the one approved and make changes and submit to the manager for approval. I'm using Django and I'm not sure what I need to use for this. I've looked at django-reversion-API, django easy-mode and wagtail. But I'm very confused. I don't know what I need. Reversion, CMS, something related to state????? Any help would be appreciated. -
Push rejected, failed to compile Node.js app while deploying in heroku
i am deploying my django+react app on heroku but its raising this error every time Push rejected, failed to compile Node.js app i have tried every thing remove cache delete package-lock.json update the node version according to .env file and other packages , app working fine in local but not deploying on server.i have this error so far at every time please help me to resolve i have also follow the heroku documentation to resolve this issue but not worked for me. -
How to combined C++ code implement in Django?
My project is based on Face Recognition, Hence C++ code implements in my project. -
Make that django simple JWT have the same permissions as Django Admin
I'm developing an api in Django with DjangoRestFramework, and now I started to work with Tokens, (I'm using JWT with the djangorestframework_simplejwt library). What I want is to have the same permissions that I have in my django Admin in the token, for intance, I created a group for an specific app in my Django admin but when I use httpie with an user that wasn't supose to have permissions I can get all the data. Do you know a way to connect that permissions? This is the code that I wrote. from rest_framework.permissions import IsAuthenticated class ArticulosLista(APIView): permission_classes = (IsAuthenticated, ) # All other methods -
How to have one model property be a dropdown between attributes of another model?
Relatively new to Django. I think what I am trying to do is very simple but I've never done this before. "irrelevant2" is an attribute in my class first that I want to refer to a direct element in the class second (this part is working fine). Additionally, I want there to be a field in my class first that is essentially a dropdown menu that chooses between two elements of the class second and can only pick one. I understand that I need a form but so far have not been successful. My hunch says RELEVANT_VARIABLE should be a ForeignKey but I'm not sure how to attach it to a dropdown of either attr1 or attr2 from class second. class second(models.Model): attr1 = models.CharField(max_length=100) attr2 = models.CharField(max_length=100) class first(models.Model): irrelevant1 = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) irrelevant2 = models.ForeignKey(second, on_delete=models.CASCADE) RELEVANT_VARIABLE = models.ManyToManyField(second, related_name="team_selection") And then in forms.py class FirstForm(forms.Form): def __init__(self, *args, **kwargs): super(FirstForm, self).__init__(*args, **kwargs) self.fields[**not sure what to even put here**] = forms.ChoiceField( choices=[(o[**not sure**], str(o[**not sure**])) for o in Second.objects.filter(irrelevant2=self)] ) class Meta: model = second -
Django multiple forms in CreateView
I'm trying to show a view with two forms on it. The RoadCost form which will calculate the road's cost & pass it into the Road model so that when a Road is created it has the RoadCost associated with it. How can I show these two forms on the same CreateView & the pass it into the Road model? In theory, all the RoadCost should do is be next to the create view & allow the user to input the spent & allocated values it will do some calculations & then pass in the spent & allocated to the Road form ready for it to be created. I'm fairly inexperienced with Django, if there is a way to do this please let me know. model.py class RoadCost(models.Model): cost_spent = models.CharField(max_length=100) cost_allocated = models.CharField(max_length=100) class Road(models.Model): name = models.CharField(max_length=100) road_cost = models.OneToOneField( RoadCost, default=False, on_delete=models.CASCADE, primary_key=True, ) views.py class RoadCreateview(CreateView): model = Road fields = ['name', 'distance'] forms.py class RoadCostForm(forms.ModelForm): class Meta: model = RoadCost fields = ['spent', 'allocated'] -
How can I send context to Django in every page without sending from all the views
I am trying to create an eCommerce app and have the cart option in that. However, on every page of the site (or every view), I always type the code... context = { "no_in_cart":no_of_items_in_cart(request) } Where no_of_items_in_cart is a function to find the number of items in the cart. But I feel this is a waste of code and may have several inefficiencies. And also I am not sure on how I can send this code through auth_views, such as login or register views. Any help would be greatly appreciated. Thanks! -
Django Pass a Form's Field to a Model's Field
I am learning Django web framework by going through this example. In one of the view functions: def renew_book_librarian(request, pk): """View function for renewing a specific BookInstance by librarian.""" book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) book_instance.due_back = form.cleaned_data['renewal_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed')) # If this is a GET (or any other method) create the default form else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal_date': proposed_renewal_date}) context = { 'form': form, 'book_instance': book_instance, } return render(request, 'catalog/book_renew_librarian.html', context) It assigns form.cleaned_data['renewal_date'] to book_instance.due_back. However, form.cleaned_data['renewal_date'] is not a models.DateField as defined by the BookInstance class: class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book', on_delete=models.RESTRICT) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) … -
Having trouble rendering an array of images from an api (Django Rest Framework) response in React
Hi this is my first project in both React and Django Rest Framework and I need to figure this out to complete the project. The issue I'm having (I believe it's a React one) is that my api is returning an json response which React receives using axios which works fine since when I do the console log all the data is there and Im also able to pass the data to a tag, etc. I would like to display the photos that are being sent to by the api. The link is not the problem as I am able to view the photo in the browser using the link provided by the api. The problem is that I have multiple images in the api response that are set up as an array. As shown here: postmanResponse Response using console: enter image description here I guess essentially what I'm asking is there a way that I can make an array/object with the image array that my api is delivering so that I can then use it to show the picture in React? Any help will be helpful. Thank you! Here is my code for the React side: // Import Files … -
Django: TypeError: 'ModelSignal' object is not callable
I have a piece of code throwing an error: TypeError: 'ModelSignal' object is not callable. While I'm gonna add signals in my project, this error is occuring. Why this type of error is occured? What you need to know to give my answer? Please help me someone. I'm a newbie to Django. Thanks in advance. Here is my views.py file: def registerPage(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): user =form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account successfully created for ' + name) return redirect ('login') context = {'form': form} return render(request, 'accounts/register.html', context) My models.py file: from django.db import models from django.contrib.auth.models import User class Student(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) My signals.py file: from django.db.models.signals import post_save from django.contrib.auth.models import Group, User from .models import Student def student_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name = 'Student') instance.groups.add(group) Student.objects.create( user = instance, name = instance.username ) post_save(student_profile, sender= User) My apps.py file: from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' def ready(self): import accounts.signals … -
Setting up Django, Nuxt, with Nginx and docker
I am trying to create a docker image for all of the above services. I was able to get django set-up with a database and Nginx, but I am having a lot of trouble adding Nuxt to the mix and cannot get the Nuxt app to run properly and it is giving me constant errors that do not occur if I manually start the node server. I suspect that most of the issues are from auth and/or improper routing in Nginx, likely stemming from incorrectly setting up the appropriate files. Any advise on how to set-up these configuration files would be greatly appreciated! My folder structure is as follows. The dockerfile inside the app directory corresponds to the django app WebsiteProject/ ├── app/ │ ├── frontend-nuxt/ | | ├──Dockerfile | | └──nuxt.config.js │ ├── nginx/ | | ├──Dockerfile | | └──nginx_local.conf | └──Dockerfile └── docker-compose.yml docker-compose.yml version: '3.7' services: web: build: ./app command: gunicorn webapp.wsgi:application --bind 0.0.0.0:1339 --reload entrypoint: ./entrypoint.sh volumes: - ./app/:/usr/src/app/ - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 1339 env_file: - ./.env.dev depends_on: - db # - redis frontend: build: ./app/frontend-nuxt volumes: - ./app/frontend-nuxt/:/user/src/app/ expose: - 3000 ports: - 3000:3000 depends_on: - web command: npm run dev db: image: … -
How To Use django.views.APIView In Python?
I'm currently facing trouble using rest_framework.views.APIView. When I try running python manage.py makemigrations, it says that there is nthroughing such as django.utils.six. The line that it throws an error on is from rest_framework.views import APIView. Can anyone give me guidance on how to fix this issue? -
How to add hide button next to delete button in django admin
How can I add a custom action button(Hide) to the position where Delete button originally at (Blue circle). -
How to stop Django 3.0 leaking db connections?
In my requirements.txt I only change from django==2.2.17 to django==3.0 (or 3.1.4) and the webserver starts leaking postgres db connections. (Every request increases the number of connections when I check the list of clients in pgbouncer.) How can I stop the leakage? Is there any way to limit the number of connections to a server? -
psycopg2-binary failing to install in docker container
Apologies for newbie question. I've tried all of the answers from other questions here but the don't pay off either. Dockerizing my python/django app with Postgres is proving... daunting. I'm getting the error "Error: pg_config executable not found." consistently when it starts working through my requirements.txt Here's the Dockerfile: FROM python:3.8.3-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD ./ /code/ ...and my requirements.txt... asgiref==3.3.1 Django==3.1.4 psycopg2-binary==2.7.4 pytz==2020.5 sqlparse==0.4.1 django-compressor>=2.2 django-libsass>=0.7 When I run docker-compose up --build I'm getting this error over and over: Step 6/7 : RUN pip install -r requirements.txt ---> Running in e0fd67d2d935 Collecting asgiref==3.3.1 Downloading asgiref-3.3.1-py3-none-any.whl (19 kB) Collecting Django==3.1.4 Downloading Django-3.1.4-py3-none-any.whl (7.8 MB) Collecting psycopg2-binary==2.7.4 Downloading psycopg2-binary-2.7.4.tar.gz (426 kB) ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fha1c65p/psycopg2-binary/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fha1c65p/psycopg2-binary/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-ewxlxmh6 cwd: /tmp/pip-install-fha1c65p/psycopg2-binary/ Complete output (23 lines): running egg_info creating /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info writing /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-ewxlxmh6/psycopg2_binary.egg-info/SOURCES.txt' Error: pg_config executable not found. -
Django sys.exectuable not running in production mode
Code beneath takes an image and runs it through a python script. Everything works great locally. On production mode it does not seem to run (Droplet on digital ocean). I have tried to debug this as much as i can but i cant seem to retrieve anything of use... import sys from subprocess import Popen, PIPE, STDOUT, run class ImageViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): parser_classes = (JSONParser, MultiPartParser, FormParser,) queryset = UploadImageTest.objects.all() serializer_class = ImageSerializer def post(self, request, *args, **kwargs): self.create(request, *args, **kwargs) inp = request.FILES.get('image').name out = run([sys.executable,'//Users//macbookpro//mywebapp//myprojectenv//Script.py',inp],shell=False,stdout=PIPE, text= True) if out.returncode == 0: stat = 'Success' else: stat = 'Fail' data = { 'info': out.stdout, 'status': stat, } return JsonResponse(data, status=status.HTTP_200_OK) The only difference on the production server is the path below which could be incorrect. out = run([sys.executable,'//mywebapp//myprojectenv//Script.py',inp],shell=False,stdout=PIPE, text= True) On the production server the code above returns as "Fail" which means that it is being processed. For the Script i don't get any feedback. Either the path is faulty or the script is. however i'm not sure how to check if the Script is attempting to run but failing. Any help would be appreciated. -
Django Suggested Pages by User Tracking
I have a project I'm working on similar to a website like Game Informer to try to learn more of django. So I have a section of the website for a blog, for videos, for reviews, and for news. Each has its own model. I'd like to associate a tagging system with each of these models, probably using a many to many field to a model that just contains tags. The part that I'm struggling with is figuring out how I could use this tagging system to generate a list of suggested articles for users that are logged in. I thought about creating a model with a foreign key to the user and a foreign key to the post, then in the view logic, create an object and save it to the model with the user and page visited. But I'm not quite sure how I would access the tags that this person visited the most. I'm also curious if there's a way that I can add more weight to the certain tags if a user has liked a post with those tags and less weight if they've disliked. Any ideas, suggestions, or guidance would be greatly appreciated. I'll post … -
Saving form data upon social login
I'm using Django Allauth. I have few social login buttons (Google, Twitter, Facebook). I also have a form if the user wants to sign up via email. The form contains a hidden field that contains the App ID (if they are on an Android device). If they sign up via email, I have made a way where I can capture that information through the POST request. However, how do I capture this hidden field's data and pass into a social adaptor so that I can save this App ID. class SocialAccountAdapter(DefaultSocialAccountAdapter): def authentication_error(self, request, provider_id, error=None, exception=None, extra_context=None): messages.error(request, "An error occurred while attempting to login via your social media account.") raise ImmediateHttpResponse(redirect('/login/')) def save_user(self, request, sociallogin, form=None): user = super(SocialAccountAdapter, self).save_user(request, sociallogin, form) print(self.request.GET) //This doesn't work, but this is what I've tried Is there a way I can get this local value passed along when a user does social sign up? -
Django create Datepicker field in HTML Template
I am looking to create a datepicker field along with other existing search fields in my HTML template. I am looking for how to create datepicker and initialize it to show calendar. I have looked at all other forums on web and all give options to add datepicker widget in the form and then call form in your template. I want to directly create datepicker in template along with all my other fields in template. Can you please suggest? -
is there an alternative to the way i am doing it ? any help will be appreciated
[https://pastebin.com/1EB5FuAZ][1] I need help, I am new to Django and I am following a tutorial on building a program but when I enter I data to the form. it doesn't input it into my MySQL database and it seems like it is the code that is in breaking it. After I have enter my data to my form and submit it takes me to the error page but when i remove the error it displays I output it couldn't add the data. -
Django Email Templates Rendering as Text
I am using trying to use the Django Dynamic Email Templates over SendGrid API. I understand there are some threads on this already, however I have not been able to get these to work. I have a basic template with some dynamic variables based on searches that I want emailed to the user. This is all works except the html is always rendered in text despite applying what I have seen in a number of other threads here. Would be grateful for any help here. Views.py def customer_selections_sent(request): #make=request.POST['makeselection'] if request.method == 'GET': current_site = get_current_site(request) emailto = request.user.email_user user = request.user.username #call session values from SearchInventory function modelvalue =request.session.get('modelvalue') makevalue =request.session.get('makevalue') subject = 'ShowVroom Selections' #create variables to be used in the email template Email_Vars = { 'user': user, 'make': makevalue, 'model': modelvalue, #'offer': DisplayInventory.GaragePrice, 'domain': current_site.domain, } #create the email msg message = get_template('customer_selections_email.html').render(Email_Vars) message.content_subtype = "html" # Main content is now text/html #send email request.user.email_user(subject, message) #return redirect('customer_selections_sent') return render( request, 'customer_selections_sent.html', { 'title':'Deals are on the way', 'body':'We will email you shortly with more detail on your choices, you can respond to the dealers via the app until you agree to a viewing, test or purchase … -
How to have the choices for a Django Model object come from the corresponding instance of another model?
I am trying to set the choices for a Child field equal to two choices that are fields that come from the Parent class that it's related to (each child only has one parent). How do I access these values? class Parent(models.Model): attribute1 = models.CharField(max_length=100) attribute2 = models.CharField(max_length=100) class Child(models.Model): choices_in = [{{ Parent.attribute1 }}, {{ Parent.attribute2 }}] parent = models.ForeignKey(Parent, on_delete=models.CASCADE) item = models.CharField(max_length=100, null=True, choices=choices_in) -
Is it safe to edit the django-allauth translation files?
I want to edit the django-allauth translation files. When I first opened the en django.po file, PyCharm gave the message: This file does not belong to the project. If I edit the file, is it going to cause problems that I don't want or can I edit the translation without messing something up? -
validation error not seen in template form using form
validation error is not shown before also when i created form using form api i send error but is does not appear in html and now also when created User using UserCreationForm now also error not appered in html submitting this form without fillig single field. views.py file from django.shortcuts import render from .forms import signup # Create your views here. def sign_up(request): fm = signup() if request.method == 'POST': fm = signup(request.POST) if fm.is_valid() : print('until this runs') fm.save() else: fm = signup() print(fm.errors) return render(request, 'at/signup.html', {'form': fm}) forms.py file from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class signup(UserCreationForm): class Meta: model=User fields=['username','first_name','last_name','email'] html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>user regisration</title> </head> <body> {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} <form action="" method='POST' novalidate> {% csrf_token %} {{form.as_p}} <input type="submit" value='submit'> </form> <form action="" method='POST' novalidate> {% csrf_token %} {% for fm in form %} {{fm.label_tag}} {{fm}} {{fm.errors|striptags}} <br> <br> {% endfor %} <input type="submit" value='submit'> </form> </body> </html> -
How to use Primary Key in Django context view to render on html in python for loop
I have this method in my views followed by my html: `def index(request): context = { "user": User.objects.get(id = request.session['user_id']), "book": Book.objects.all(), "review": Book.objects.get(pk=1).book_reviews.all() } return render(request, "books_home.html", context) {% for Book in book %} {{Book.contributor.id}}<br> Book Title: <a href="{{Book.id}}">{{Book.title}}</a><br> Author: {{Book.author.name}}<br> Contributor: <a href="{{Book.contributor.id}}">{{Book.contributor.first_name}} {{Book.contributor.last_name}}</a><br> {% for book_reviews in review %} <a href="{{User.id}}">{{book_reviews.poster.first_name}} {{book_reviews.poster.last_name}}</a> says: {{book_reviews.content}}<br> Rating: {{book_reviews.rating}}<br> Posted on: {{book_reviews.created_at}}<br> {% endfor %} {% if Book.contributor.id == request.session.user_id %} <a href="reads/{{Book.id}}/delete">Delete All</a>{% endif %} <hr>` I'm having a problem with "review": Book.objects.get(pk=1).book_reviews.all(), the pk=1 is the problem. I don't know how to run through each pk so that each review is rendered, not just those with pk=1.