Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It is possible to run two apps on different ports in single Django project?
I want to run 2 django apps on different ports in single project. It is possible? If so, how do I do it? -
Django rest framework, trying to customize the browsable API
I have a Django rest framework and I'm trying to customize one of the API's browsable API but I can't seem to be able to refer to it in the HTML File. <!DOCTYPE html> {% load rest_framework %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Second GDT Options</title> </head> <body> <form action="{% url 'secondgdt' %}" method="post"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> </body> </html> secondgdt/urls.py: from django.urls import include, path from rest_framework.routers import DefaultRouter from .views import PointsViewSet router = DefaultRouter() router.register(r'secondgdt', PointsViewSet, basename='secondgdt') urlpatterns = [ path('', include(router.urls)), ] This code raises the following error when running the server: NoReverseMatch at /secondgdt/ Reverse for 'secondgdt' not found. 'secondgdt' is not a valid view function or pattern name. -
Ifequal in django templates
Models.py solution_req = models.CharField(max_length=250, default=0, choices=(('FLC', 'FLC'), ('FSC', 'FSC'), ('Crate', 'Crate'), ('PPBox', 'PP Box'))) HTML {% ifequal l.solution_req PPBox %} <a href="{% url 'emp:ppbox_form' l.pk %}" class="btn btn-primary">Create Solution</a> {% else %} <button class="btn btn-primary" disabled> Create Solution </button> {% endifequal %} The above are my models and django templates The problem is when the object has solution_req as PPBox it is still showing the disabled button instead of the link -
Django ORM query join unrelated tables on two fields
The problem I'm writing a program where I register treatments performed on patients in various medical places. Each treatment is performed on certain body part and each medical place can define their own way of naming those body parts. My models look like this: class Treatment(Model): medical_place = ForeignKey(to=MedicalPlace, on_delete=PROTECT, related_name='treatments') body_part = CharField(max_length=64, choices=BodyPart.choices(), db_index=True) ... (some other fields) ... class LocalProcedure(ProcedureBase): medical_place = ForeignKey(to=MedicalPlace, on_delete=PROTECT, related_name='procedures') identifier = CharField(verbose_name=_('Procedure number'), max_length=64, blank=False, null=False) description = CharField(verbose_name=_('Procedure description'), max_length=256, blank=True, null=False) body_part = CharField(max_length=64, choices=BodyPart.choices(), blank=False, db_index=True) class Meta: unique_together = (('body_part', 'medical_place', 'identifier'),) I need to retrieve list of "LocalProcedure" objects with annotated: count of related treatments count of related treatments performed up to X days ago (Treatments model has created datetime field I didn't show here) Solutions I have tried so far I can retrieve annotated list of LocalProcedures while using subqueries: related_treatments = Treatment.objects.filter( body_part=OuterRef('body_part'), medical_places=OuterRef('medical_place'), ).values( f'body_part', ) LocalProcedure.objects.annotate( treatments_count = Subquery(related_treatments.annotate(count=Count('pk')).values('count'), treatments_count = Subquery(related_treatments.filter(created__gt=now()).annotate(count=Count('pk')).values('count'), ) but this solution does indeed perform subqueries, whereas joining those two tables (when writing raw query) is much much faster. Any help appreciated. -
Displaying objects from a query inside a loop
I'm just a newbie in python and django, and I'm quite lost on my current issue, this problem somehow not new to some, hoping to get some guidance for me to solve this matter. I performed my first query to get a list of foreign key values and used a loop to pass the individual value and used it as a param to my second query. Technically I did my second query inside the iteration of the loop. Then I used and get the iterated values of my second query and pass it on the self.paginate_queryset in order for me to serialize it and produce the response on my get_paginated_response. As part of observing, I printed all the result of my second query inside the said loop earlier, and it worked properly, but when I tried to run it on postman, I noticed the response only produced one result from my series of results base on the given loop. What exactly do I need to do to produce all the needed results? Here is my function in views.py: def get(self, request, *args, **kwargs): global friend, request_queries self.pagination_class = PageNumberPagination friends = Friend.objects.filter(from_user=request.user.pk) for friend in friends: request_queries = GosamFriendProfile.objects.raw("""SELECT * … -
Related Field got invalid lookup: icontains (views.py)
I am trying to write a search field. It works for some of the module fields. My problem is when I use a ForeignKey field. show error [Related Field got invalid lookup: contains] I'm not sure where I did wrong. my models.py class Home(models.Model): type_home = models.CharField(max_length=255) def __str__(self): return self.type_home class Furniture(models.Model): name = models.CharField(max_length=255) type_home = models.ForeignKey(Home, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name my views.py class HomeListView(ListView): model = Home def get_queryset(self): qs = super().get_queryset() self.query = "".join( c for c in self.request.GET.get("query", "") if c.isalnum() or c.isspace() ).split() if self.query: name_qs = super().get_queryset() type_home_qs = super().get_queryset() for term in self.query: name_qs = name_qs.filter(Q(name__icontains=term)) type_home_qs = type_home_qs.filter( Q(type_home__icontains=term) ) qs = name_qs | type_home_qs return qs help me, please Thanks -
__str__ returned non-string (type Leads)
I am getting the following error and I am not able to figure it out: TypeError: str returned non-string (type Leads) class Pfep(models.Model): client = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='vendor_owner') receiver = models.CharField(max_length=250, default=0 ,blank=True, null=True) receiver_location = models.CharField(max_length=250, default=0 ,blank=True, null=True) def __str__(self): return self.client class PPboxSol(models.Model): box_length = models.IntegerField(default=0, blank=True, null=True) box_breadth = models.IntegerField(default=0, blank=True, null=True) box_height = models.IntegerField(default=0, blank=True, null=True) created_on = models.DateField(auto_now_add=True) pfep = models.ForeignKey(Pfep, on_delete=models.CASCADE, related_name='pfep_box_sol') created_by = models.ForeignKey("packsapp.Employee", on_delete=models.CASCADE, related_name='ppbox_createdby') Views.py class PpboxsolFormView(CreateView): model = PPboxSol form_class = Ppboxsolform template_name = 'pfep/PpboxsolForm.html' def get_initial(self): initial = super().get_initial() initial['pfep'] = Pfep.objects.get(pk=self.kwargs['pk']) return initial def form_valid (self, form): if self.request.user.employee.employee_role == 'admin': product = form.save(commit=False) product.created_by = Employee.objects.filter(user=self.request.user.id)[0] product.save() messages.success(self.request, 'The PP Box Solution was created with success!') return redirect('emp:ppbox_table') else: messages.success(self.request, "You don't have permission to create Solution!") return redirect('emp:ppbox_table') return redirect('emp:pfep_table') Urls.py path('ppboxsol/add/<int:pk>/', PpboxsolFormView.as_view(), name='ppbox_form'), Do I need to add def __str__(self): to model PPboxSol as well ? -
Djano/Google Sheets API Model/View Question
I'm very new to Python/Django: I've tested the Google Sheets API by itself and it works. Modifying it slightly, I've placed it in my model as follows: from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' SAMPLE_RANGE_NAME = 'Class Data!A2:E' def mainLoop(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME).execute() values = result.get('values', … -
Implement Push notifications in DRF and ReactJS
I am a beginner so please forgive me if I sound silly. I am trying to make a Rest API using DRF and am using serializers for connecting the models and retrieving the data in ReactJS using the fetch method. I wanted to have the functionality of push notifications, and use the data of the different models in the notifications. Any suggestions? -
Django open word document with google docx
I am generating a word document with a unique name while running django and want to display the same document file in google docx viewer once the file is generated. I tried using Iframe: but unable to view the document. Where am I going wrong? -
Python Django email login/authenticate 'user is None' with ModelBackend, CustomUserModel
I tried to make a email login/authenticate in views.py, but it returns 'user is None'. I tried to use just email for login not username. If I tried to login with email, it seems to take 'user is None' with custom error messages 'invalid credentials' in views.py. Django version: 3.0.4 // Model: Custom User Model (AbstractBaseUser) -> USERNAME_FIELD = 'email' // Backend: ModelBackend -> use email for username Problem 1: def signin in Views.py returns 'user is None' // Problem 2: model have a password(default), password1 and password2(both defined by UserCreationForm) users_models.py from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import AbstractBaseUser from django.db import models from django import forms from django.utils import timezone from .users_managers import UserManager class User(AbstractBaseUser): USERNAME_FIELD = 'email' email = models.EmailField( verbose_name='email', max_length=255, db_index=True, unique=True, ) password1 = PasswordModelField('password', max_length=50, error_messages={something},) password2 = PasswordModelField('password check', max_length=50, error_messages={something},) ... objects = UserManager() class Meta: db_table = 'users' verbose_name = 'user' verbose_name_plural = 'users' users_forms.py from django import forms from django.contrib.auth import authenticate, get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField from .users_models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField( label='password', strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'something'}), error_messages={something}, ) password2 = forms.CharField( label='password check', widget=forms.PasswordInput, error_messages={something}, ) class Meta: model = … -
Django only authenticates superuser
I am new in Django. I have a problem with authenticate(). It only authenticates the superuser. For any other user it returns None. I use "user_id" field instead of "username" field. I don't want to user Django forms. this is my models.py. models.py class UserProfileManager(BaseUserManager): def create_user(self, user_id, first_name, last_name, user_class, password = None): user = self.model(first_name = first_name, last_name = last_name , user_id = user_id, user_class = user_class) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, user_id, first_name, last_name , password = None): user = self.create_user(user_id, first_name, last_name, None, password = password) user.is_superuser = True user.is_staff = True user.save(using = self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length = 255) last_name = models.CharField(max_length = 255) user_id = models.IntegerField(unique = True, null = True) user_class = models.ForeignKey(Class, on_delete = models.PROTECT, default = None, unique = False, null = True) is_active = models.BooleanField(default = True) is_staff = models.BooleanField( default = False) objects = UserProfileManager() USERNAME_FIELD = 'user_id' # REQUIRED_FIELDS = ['first_name', 'last_name'] def get_short_name(self): return self.first_name def get_full_name(self): return '{} {}'.format(self.first_name, self.last_name) def __str__(self): return '{} {}'.format(self.first_name, self.last_name) this is my views.py. views.py class HomeView(TemplateView): template_name = 'user_profile/home.html' def post(self, request, *args, **kwargs): if request.method == 'POST': user_id = request.POST.get('user_id') … -
Why Django server is not working after finished the code
I just started learning Django, trying to build my first blog, after finished the code, I tried to run the server but it's not working, please help me.here is the error -
How to save multiple object in a single POST request
I am new to DRF I am saving a user details and his pets details . Here is the model class Users(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) job = models.CharField(max_length=255, blank=True) age = models.CharField(max_length=255, blank=True) class PetDetails(models.Model): user = models.ForeignKey( Users, on_delete=models.CASCADE, blank=True, null=True) pet_name = models.CharField(max_length=255, blank=True) pet_color = models.CharField(max_length=255, blank=True) pet_category = models.CharField(max_length=255, blank=True) In this I need to save both user and his pets in a single Post request. So I created a serializer like this class UserCreateSerializer(ModelSerializer): class Meta: model = Users fields = ['first_name','last_name','job','age'] class PetDetailCreateSerializer(ModelSerializer): user = UserCreateSerializer() class Meta: model = PetDetails fields = ['user','pet_name','pet_color','pet_category'] def create(self, validated_data): user_data = validated_data.pop('user') user_obj = Users.objects.create(**audit_data) Pet_details = AuditPlanDetail.objects.create(user=user_obj, **validated_data) return Pet_details The issue I am facing is if a single person can have multiple pets. For Example John is a user and he having two Pets. So in this cases two users object will creating .How to resolve this OR is there any other methods for handling this -
How do I fix my docker-compose.yml , error in installing Mayan-EDMS with django
I am trying to install the Mayan-EDMS image with the Django app and Postgres database using docker-compose but each time, I try to build docker-compose using docker-compose up it gives an error. ERROR: yaml.parser.ParserError: while parsing a block mapping in "./docker-compose.yml", line 8, column 3 expected <block end>, but found '<block mapping start>' in "./docker-compose.yml", line 29, column 4 here is my docker-compose.yml docker-compose contain postgres:11.4-alpine,redis:5.0-alpine and mayanedms/mayanedms:3 version: "3" networks: bridge: driver: bridge services: app: container_name: django restart: always build: context: . ports: - "8000:8000" volumes: - ./app:/app environment: - DB_NAME=app - DB_USER=insights - DB_HOST=db - DB_PORT=5432 depends_on: - db command: > sh -c "mkdir -p logs media && python manage.py wait_for_db && python manage.py runserver 0.0.0.0:8000" db: image: postgres:11.4-alpine container_name: postgres volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=insights - POSTGRES_DB=app redis: command: - redis-server - --appendonly - "no" - --databases - "2" - --maxmemory - "100mb" - --maxclients - "500" - --maxmemory-policy - "allkeys-lru" - --save - "" - --tcp-backlog - "256" - --requirepass - "${MAYAN_REDIS_PASSWORD:-mayanredispassword}" image: redis:5.0-alpine networks: - bridge restart: unless-stopped volumes: - redis_data:/data mayanedms: image: mayanedms/mayanedms:3 container_name: mayanedms restart: unless-stopped ports: - "80:8000" depends_on: - db - redis volumes: - mayanedms_data:/var/lib/mayan environment: &mayan_env MAYAN_CELERY_BROKER_URL: redis://:${MAYAN_REDIS_PASSWORD:-mayanredispassword}@redis:6379/0 MAYAN_CELERY_RESULT_BACKEND: … -
How to add the absolute URL field to related post in Django models
I was wondering if there's a way to add absolute URL field to related post inside the Django model. I tried using slug field but that didn't work. -
Create a seperate model with other fields for users with staff user status?
I want to create another model only for the staff and not for the admin or normal users. The model will have some other data that will also be visible for the other users but the other users will not require any if this data. Also, the staff members will have another separate app for themselves. How do I link another model to each user that has a staff permission? class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Not sure how i'm supposed to link only the staff members. -
how to create custom admin panel for django
Hi there I'm learning to django and I want to create custom admin for my django project so I can deliver my project to clients with beautiful admin panel. Please suggest me some ideas for doing this. can it be possible with react? Please share your thoughts thanks -
How to create search field lookup like Yahoo Finance symbol field
Guys i want to create search in one field where when a user types code it can see drop down suggestions ( from only db not internet) like the one from https://finance.yahoo.com/quote/AAPL. When i type AAPL ticker in yahoo finance search field -it gives autocomplete or suggestions like Apple Inc and Equity-NMS. I am not sure how it is called as i am new to django but i would like to learn what technology , package is used to create such dynamic form. I want create form my own DB rather than from internet so i assume it should be easier to implement ? What type of method do they use so i can do my reserach and explore more about it. I looked to autocomplete light but i feel like it is not what i am looking for. Would appreciate any advice and suggestions. -
How can I add an object to a group when it is created?
I need to save an object to a group at the time of creation. I have Porumbei and Grupuri models. Each Porumbei must belong to a Grupuri. I have 4 different Grupuri and depending on form fields value, it must be added to the right Grupuri. Is there a 'best practice'? Below are may models. Grupuri class Grupuri(models.Model): """ Definire model pentru salvarea porumbeilor in grupuri""" nume_grup = models.CharField(max_length=50, unique=True) porumbei = models.ManyToManyField(Porumbei, related_name="grup_porumbei") Porumbei class(models.Model): id_porumbel = models.AutoField(primary_key=True) serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") is_active = models.BooleanField(default=True) status = models.ForeignKey(StatusPorumbei, on_delete=models.PROTECT) ... My view def porumbelnou(request): if request.method == "POST": # crescator=request.user - folosit pentru a filtra porumbeii crescatorului logat form = AdaugaPorumbel(request.POST, request.FILES, crescator=request.user) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return redirect('porumbei') else: # crescator=request.user - folosit pentru a filtra porumbeii crescatorului logat form = AdaugaPorumbel(crescator=request.user) context = { 'form': form, } template = loader.get_template("adaugare-porumbel.html") return HttpResponse(template.render(context, request)) What I try but it got me MultiValueDictKeyError on 'id_porumbel' if form.data['is_active']: toti = Grupuri.objects.get(nume_grup__exact="Toti porumbeii") toti.porumbei.add(form.data['id_porumbel']) -
How to run an entire external python file on click of a button in html
I want to run a python file from an html page. I want to run the entire script and not a single function. Returning a value to the page is not required -
Override requiered field in validator django DRF
I have simple EmployeeSkill and Skill models: class EmployeeSkill(models.Model): # this is required employee = models.ForeignKey( Employee, on_delete=models.CASCADE ) # this is required skill = models.ForeignKey( Skill, on_delete=models.CASCADE ) def skill_name(self): return self.skill.name class Skill(models.Model): # this is required name = models.CharField(max_length=255, unique=True) I want to keep the skill attribute of EmployeeSkill required in the model, but I want to enable passing only a skill name in the serializer, which would get or create the appropriate Skill. Here is my serializer: class EmployeeSkillSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "employee", "skill", "skill_name", ) model = EmployeeSkill extra_kwargs = { "skill": {"required": False}, } def validate_skill(self, value): """ custom validator for skill. skill can be empty if skill_name is valid """ if value is None: skill_name = getattr(self, "skill_name", None) if not (skill_name and type(skill_name) is str): raise serializers.ValidationError( "if no skill is provided, skill_name should be a valid string" ) elif not type(value) is Skill: raise serializers.ValidationError("skill must be of type Skill or None") return value def create(self, validated_data): if (not self.skill) and self.skill_name: validated_data["skill"] = Skill.objects.get_or_create(skill_name=self.skill_name)[0] super().create(validated_data) The problem is, I still get an error: { "skill": [ "This field may not be null." ], } Any idea on … -
Unable to pass arguments in python3 class
Firstly, I created a class that has init() on it in models.py, as you can see below. And when I import it in my views.py, the vscode intellisense also shows that my class takes 4 arguments. But when I try to run the program, it shows me an error saying that the class doesn't take any arguments. Any help would be appreciated, ty. // models.py --------------- from django.db import models class destination: def __init__(self, name, desc, price, img): self.name = name self.desc = desc self.price = price self.img = img // views.py -------------- from django.shortcuts import render from .models import destination dest1 = destination('Bali', 'Nice place to visit', 1000, 'destination_1.jpg') dest2 = destination('Mumbai', 'The city that never sleeps', 500, 'destination_2.jpg') dest3 = destination('Sylhet', 'The city of tea', 100, 'destination_3.jpg') dests = [dest1, dest2, dest3] def travello(req): return render(req, 'index.html', {'dests': dests}) // when I run python3 manage.py runserver ------------------------------------------ Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/adnanbadshah/test/lib/python3.7/site-packages/django/core/management/base.py", … -
Django Ajax like button not changing when user likes a post in a post list
I am trying to build a like button like social media apps where user likes the button on a post and then the button changes, however, my button does not change but, the like count does change. I am using ajax. in my post list template i ave this that includes the like form: <div id="like-section"> {% include 'home/posts/likes.html' with post=post %} </div> my likes.html: {% if request.user.is_authenticated %} <form action="{% url 'home:post-like' post.id %}" method="POST"> {% csrf_token %} {% if post.is_liked %} <button type="submit" id="likeBtn" data-url="{% url 'home:post-like' post.id %}" data-token="{{ csrf_token }}" name="post_id" value="{{ post.id }}" class="btn btn-sm"> <span class="text-primary"> <i class="fas fa-thumbs-down"></i> {{ post.likes.count }} </span> </button> {% else %} <button type="submit" id="likeBtn" data-url="{% url 'home:post-like' post.id %}" data-token="{{ csrf_token }}" name="post_id" value="{{ post.id }}" class="btn btn-sm"> <span class="text-primary"> <i class="fas fa-thumbs-up"></i> {{ post.likes.count }} </span> </button> {% endif %} </form> {% endif %} my view: @login_required def post_like(request,id): data = dict() post = get_object_or_404(Post, id=id) user = request.user if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['html'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) return JsonResponse(data) my javascript code: $(document).ready(function (e) { $(document).on("click", "#likeBtn", function (e) { e.preventDefault(); var pk = $(this).attr("value"); var tk = … -
How do I access the original data from object in python. Here I've used group by to group data. Can someone please help me with this issue?
I am trying to group data based on the following data fields I have, and when I am not able to access the original data in the fields Printing the filtered_data is giving something like "object at 0x10dd1abf0>", so I need to access the original human-readable value in the objects. data_objects = ['*', '*', '*', ......] // This is list of data items filterd_data_objects = groupby( data_objects, lambda data: (data.x, data.y, data.z) and data.p ) for filterd_data_object, _ in filterd_data_objects: x = data_object[0] // this is not working I've tried this to access the original data y = data_object[1] z = data_object[2] p = data_object[3]