Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can do not delete post and comment whose deleted user in django?
Hello i recently study django and make board my question was that how can do not delete post and comment whose deleted users how can display deleted user's name in post and comment like 'deleted user' in board's user name (not blank or Null) yeah i know in this code user was conneted with post and comment through foreign key and on_delete=models.CASCADE and if user deleted the post and comment deleted automatically then how can i connect this table? using nickname? it was unique but can changed i wanna know how to solve this problem, need to some tips class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField(default= timezone.now()) def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() create_date = models.DateTimeField(default=timezone.now()) -
VS Code not using selected python interpreter
What's up fellas. I always seem to have this problem and I've tried various ways of fixing it. Including creating the settings.json file that you can see in the picture attached. The problem: VS Code isn't using my selected python interpreter (pictured in the bottom left hand corner of photo) which is in venv/bin/python. Even though I can select it as the interpreter in vs code when I do python manage.py runserver for Django it gives me an error due to it using an older version of python that came with my computer. I just tried to use pycharm for the first time because of this and ended up having the same problem. Is it just that the terminal isn't using the right version of Python maybe? VS Code Version: 1.62.3 Also I am on iOS (M1) Let me know if I can provide you with any further information, thanks. [![Image of my vscode set up][1]][1] ➜ Akutagawa . venv/bin/activate (venv) ➜ Akutagawa which python /usr/bin/python (venv) ➜ Akutagawa which python /usr/bin/python (venv) ➜ Akutagawa cd Djanrest/backend (venv) ➜ backend git:(main) ✗ which python /usr/bin/python (venv) ➜ backend git:(main) ✗ python manage.py runserver File "manage.py", line 17 ) from exc … -
Добрый день, кто может подсказать как реализовать данную задумку на DJANGO REST
Схема работы: 1 Пользователь регистрируется в нашей системе. При регистрации указывает логин, пароль и имя 2 Пользователь находит бота в Telegram и подписывается на него. На этом этапе требуется создать Telegram бота. 3 В личном кабинете генерирует токен и привязывает этот токен к своему чату. Простой способ реализации: любое входящее сообщение от пользователя бот запоминает как токен пользователя 4 Пользователь отправляет на API своё сообщение. В этот момент бот сразу дублирует его в Telegram. Пользователь должен получать только свои сообщения. Добрый день, кто может подсказать как реализовать данную задумку на DJANGO REST, или же вы видели похожие проекты на github -
Django web project not running
My Web Application is not running on the new system it says it does not recognize "python"/ "pip as an internal and external command. My Powershell Terminal ''' PS C:\Users\Nawaf Bhatti\Desktop\learn> python -m pip install pillow python: The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + python -m pip install pillow + ~~~~~~ + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ''' My cmd ''' C:\Users\Nawaf Bhatti\Desktop\learn\web_app>python manage.py runserver 'python' is not recognized as an internal or external command, operable program or batch file. ''' -
insert or update on table "django_admin_log" violates foreign key constraint
Trying to save a post on a django project I got this error The above exception (insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". ) was the direct cause of the following exception: The model: from django.conf import settings class Tag(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to='', blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title The view: from django.views.generic import ListView, DetailView from django.shortcuts import get_object_or_404 from .models import Post class BlogView(ListView): template_name = 'base/blog.html' queryset = Post.objects.all() paginate_by = 2 class PostView(DetailView): model = Post template_name = 'base/post.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs['pk'] slug = self.kwargs['slug'] post = get_object_or_404(Post, pk=pk, slug=slug) context['post'] = post return context How can I solve this problem? -
Able to run Dockerized Django app with supervisor locally, but timing out when deployed to Azure app services
So I have a Dockerized Django app running with uWSGI and NGINX, managed by supervisord (so both of them are run in the same container). It works fine and dandy when running it locally, but when I deploy it to a Azure web-app for containers, it fails to respond on the http warmup-request. I've tried doing different kinds of adjustments regarding the ports on Azure/in the app, but nothing seems to be working. The set-up I've been trying is: NGINX exposing the app in port 80, adding configuration in the Azure portal with PORT=80 NGINX exposing the app in port 8000, adding configuration in the Azure portal with PORT=80 and WEBSITES_PORT=8000 In both cases exposing both 80 and 8000 in the Dockerfile Increase the timeout-limit for the app to 1800 seconds But I'm still receiving the same error, and I really feeling I don't know where to go from here. Can anyone help me figure this one out? I'll post the logs and the relevant files below. As you can see in the logs, supervisor seems to be starting up, but not giving the response that Azure seems to need to start up the server. Repository structure myapp/ ┣ .devcontainer/ … -
Django making migrations
Consider the following three classes: class UUIDModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) class Meta: abstract = True class TimeStampedUUIDModel(UUIDModel): created = models.DateTimeField(auto_now_add=True, editable=False) modified = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True class UsefulClass(TimeStampedUUIDModel): name = models.CharField(max_length=150, unique=True) creator = models.ForeignKey('OtherClass', on_delete=models.SET_NULL, null=True) Based on these classes, when I am running the makemigrations command, Django will create two migrations. One contains the id, created, modified and name (!) fields and the second one adds the creator foreign key. What could be the reason of the creation of two migrations, instead of just one? -
how do i get all my object instances as an int
i am creating a ToDo app and i want to calculate the percentage of activities completed based on the total activities set my views.py def progress(request): todo1 = int(ToDo.objects.all().count()) complete1 = int(ToDo.objects.filter(completed=True)) todo = int(todo1) complete = int(complete1) percent = complete // todo * 100 context = { 'percent' : percent, } return render(request, 'percent.html', context) but i receive a TypeError: int() argument must be a string, a bytes-like object or a number, not 'QuerySet' i really need help -
hello how to change string type into <class 'django.db.models.query_utils.Q'>
''' string = Q(run_date = '2016-05-01') & Q(distance__gt = 20) | Q(distance__lt = 10) data = Test_allowed.objects.filter(q_pickled) return HttpResponse(data) got error "too many values to unpack (expected 2)" because type is str ''' -
Django - Find reserved times
I would like to show all the available times for the not booked appointment dates with a time interval between 11:00AM to 21:00PM: models.py class Appointment(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True) work = models.ManyToManyField(Therapy, related_name='work', verbose_name=_('Work'), blank=True) start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) views.py def check_available_hours(request): day_request = date.today() day_request1 = str(day_request) date_of_reference = datetime.strptime(day_request1, "%Y-%m-%d") initial_time = datetime.combine(date_of_reference.date(), time(11, 0)) final_time = datetime.combine(date_of_reference.date(), time(21,0)) appointments_of_day = Appointment.objects.filter( start_appointment__gte=initial_time, start_appointment__lte=final_time ) print(appointments_of_day) # This returns all appointments in a day reserved_times = [datetime(2021, 12, 8, 11, 0), datetime(2021, 12, 8, 15, 0)] hours_between = [datetime.combine(date_of_reference.date(), time(hour + initial_time.hour, 0)) for hour in range(((final_time - initial_time).seconds // 3600) + 1)] available_hours = [hour for hour in hours_between if hour not in reserved_times] return render(request, "name_template.html", {"hours": avaliable_hours}) If i set reserved_dates like above it works. However i'm trying to set it based on my models so i used below code but it doesn't return anything. reserved_times = [ appointment.start_appointment + timedelta(hours=i) for appointment in appointments_of_day for i in range((appointment.end_appointment - appointment.start_appointment).seconds//3600)] print(reserved_times) Any suggestions? Thank you -
Django - Return only checked object from nested JSON
I have a problem returning checked data from html page views.py: First I open JSON file and store it to data from django.shortcuts import render from django.http import HttpResponse, request import json from fpdf import FPDF from django.db import models # Create your views here. #invalid = '<>:"//\t\|?*' url = 'podaci.json' class PDF(FPDF): def header(self): self.image('Logo_SAVA_osiguranje_RGB.png',w=60) self.ln(20) with open(url,encoding="utf8") as f: data=json.load(f) def remove(string, i): a = string[ : i] b = string[i + 1: ] return a + b def display_data(request): render(request,'home.html',{'data':data}) if request.method=='POST': for podatak in request.POST.getlist('checks'): print(podatak) return render(request,'home.html',{'data':data}) html: in HTML i set a value of Checkbox to be an object of data <body class="container"> <form method="post"> {% csrf_token %} <button type="submit">Submit</button> {% for duznici in data %} <div class="card"> <div class="card-header" > {{duznici.NazivDuznika}} <input class="form-check-input" type="checkbox" name="checks" value='{{data}}'> </div> <div class="card-body"> <blockquote class="blockquote mb-0"> {% for podaci in duznici.DunningItems %} <p name="checks" value="{{NazivDuznika}}">{{podaci.BrojPolise}}</p> {% endfor %} </blockquote> </div> </div> {% endfor %} </form> </body> podaci.json structure: [ { "NazivDuznika": "xxxxxxxx", "Pib": "xxxxxxxx", "Mtbr": "xxxxxxxx", "IdLica": xxxxxxxx, "Email": xxxxxxxx, "DunningItems": [ { "BrojPolise": "xxxxxxxx", "Broj_dokumenta_Z": "xxxxxxxx", "Dug": xxxxxxxx, "Datum_Dospeca_Z": "xxxxxxxx", "RbRate": xxxxxxxx, "VrstaOsiguranja": "xxxxxxxx", "Rocnost": xxxxxxxx }, { "BrojPolise": "xxxxxxxx", "Broj_dokumenta_Z": "xxxxxxxx", "Dug": xxxxxxxx, "Datum_Dospeca_Z": "xxxxxxxx", … -
Storing Data in Database without Tables (Because I don't need Entities/Objects) Django Models class
Let me Explain the Whole Question Correctly. I have a class called CData and I just want to store 6 values in it. I don't want different instances/Objects of it because it is global data that is not related to its instances i.e. Its static and should be accessed only by Class itself No objects are to be created. Model.py from django.db import models # Create your models here. class Patient(models.Model): name = models.CharField(max_length=100, default='') dob = models.DateField() fever = models.BooleanField(default=False) cough = models.BooleanField(default=False) headache = models.BooleanField(default=False) diarrhea = models.BooleanField(default=False) diarrhea = models.BooleanField(default=False) tasteless = models.BooleanField(default=False) def __str__(self): return self.name class CovidPatient(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) def __str__(self): return self.patient.name class CData: total = 0 covid = 0 treatment = 0 recovered = 0 dead = 0 discharged = 0 def total_patient(self): self.total = len(Patient.objects.all()) return self.total def add_patient(self, pid): patient = CovidPatient.objects.get_or_create(id = pid) self.covid += 1 return patient.name def covid_patient(self): return self.covid def under_treatment(self): self.treatment = len(CovidPatient.objects.all()) return self.treatment def add_recovered(self, cpid): patient = CovidPatient.objects.get(id = cpid) self.recovered += 1 patient.delete() def total_recovered(self): return self.recovered def add_dead(self, cpid): patient = CovidPatient.objects.get(id = cpid) self.dead += 1 patient.delete() def total_dead(self): return self.dead def add_discharged(self, cpid): patient = CovidPatient.objects.get(id = … -
how to calculate gain loss in python
I have to calculate the gain loss of stocks in python,I used python library "capital-gains" which is only support python3.9+ version. Can anyone know any python library that i can use for calculate the capital gain loss which will support python 3.6,3.7,3.8 version.or older version of capital-gains which will support python older versions. -
Django testing views for logged user
I have a blocker which driving me to creazy. I would like to test view which is intended only for log in users. So basically in setUp(), I've created a user and in my test case I am trying to log in with his credentials, but still I can't get positive result. def setUp(self): self.custom_user = User.objects.create_user( username='test', first_name='test name', email='test@test.test', password='password', is_active=True, ) and then in tests case: def test_create_view_logged(self): login = self.client.login(email='test@test.test', password='password') self.assertTrue(login) response = self.client.get(reverse("new")) self.assertEqual(response.status_code, 200) Status: self.assertTrue(login) AssertionError: False is not true Any idea how to test Views for logged in users in Django? EDIT: Ok, so basically it was a simple as ... :) Authentication is provided via username field not as I tought vie email field. So the answer is: login = self.client.login(username='test', password='password') -
Importing Data from .sql file into postgresql database (Django)
I have a .sql file containing a 1 year amount of records, and I have a running Django app with a Postgresql database. I would like to import all the records on the .sql file into the new empty database. I used to use these two commands on a different project running with Docker : To export the database : docker exec -t *** pg_dumpall -c -U *** > dump_date +%d-%m-%Y"_"%H_%M_%S.sql To import the database : cat dump_***.sql | docker exec -i *** psql -U *** -d *** But without really understanding what I am doing, so I can't find the equivalent command to use in case I am not using Docker. Thank you for your help. -
how show product by subcategory in django?
i want to show product in category by subcategory. I wrote this but it show all product in category except subcategory!!!? i tested {% if category.childern.all %} in list.html but its not work model.py class Category(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200,db_index=True), slug = models.SlugField(max_length=200,db_index=True), ) parent = models.ForeignKey('self', related_name='children',on_delete=models.CASCADE,blank=True,null=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Product(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200,db_index=True), slug = models.SlugField(max_length=200,db_index=True), description = models.TextField(blank=True), price = models.PositiveIntegerField(), ) category = models.ForeignKey(Category, related_name='products' ,on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d',blank=True) available = models.BooleanField(default=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id,self.slug]) def __str__(self): return self.name view.py def product_list(request,category_slug=None): category = None categories = Category.objects.filter(parent=None) products = Product.objects.filter(available=True) if category_slug: language = request.LANGUAGE_CODE category = get_object_or_404(Category,translations__language_code=language,translations__slug=category_slug) products = products.filter(category=category) context = { 'categories':categories, 'category':category, 'products':products, } return render(request,'shop/product/list.html',context) list.html (it show when user click on subcategory in menu bar) {% extends "shop/index.html" %} {% block title %} product list {% endblock title %} {% block content %} <div class="container-fluid"> <div class="row mt-4"> <div class="col-9"> … -
How to insert image file using modal in django?
I want to insert image file using modal form in django framework? the html is not accepting the forms i am using right now. Below is the form I am using Views.py: Forms.py: Html: I am not able to use the below html in modal: def free_upload(request): if request.method == 'POST': imgform = ImageUForm(request.POST, request.FILES or None) if imgform.is_valid(): img_obj = imgform.instance imgform.save() return render(request, 'temp_test.html',{'form': imgform, 'img_obj':img_obj}) else: return HttpResponse("not valid") else: form = ImageUForm() return render(request, 'temp_test.html',{'form': form}) Forms.py: class ImageUForm(forms.ModelForm): class Meta: model = Image fields = ['title', 'image',] HTML: <form method="POST" enctype="multipart/form-data" > {% csrf_token %} <div class="row"> <div class="col-lg-6 col-md-12"> {{form.title|as_crispy_field}} </div> <div class="col-lg-6 col-md-12"> {{form.image|as_crispy_field}} </div> </div> <p> <button type="submit" href="{% url 'userload' %}" class="btn btn-primary">Upload </button> </p> </form> class Meta: model = Image fields = ['title', 'image',] -
how to resolve this error code in django: RelatedObjectDoesNotExist
How to resolve this error code in django rest-framework (RelatedObjectDoesNotExist at /api/following/) User has no following. -
Django is init view twice
Django is run in multithreading mode. Main Thread and Django MainThread How to run in a single-thread mode? Also how to init view file once? -
Cannot query "amclient15": Must be "Client" instance
Am trying to filter the appointments made by a specific client when he is logged in def user( request): client = request.user.client request.user.id appointments = Appointment.objects.filter(user=request.user) context = { 'client': client, 'appointments':appointments } return render(request, 'users/user.html', context) -
DRF ModelViewSet route get mixed in with ApiView route
I have the following views: class NotificationAPI(viewsets.ModelViewSet): authentication_classes = (CustomJWTAuthentication, SessionAuthentication) permission_classes = (IsAuthenticated,) queryset = Notification.objects.all() def get_queryset(self): qs = self.queryset.all() queryset = qs.filter(recipient=self.request.user.id) return queryset class MarkAsReadView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = [CustomJWTAuthentication, SessionAuthentication] @swagger_auto_schema(manual_parameters=[authorization]) def post(self, request, notification_id): # mark single notification as read class MarkAllAsReadView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = [CustomJWTAuthentication, SessionAuthentication] @swagger_auto_schema(manual_parameters=[authorization]) def post(self, request): #mark all notifications as read and here is my urls.py routing: router = routers.DefaultRouter(trailing_slash=False) router.register('notifications', NotificationAPI, basename='notifications') urlpatterns = [ path('', include(router.urls)), # notifications path('notifications/mark-as-read/<int:notification_id>', MarkAsReadView.as_view(), name='mark-as-read'), path('notifications/mark-all-as-read', MarkAllAsReadView.as_view(), name='mark-all-as-read'), ] Currently whenever i call mark-as-read it work find, but when i try to call mark-all-as-read api it always return the following error: { "detail": "Method \"POST\" not allowed." } I checked and it seem like the notification modelviewset routing messing up the other ApiView routes. I checked by commenting out the ModelViewSet out and the mark-all-as-read now work. Why is this happening? shouldn't routing be separate by name and basename ? Why it's when i call mark-all-as-read it go into the ModelViewSet route, but the mark-as-read work normally? -
Query data linked via Foreign key
I have 2 models linked 'Project' and 'Event'. Event has an FK to Project I want to return all events that are related only to the project. I have a basic view that returns the specific project and im trying to include the event list within that view. def show_project_details(request,project_id): today = now().date() project = Project.objects.get(pk=project_id) events = Event.objects.event_list = Event.objects.filter(event_date__gte=today).order_by('event_date') events_list = Event.objects.get(project_name_id=project_id) form = ProjectForm(request.POST or None, instance=project) return render(request, 'pages/project_details.html', {"project": project, "form": form, "events": events, 'events_list':events_list}) but it returns Event matching query does not exist. Any ideas? -
Django choice field(dropdown) restrict according to user type for multiuser type
I have multi user types in my django app where the user can change the status of something usertype a has options to perform create a task,close(choice fields) while usertype b has option to accept the task created by usertype a and mark finish. how do i restrict them in the form according to the user type when the usertype a clicks on form he should see only close under dropdown whereas the usertype b has to see only accept and finish option in dropdown. models.py class todo(models.Model): title = models.CharField(max_length=200) info = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( (0,opened), ('1','Accepted'), ('2','Completed'), ('3','finish') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,default = 'Open') forms.py class CreateForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'info') class EditForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'info','status') -
Django, Python: Can't filter products with passing values true the get request and order the products
I'm trying to filter some products and order the filtered products by price ascending and descending. This is my code in the view: def is_valid_queryparam(param): return param != '' and param is not None def filter(request): if request.GET: price_min = request.GET.get('priceMin') price_max = request.GET.get('priceMax') sort_by = request.GET.get("sort", "l2h") if is_valid_queryparam(price_min): if sort_by == "l2h": products = Product.objects.filter(price__gte=price_min).order_by('price') elif sort_by == "h2l": products = Product.objects.filter(price__gte=price_min).order_by('-price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() if is_valid_queryparam(price_max): if sort_by == "l2h": products = Product.objects.filter(price__lte=price_max).order_by('price') elif sort_by == "h2l": products = Product.objects.filter(price__lte=price_max).order_by('-price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() else: products = Product.objects.all().order_by('price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() context={ 'products': paged_products, 'product_count': product_count, } return render(request, 'store.html', context) If I try to filter based on the min and max price it works, but when I'm trying to sort or if there is no filter apply I get this UnboundLocalError: UnboundLocalError at /store/ local variable 'paged_products' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/store/?sort=h2l Django Version: 3.1 Exception Type: UnboundLocalError Exception Value: local variable 'paged_products' referenced before assignment Exception Location: C:\Users\store\views.py, line 299, in filter … -
Duplication of id values in another column in same table django
I am working on one python(django framework) project in which i have one user model which has 1000 users. I want to make one another column named priority id and need to put default id values in that priority id column accordingly (you can see it below). id username email priority_id 1 abc abc@gmail.com 1 2 xyz xyz@gmail.com 2 ofcourse i can do it manually but for 1000 users it is time consuming. how do i change models.py or admin.py or something else to achieve this?