Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tenants AssertionError: First parameter to ForeignKey must be either a model, a model name, or the string 'self'
im trying to implement tenancy app using django-tenants but when i try to makemigrations it raise this error AssertionError: ForeignKey(('users.User','rooms.Room','rooms.City')) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' my django version is 3.2 from django_tenants.models import TenantMixin, DomainMixin class User(AbstractBaseUser,PermissionsMixin,TenantMixin): username = models.CharField(max_length=80,unique=True) active = models.BooleanField(default=True) #others USERNAME_FIELD = 'username' objects = AccountManager() def __str__(self): return self.username def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True class Domain(DomainMixin): pass class Room(TenantMixin): room_no = models.IntegerField() beds = models.IntegerField(default=2) here is my settings.py SHARED_APPS = [ 'django_tenants', 'users', 'rooms', 'rosetta', 'widget_tweaks', 'import_export', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TENANT_APPS = [ 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = ( "users.User","rooms.Room","rooms.City" ) TENANT_DOMAIN_MODEL = "users.Domain" middleware classes at the top 'django_tenants.middleware.main.TenantMainMiddleware', my database setting DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', others settings DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) DEFAULT_FILE_STORAGE = 'django_tenants.storage.TenantFileSystemStorage' i tried several libraries but still i couldnt implement tenancy into my application note there are some more model class all of them inherited from TenantMixin thank you for helping .. -
I have an error msg trying to use a slug field that contains an unusual character
My DB, my model and my view are all defined to use unicode characters. The creation of the record is ok and a slug is correctly created with a value as for example corée. The problem raise right after the creation with a NoReverse match error msg. I had a look to the documentation but I don't understand what I'm doing wrong. Thanks for your support. Model: class Countrycode(models.Model): cou_code = models.CharField( "Country name", max_length=40, primary_key=True) cou_recblocked = models.BooleanField("Country record blocked") cou_creator = models.ForeignKey( User, on_delete=models.PROTECT, related_name='+', verbose_name="Created by") cou_creationdate = models.DateTimeField("Creation date", auto_now=True) cou_modifier = models.ForeignKey( User, on_delete=models.PROTECT, related_name='+', verbose_name="Last modification by") cou_modified = models.DateTimeField( "Last modification date", auto_now=True) slug = models.SlugField(max_length=50, allow_unicode=True) class Meta: ordering = ["cou_code"] def __str__(self): return self.cou_code def get_absolute_url(self): return reverse('countrycode_update', kwargs={'slug': self.slug}) View: from masterdat.models import Countrycode #----------------------- # List view Management #----------------------- class CountrycodeListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): permission_required = 'masterdat.view_countrycode' model = Countrycode paginate_by = 10 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) return context # Search bar def get_queryset(self): result = super(CountrycodeListView, self).get_queryset() query = self.request.GET.get('q') if query: query_list = query.split() result = result.filter( reduce(operator.and_, (Q(cou_code__icontains=q) for q in query_list)) ) return result #----------------------------------- # Create and Update Views Management #----------------------------------- … -
how to upload video multiple quality in python django?
While creating YouTube clone I want video quality management. Then I searched how to do that. Then I got ffmpeg library. But I don't got correct way of implementing it. Please suggest libraries or GitHub repositories for do that. NB: I using backend Django rest framework and front-end Reactjs. -
navbar dropdown, navbar login link does not work but the dropdown menu links do
Good morning community I am building my first application in Django and I have a problem with the navbar. The "login link" placed in the navbar does not work. The links that are on the dropdown menu work just fine. Any hints? Hereunder is my code, <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="http://127.0.0.1:8000/login" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Login </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li><a class="dropdown-item" href="http://127.0.0.1:8000/logout">Logout</a></li> <li><a class="dropdown-item" href="{% url 'simple_investing:register' %}">Register</a> </ul> </li> -
Do `Users` need to exist in Django DRF for SSO?
Basically I am implementing the following functionality where the Front end will send signed JWTs to the backend. If the backend is able to decode and hence validate the Token (i.e. the signature, claims, audience etc), then it will give access to the protected API resources: Now the users already exist in Azure AD (so I don't want to have to create/manage users in the Django DB aswell). So essentially all I want to do is protect the Django Restful API endpoints with validated Access Tokens. I was looking at Custom Authentication (by extending rest_framework.authentication.BaseAuthentication) but it seems that the authenticate method expects a User to be matched (Hence Users to exist) and returned for a successful authentication (I would like to just pass if JWT validation is success or raise Exception is there is an error). Django docs: Either way, authenticate() should check the credentials it gets and return a user object that matches those credentials if the credentials are valid. If they’re not valid, it should return None. I have achieved my desired flow (i.e. having no Django Users using method_decorator but this does not seem like a correct pattern for authentication: class ComponentViewSet(viewsets.ModelViewSet): queryset = Component.objects.all() serializer_class … -
I am getting an operational error in django 2.1 [duplicate]
Ok so i am getting an operational error where the request method is POST when I try to add a product through the admin panel. This is the view of the error Here is some relevant code I used models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2100) class Offer(models.Model): code = models.CharField(max_length=8) description = models.CharField(max_length=255) discount = models.FloatField() code in admin.py from django.contrib import admin from .models import Product admin.site.register(Product) If you need some other code, please tell me What do I do? -
Django Error while trying to create 2 files of urls in different apps
I am trying to create a Django project for the first time, I have a problem in my project when I try to run it I get a long error which ends with: line 6 07, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf 'djangoProject.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. in the beginning the code worked and the API worked as well with "skills" app, but after I added the "projects" app, I get the error as above I believe I'm doing something wrong, maybe the way I'm building the project is wrong. What I'm trying to do is have 3 different API's - with the "Skill", "Experience" and "Projects" this is the link to the product, if you look at the commits, if you go 1 commit back - it works, if you look at the current commit - it does not work https://github.com/itzikd1/DjangoProject Thanks -
How to render django html templates as plain text?
Is there any mechanism in django to render html as plain text. For example render the following: <h1>Title</h1> <p>Paragraph</p> As: Title Paragraph Specially for attaching text alternative for HTML emails -
JavaScript elements gets appended more that once
I'm creating a web app using Django and one of its web pages allows the user to comment under others' posts. Once a user comments, I'm using Javascript to add the comment to the database and display it among the other comments in a div called "comment_list". When I comment under a post for the first time, the comment is appended properly, only once. But when I comment for the second time, without refreshing the page, it gets appended twice. It gets appended thrice for the 3rd time and 4 times 4th the time and so on. This is my HTML code <button class="btn btn-dark" id="comment_{{post.id}}" onclick="comment('{{ post.id }}')" >Comment</button> <hr id="line1_{{post.id}}" style="display: none;"> <textarea class="form-control mb-2" id="comment_box_{{post.id}}" name="comment" style="display:none;" required></textarea> <button id="comment_button_{{post.id}}" class="btn btn-dark" style="display:none;">Comment</button></br> <hr id="line2"> <div id="comment_list_{{post.id}}"> {%for comment in comments%} {%if comment in post.comments.all%} <div> <p style="margin-left: 1cm;">{{comment.user}} - {{comment.content}}</p> </div> {%endif%} {%endfor%} </div> This is the Javascript function function comment(id) { document.querySelector(`#comment_box_${id}`).style.display = 'block'; document.querySelector(`#comment_button_${id}`).style.display = 'block'; document.querySelector(`#line1_${id}`).style.display = 'block'; document.querySelector(`#comment_${id}`).style.display = 'none'; document.querySelector(`#comment_box_${id}`).value="" document.querySelector(`#comment_button_${id}`).addEventListener('click', () => { fetch('/comment/' + id, { method: 'PUT', body: JSON.stringify({ post: document.querySelector(`#comment_box_${id}`).value }) }) .then((res) => res.json()) .then((res) =>{ var com = document.createElement('div'); com.innerHTML = `<p style="margin-left: 1cm;">${res.user} - … -
Reverse not found even if the name was set correctly Django
I have a view for a product liking like this below: @api_view(['POST']) @permission_classes([IsAuthenticated]) def LikeView(request, pk): product = get_object_or_404(Product, id=pk) product.bumps.add(request.user) return HttpResponseRedirect(reverse('detailcreate', args=[pk])) but when I am sending a post request like this: http://127.0.0.1:8000/api/like/04a544c1-78a2-4dc7-9b1c-897feb527541 I get an error: Reverse for 'detailcreate' not found. 'detailcreate' is not a valid view function or pattern name. My urls.py looks like this: from django.urls import path from .views import LikeView, ProductList, ProductDetail app_name = 'name' urlpatterns = [ path('<uuid:pk>', ProductDetail.as_view(), name='detailcreate'), path('', ProductList.as_view(), name='listcreate'), path('like/<uuid:pk>', LikeView, name='like_product'), ] so I don't know what is wrong, the name is corectlly set. pk is uuid -
what is the code in HTML to make the attached image
I'm a beginner and I'm trying to create a website to sell car parts but I'm having trouble finding the license plate. Thanks https://i.stack.imgur.com/lvJmQ.png -
AttributeError at /delete/1/ Generic detail view DeleteTodo must be called with either an object pk or a slug in the URLconf
I'm starting with Django, and i wanna create simple projects to test my skills. First is the simple todo list. I've found a problem during trying to create 'delete task' functionality on my project. views.py from django.shortcuts import render, redirect from django.urls import reverse_lazy from .models import Task from .forms import TaskForm from django.views.generic import DeleteView def index(request): return render(request, 'todoxd_app/index.html') def todo(request): objekt = Task.objects.all() context = {'objekt': objekt} return render(request, 'todoxd_app/todo.html', context) def new_todo(request): if request.method != 'POST': form = TaskForm() else: form = TaskForm(data=request.POST) if form.is_valid(): form.save() return redirect('todoxd_app/new_todo') context = {'form': form} return render(request, 'todoxd_app/new_todo.html', context) class DeleteTodo(DeleteView): model = Task template_name = 'registration/delete_todo.html'\ urls.py from django.urls import path, include from .views import DeleteTodo from . import views app_name = 'todoxd_app' urlpatterns = [ path('', views.index, name='index'), path('todo/', views.todo, name='todo'), path('new_todo/', views.new_todo, name='new_todo'), path('delete/<post_pk>/', DeleteTodo.as_view() ,name='delete_todo'), ] delete_todo.html Title {% extends 'todoxd_app/base.html' %} {% block content %} {% csrf_token %} DELETE TASK {% endblock content %} from django.db import models class Task(models.Model): name = models.CharField(max_length=50) description = models.TextField() date_added = models.DateField(auto_now_add=True) date_end_of_task = models.CharField(max_length=20) progress = models.BooleanField() def __str__(self): return self.name I would be grateful for help (: -
Create page tree nodes in django cms from data in model
I'm creating a web site using djangocms and I need to generate some page in the tree page node from the data in a model. For example: I have a Model called Category and I want to create automaticaly a page for every category that I have in my model. Then if is posible I want to render with some template the other info that I have in that model. Final example: From the name of the category in every category generate the Title and slug of the page and the other data of the category must be rendered as the content of the page. -
TypeError at /index 'ModelBase' object is not iterable in django?
This is my index views file from where i store data on table def index(request): if request.method == "POST" : for staffs in staff : stf_if = 'staff_id' + {{staffs.id}} staff_id = request.POST[stf_if] at_if = 'attendance' + {{staffs.id}} attendances = request.POST[at_if] date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() staffs = staff.objects.all() attendances = attendance.objects.all() amounts = amount.objects.all() count_id = staff.objects.latest('id') date = datetime.date.today() return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'amount': amounts, 'count_id': count_id, 'date': date}) here are error on for staffs in staff : This is my index.html template file where is form <form action="/index" method="POST"> {% csrf_token %} {% for staffs in staff %} <input type="hidden" name="staff_id{{staffs.id}}" value="{{staffs.id}}"> <input type="hidden" name="attendance{{staffs.id}}" id='input_attendance{{staffs.id}}'> <tr> <td> {{staffs.id}} </td> <td> {{staffs.name}} </td> <td> <div class="btn-group"> <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='present{{staffs.id}}'> Present </button> <div class="dropdown-menu"> <a class="dropdown-item" onclick="attendance_present({{staffs.id}})">Present</a> <a class="dropdown-item" onclick="attendance_absent({{staffs.id}})">Absent</a> <a class="dropdown-item" onclick="attendance_half_day({{staffs.id}})">Half-day</a> </div> </div> </td> <td> {{staffs.role}} </td> </tr> {% endfor %} <tr> <button type="submit" style="float:right" class="btn btn-info">Save</button> </tr> </form> I am new in django and whats the problem is I not understand, Please help me and thanks for help me in advance. -
Django how can I get relative path so static images to save my images there
I have an image to be saved but when I save it in other folther that is not the static folther I receive an error and it say the folther is not thrusted. I need the path to static foltherto save in database that is not hardedcoded -
Python image in `bytes` - get height, width
I'm trying to detect width and height of an image before saving it to the database and S3. The image is in bytes. This is an example of an image before saved to Django ImageField: NOTE: I don't want to use ImageFields height_field and width_field as it slows down the server tremendously for some reason so I want to do it manually. The image is downloaded using requests: def download_image(url): r = requests.get(url, stream=True) r.raw.decode_content = True return r.content -
Getting MultiValueDictKeyError perhaps due to interference
I have made a main search function in my base html file and then made filters for specific searches. the base html file name is consult_home.html. consult_home.html <form method="GET" action="{% url 'search' %}"> <input type="search" placeholder="Search with any keyword..." name="searched" /> <button class="srch-bttn" type="submit">SEARCH &nbsp<i class="fas fa-search"></i></button> </form> and the views function that handles the above form is this view.py def search_univ(request): # SEARCHED CONTENT WILL BE DSIPLAYED IN THSI PAGE BAR IS IN CONSULT_HOME.HTML searched= request.GET['searched'].lower() if len(searched)>78 or len(searched)<1: search_result = Laws.objects.none() #return HttpResponse('The search is invalid. Please return back to previous page.') else: search_resul_Lawcat= Laws.objects.filter(law_category__icontains=searched) search_result_Judge =Laws.objects.filter(judgements__icontains=searched) search_result_Title =Laws.objects.filter(title__icontains=searched) search_result= search_resul_Lawcat.union(search_result_Judge, search_result_Title) if search_result.count() == 0: messages.warning(request, 'No search results found...') return render(request, 'search.html', {'searched': searched, 'search_result':search_result}) Now i have added a button for more specific searches that leads to the page and the codes in it is search_citation <form method="POST" action="{% url 'search' %}"> {% csrf_token %} <input class="citation-srch" type="search" placeholder="eg. SCC(volume number) (page number) etc..." name="query" /> <button class="srch-citation-bttn" type="submit"><i class="fas fa-search"></i></button> </form> and the views function that handles the above form is vews.py def srch_by_citation(request): if request.method == 'POST': searched_citation = request.POST.get['query'] if len(searched_citation)>78 or len(searched_citation)<1: search_result = Laws.objects.none() else: search_result = Laws.objects.filter(equivalent_citations__icontains=searched_citation) if … -
Django constraint: allowing 1 field to only have a single combination with another field
I am trying to create a constraint on my Offer table, which has an offer_id (charfield) and a product_id (foreign key) where an offer_id can only be combined with 1 product. It is not allowed that an offer_id is combined with multiple products. I can not make offer_id simply unique, since this table uses historical data. How can I make a constraint for my django Model, which makes sure that every offer_id is at most linked to 1 product, a product can have multiple offer_ids and a single offer_id can occur multiple times due to historical data. Simple overview of offer model: class Offer(models.Model): offer_id = models.CharField(max_length=45, default=-1) seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) time = models.DateTimeField(default=timezone.now) class Meta: constraints = [ models.UniqueConstraint(fields=['offer_id'], condition=?, name='unique_offer_product') ] def __str__(self): return f"Product {self.product} with seller {self.seller} has offer_id {self.offer_id}" -
django.db.utils.OperationalError: no such table: price_category AFTER GIT CLONE
I've been trying to solve this problem for a day now... and I can't seem to figure out why. So after I'm working on two computer. Computer A is working fine. not throwing any error. but Computer B after git clone keep throwing this error although I think I've set my .gitignore fine. Things I check/tried: 1.makemigrations, migrate- its throwing the same error. 2.make sure my .gitignore is set properly. 3.Looked at all the code between two computer. Since All i did with computer B was git clone, all I had to do is checkout to the branch I commited after I git clone so all the code is the same. I really cant figure out why its throwing this error. Deleted the cloned one n git clone again. ALL to no avail. It's making me wanna cry since I have no idea why.... tho one thing I can say for sure is the last thing I was working on on computer A was the price app. PLEASE HELP, any clues? What can I do? forms.py from django import forms from django.contrib.auth.models import User from .models import Price, Category choices= Category.objects.all().values_list('name', 'name') choice_list= [] for item in choices: choice_list.append(item) class … -
Django Media S3 - Model.get_queryset is accessing S3?
I have MEDIA files stored in S3 bucket and I noticed that REST API responses are very slow. What I also noticed is that Django tries to access the S3 when I do Model.objects.all(). Why it does that? Doesn't it store the URL in the database so it doesn't have to access S3 storage unless the URL is explicitly fetched (on the frontend side)? DEFAULT_FILE_STORAGE = 'project.storage_backends.MediaStorage' from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False The image field: image = models.ImageField(upload_to='images', max_length=2048, null=True, blank=True, height_field='image_height', width_field='image_width') image_height = models.PositiveSmallIntegerField(null=True, blank=True) image_width = models.PositiveSmallIntegerField(null=True, blank=True) -
Django not able to fetch model.objects data inside method of view class
I am not able to fetch data using model.objects from method inside view.py class Mean a while I am able to fetch data from out side of the method in the same class attached screenshot enter image description here enter image description here -
sending SMS to the user using fast2SMS
I want to send an SMS to the user in the Marathi language but in fast2SMS it is been send in the default language that is English. I have gone through the API Documentation of fast2sms but didn't found the answer to my query. please help how can I send the SMS OTP in marathi .enter image description here querystring = { "authorization":"SqbjiJDXHkYR2An46KOl8ZGexFmdsvWVc0fa3h1PgCIou9NMUTK5XiNwGH7jDVrmP6haAxpSZItyl0f3", "sender_id":"KAMALCLS", "message":"ur password is " +pw, "language":"english", "route":"p", "numbers":str(ph) } res = requests.request("GET",url,params=querystring) -
Importing from excel works with django's inbuilt ImportExportModelAdmin but not through user created import view
I have an excel file with data of employees... The unit name field in the excel sheet is linked to the unit table which is another model. Have included the ForeignKeyWidget in resources.py to look for the unit while importing and it works with django's inbuilt ImportExportModelAdmin. While importing through the user made view it throws following error. ['“A Unit” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
how to connect to postgres13 from spinning up docker-compose from inside ubuntu ec2 instance
I am running a ubuntu 20.04 on AWS ec2 instance and I have the following Dockerfile file configuration for my backend application: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /backend COPY requirements.txt /backend/ RUN pip install -r requirements.txt && \ pip install --upgrade pip COPY . /backend/ COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] docker-compose version: "3.3" services: db: image: postgres:latest container_name: db restart: always env_file: .env volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - backend_network backend: build: ./backend container_name: backend stdin_open: true tty: true restart: always env_file: .env volumes: - ./backend:/backend - ./backend/static:/backend/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - backend_network volumes: postgres_data: networks: backend_network: driver: bridge settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("POSTGRES_DB"), "USER": os.environ.get("POSTGRES_USER"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), "HOST": os.environ.get("POSTGRES_HOST"), "PORT": 5432, } } .env file # APP POSTGRES_DB=somedbname POSTGRES_USER=someuser POSTGRES_PASSWORD=somepassword # DATABASE # PUBLIC_DB DB_NAME=somedbname DB_USER=someuser DB_PASSWORD=somepassword DB_HOST=xxxx.yyy.us-east-x.rds.amazonaws.com and when after spinning up my docker compose file with the command docker-compose up -d --build it look like my app cannot connect to rds psql: error: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I am … -
Dictionary items not showing up in template in django
I have gathered data from two tables that is Orders and Purchases (joined) and saved that in dictionary, when I'm printing the qty on the console its giving me the value but when I'm trying to print the values on template it not showing up however columns from the orders table like first name last name status address is shown on the template but qty and product from the purchases table is not showing up on the template but can be easily printed on console can somebody help??? Models.py Dispatcher = models.ForeignKey(Dispatchers , null=True, on_delete=models.SET_NULL ) Firstname = models.CharField(max_length=200 , null=True) Lastname = models.CharField(max_length=200 , null=True) Email = models.CharField(max_length=200 , null=True) Address = models.CharField(max_length=200 , null=True) Country = models.CharField(max_length=200 , null=True) State = models.CharField(max_length=200 , null=True) status = models.CharField(max_length=200 , null=True) def __str__(self): return self.Lastname class purchases(models.Model): orders_id = models.ForeignKey(Orders , null=True, on_delete=models.SET_NULL ) product = models.CharField(max_length=200 , null=True) qty = models.CharField(max_length=200 , null=True) price = models.CharField(max_length=200 , null=True) def __str__(self): return self.product views.py file dispatcherOrders = {} orders = request.user.dispatchers.orders_set.all() for order in orders: dispatcherOrders[order] = purchases.objects.get(orders_id = order.id) print(dispatcherOrders[order].qty) return render(request , 'dispatcherOrders.html',{'dispatcherOrders' : dispatcherOrders}) dispatcherOrders.html {%for Orders in dispatcherOrders%} <tr> <th scope="row">1</th> <td>{{Orders.Firstname}}</td> <td>{{Orders.Lastname}}</td> <td>{{Orders.Address}}</td> <td>{{Orders.product}}</td> <td>{{Orders.qty}}</td> …