Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ulr does not accept query string
I have a view in Django that redirects a user to some url with aditional query string: return redirect('search/?print_id='+str(pk)) In my urls.py, the url pattern looks like this: path('search/', views.search, name='search'), And the problem is when Django tries to redirect, I get the following error: Reverse for 'search/?print_id=36' not found. 'search/?print_id=36' is not a valid view function or pattern name. How can I modify the url pattern to accept a query string? -
Django PDF admin
I tried to find a solution like Export django model as pdf from admin model to add PDF from the admin page in the specific object(articles) and display it in these objects and also be able to download them Thanks!!! -
when creating django project via docker container it says sh: django-admin: not found
I created a docker python image on top of alpine the problem is that when I want to start a django app it can not find django and it is right bcz when I type pip list, it does not have django and other packages. ps: when creating the images it shows that it is collecting django and other packages this is my Dockerfile: FROM python:3.9-alpine3.13 LABEL maintainer="siavash" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH = "/py/bin:$PATH" USER django-user and this is docker-compose.yml version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" and this is the command that I use: docker-compose run --rm app sh -c "django-admin startproject app . " BTW the image is created successfully -
Posts are not showing on Djangohomepage while adding pagination in posts and categories
I did mistake somewhere and i didn't get it. before pagination my allposts and categories were working properly. after doing pagination my all previous posts are not displaying. I am sharing my codes so plz help me to solve it. views.py: from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from blog.models import Post from blog.models import Category from .forms import ContactForm from django.shortcuts import get_object_or_404 from django.views.generic.list import ListView #from django.views import generic from django.core.paginator import Paginator from django.views import View # Create your views here. ''' # this is my older working code before pagination def allpost(request): #post = Post.objects.all() post = Post.objects.all().order_by('-public_date') # 'public_date' taken from 'ordering = ['-public_date']' from class meta in models.py return render(request,'posts.html',{'posts':post}) ''' def allpost(request): PostData = Post.objects.all().order_by('-public_date') paginator = Paginator(PostData, 5) page_number = request.GET.get('page') PostDataFinal = paginator.get_page(page_number) totalpage = PostDataFinal.paginator.num_pages data = { #'Post': PostDataFinal, 'PostData': PostDataFinal, 'lastpage': totalpage, 'totalpagelist': [n + 1 for n in range(totalpage)] } return render(request, 'posts.html', data) def CategoryView(request, page): # here cats is same which mentioned in dynamic url. category_posts = Post.objects.filter(category__title=cats) paginator = Paginator(article_list, 2) page_number = request.GET.get('page') totalpages = paginator.get_page(page) context = { 'category_posts':category_posts, 'lastpage':totalpages, 'articlespageslist':[n + 1 for n in range(totalpages)] } … -
Ensuring uniqueness across multiple models Django
I have three models: Account, Employee and Company. An account can be of the type employee or company and a OneToOne Field relates an account to either an employee or company record. See models below: class Account(auth_models.AbstractBaseUser): username = models.CharField(max_length=40, unique=True) ACCOUNT_TYPE_CHOICES = ( ("company", "Company"), ("employee", "Employee"), ) account_type = models.CharField( choices=ACCOUNT_TYPE_CHOICES, default="EMPLOYEE", blank=False, null=False, max_length=10, ) date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ["account_type"] I then have the Company model: class Company(models.Model): user = models.OneToOneField(Account, on_delete=models.CASCADE, unique=True) name = models.CharField(max_length=75, blank=False, null=False, unique=True) Then I have the Employee model, where an Employee is also related to the company it is employed by: class Employee(models.Model): user = models.OneToOneField(Account, on_delete=models.CASCADE, unique=True) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) date_of_birth = models.DateField(null=False, blank=False) employer = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="employees" ) employment_start_date = models.DateField(null=False, blank=False) employment_end_date = models.DateField(blank=True, null=True) I want to make sure usernames are unique within the company, but not unique within the whole web app. So there can be multiple users with the same username, but not within the same company. For example: Suppose a user created an account with the username John Smith with the company … -
Django,duration calculation between 2 fields using timestamp
I have this model table. In this table,in stay column ,I have fields as stay and on move I need to calculate whole time taken duaration for consecutive stays and on_move . my function for stay column field value updates : def mark_stay_location(): if TestLocation.objects.filter(processed=None): k = TestLocation.objects.filter(processed=None).order_by("timestamp") p = len(k) for i in range(p - 1): rowpairs = k[i : i + 2] lat1 = rowpairs[0].latitude lat2 = rowpairs[1].latitude long1 = rowpairs[0].longitude long2 = rowpairs[1].longitude lat = abs(lat2 - lat1) long = abs(long2 - long1) earth_radius = 6373.0 a = sin(lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(long / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = earth_radius * c * 1000 for rowpair in rowpairs: row_id = rowpair.id po = TestLocation.objects.filter(id=row_id) if lat < 0.0009 or long < 0.0009: po.update(stay="stay") po.update(processed=True) else: po.update(stay="on_move") po.update(processed=True) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND) my approach was adding empty list before i range for loop and append timestamps into it based on if condition take first and last items from list and get difference in minutes and save that duration in last stay field before on_move field.same process goes to on_move field time duaration calculation. -
Why textarea doesnt send data with this form?
I have a form that looks like I am trying to add a product. The description of which will be entered through this form. But my textarea dont send data to product html: <div class="col-12"> <div class="mb-2"> <label class="form-label">Текст новости</label> <div id="blog-editor-wrapper"> <div id="blog-editor-container"> <div class="editor"> <textarea name="text" class="form-control" id="text" rows="3" required>TEXT</textarea> </div> </div> </div> </div> </div> vievs: def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.preview=request.POST.get("preview") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() models: text = models.TextField('Текст статьи') -
Django: error trying to validate an email verification otp
I'm sending an email to the user on register and getting the otp together with the email, I have a separate verify model that looks like below the error I'm facing is {"message": "This OTP is invalid"} which has something to do with peace of code in the verifyEmail view(down below) class Verify(models.Model): email = models.EmailField( _("Email"), max_length=254, unique=True, default=None, blank=True, null=True) otp = IntegerRangeField( min_value=111111, max_value=999999, blank=True, null=True) created_at = models.DateTimeField( _("created at"), auto_now=False, auto_now_add=True, blank=False) expires_at = models.DateTimeField(null=True) def __str__(self) -> str: return self.email how I'm sending the email def send_opt_email(email, firstname, lastname): otp = random.randint(100000, 999999) subject = 'Email verification' message = 'Email verification' html_message = loader.render_to_string( 'email_verify.html', { 'firstname': firstname, 'lastname': lastname, 'otp': otp, } ) email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [ email], fail_silently=True, html_message=html_message) otp = Verify.objects.create( email=email, otp=otp, created_at=datetime.now(), expires_at=datetime.now() + timedelta(minutes=30) ) otp.save() this is the view I use to validate the otp class Verify_Email(APIView): """ Verify registered emails """ def post(self, request): try: data = request.data serializer = VerifySerializerBase(data=data) if serializer.is_valid(): email = serializer.data['email'] otp = serializer.data['otp'] verify = Verify.objects.get(email=email) user = User.objects.get(email=email) try: if user.is_active: return Response({ 'message': "This email has already been verified" }, status=status.HTTP_400_BAD_REQUEST) elif verify: print(verify.email) print(verify.otp) … -
Please resolve PS C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts> python Potentiostat_GUI.py
PS C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts> python Potentiostat_GUI.py Measurement frequency: 500.02083420142503 Hz Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Avinash\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_GUI.py", line 228, in Send_CV_Settings self.user.set_Scan_rate(_scan_rate) File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_userinput.py", line 46, in set_Scan_rate self.comm.usb_write(scan_rate_formatted) # Send command File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_communication.py", line 76, in usb_write self.ep_out.write(message) AttributeError: 'NoneType' object has no attribute 'write' Plot title is stored. Plot legend is stored. Cyclic Voltammetry initialization has started. Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Avinash\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_GUI.py", line 273, in Start_CV_scan self.user.run_CyclicVoltammetry() File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_userinput.py", line 113, in run_CyclicVoltammetry self.comm.usb_write("R") File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_communication.py", line 76, in usb_write self.ep_out.write(message) AttributeError: 'NoneType' object has no attribute 'write' -
Apple M1 run Django display symbol not found in flat namespace '_PQbackendPID'
I am use django to build the project, when I run python manage.py makemigrations it get the error message: Traceback (most recent call last): File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/psycopg2/_psycopg.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_PQbackendPID' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/mingzhe/Desktop/webapp/electric/electric/manage.py", line 22, in <module> main() File "/Users/mingzhe/Desktop/webapp/electric/electric/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/db/models/base.py", line 141, in __new__ new_class.add_to_class("_meta", Options(meta, … -
Django/Wagtail Type error 'ModelBase' object is not iterable
I have a project with wagtail. I have created a custom model Admin named sorting. I want to show this model's data in API. Here is the view in the database Here is models.py from django.db import models from wagtail.models import Page, Orderable from modelcluster.fields import ParentalKey from blog.models import * from wagtail.models import Page from wagtail.admin.panels import PageChooserPanel, FieldPanel, InlinePanel from django.utils.translation import gettext_lazy as _ from modelcluster.models import ClusterableModel from modelcluster.fields import ParentalManyToManyField class IDChoice(models.IntegerChoices): Featured1 = 0, _('Featured1') Featured2 = 1, _('Featured2') Featured3 = 2, _('Featured3') Featured4 = 3, _('Featured4') Featured5 = 4, _('Featured5') class Featured(ClusterableModel): featured_name = models.IntegerField(default=IDChoice.Featured1,choices=IDChoice.choices, blank=True, null=False, help_text='Featured ID', unique=True) panels = [ InlinePanel('featured_pages', label="Featured pages"), FieldPanel('featured_name'), ] class FeaturedPages(Orderable, models.Model): """ Orderable helper class, and what amounts to a ForeignKey link to the model we want to add featured pages to (Featured) """ featured_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) featured_item = ParentalKey( Featured, related_name='featured_pages', null=True, on_delete=models.CASCADE, ) panels = [ FieldPanel('featured_page'), ] def __str__(self): """String repr of this class.""" return self.featured_page class Meta: # noqa verbose_name = "Featured" verbose_name_plural = "Featured Stories" admin.py from .models import * from wagtail.contrib.modeladmin.options import (ModelAdmin, modeladmin_register,) class SortingAdmin(ModelAdmin): model = Featured menu_lebel= "Sorting" … -
Displaying the history of the child object in the history of the parent object in Django admin
I have a problem in showing a child object in parent history in django admin , as you can see in following screenshot when I create or make a change in child object(comment) from inlines it doesn't display in parent object(ticket) history . This mode is only for the mode where I use inlines, if I create an object separately through the child model itself, it will not even be displayed as an empty space. I would be very grateful if somebody can tell me how I can display child history in parent history, for example I want to display what happened to child (comment) in blank spaces. here is my code in admin: @admin.register(models.Ticket) class TicketAdmin(SimpleHistoryAdmin): actions = ['change_status_to_close'] autocomplete_fields = ['member'] list_display = ['id','owner','title','create_time','last_update','status','comments_count','history'] list_select_related = ['member'] list_editable = ['status'] list_filter = ['status',('create_time',DateTimeRangeFilter), ('last_update',DateTimeRangeFilter)] list_per_page = 20 history_list_display = ['changed_fields_with_values','status'] search_fields = ['id'] sortable_by = ['create_time','last_update','id','status'] def changed_fields_with_values(self, obj): fields = "" if obj.prev_record: delta = obj.diff_against(obj.prev_record) for change in delta.changes: fields += str("{} changed from {} to {}".format(change.field, change.old, change.new)) return fields return None @admin.display() def history(self,ticket:models.Ticket): url = reverse('admin:ticketing_ticket_history',args=[str(ticket.id)]) return format_html('<a href="{}">History</a>', url) -
Run a python function depends on the checkbox
I'm working on a python project and I want to call a function if a checkbox was checked. For expample if the yes checkbox was checked the first function will be called. I made this code, but it always calls the second function even if I checked the yes checkbox. I don't know what the issue. Any help is highly appreciated. this is my html : <input type="checkbox" id="vehicle1" name="mycheckboxname" value="yes"> <label for="vehicle1"> Without comments</label><br> <input type="checkbox" id="vehicle2" name="mycheckboxname" value="no"> <label for="vehicle2"> With comments</label><br> And this is my view.py def datatable_view(request): if request.method =='POST': form = Scraping(request.POST) if form.is_valid(): mylist=request.POST.getlist('mycheckboxname') if 'yes' in mylist: subject=form.cleaned_data['subject'] scrap(subject) client = pymongo.MongoClient("mongodb://localhost:27017/") db= client["db2"] col = db[subject] products = col.find() context = {'products' : products} return render(request,'datatable.html', context) else: subject=form.cleaned_data['subject'] hello(subject) client = pymongo.MongoClient("mongodb://localhost:27017/") # use variable names for db and collection reference db= client["db2"] col = db[subject] products = col.find() context = {'products' : products} #open datatable html and display all the data from database return render(request,'datatable.html', context) return -
Cloudflare Server Error 500 - success_fraction - mobile connection to server API error
After enabling Cloudflare, everything seems to work fine. I notice when I am on WIFI (my mobile app), I can use my server API without problems. However, when I on mobile data (4G), my mobile app (i'ved also tested directly with API), it will return 500 error. Here is the following error: <h1>Server Error (500)</h1> Response headers alt-svc: h3=":443"; ma=86400,h3-29=":443"; ma=86400 cf-cache-status: DYNAMIC cf-ray: 74968a18ee948986-SIN content-language: en content-type: text/html date: Mon,12 Sep 2022 06:20:49 GMT nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800} report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=XqpSLNdG070p90inA%2Fyz8fGLCaFJd8Ok0Q1LIX1DnZ8f1TB91QxK7C0akJOAxzWikVPGZ1%2BgGZplkOp7fo7Cx8rQDftwF6e%2FE9ZeoRHVrh6d%2BN9XidYUuwBFeAVsp5dmxQt1HrjXGxqY"}],"group":"cf-nel","max_age":604800} server: cloudflare vary: Origin,Accept-Language,Cookie x-frame-options: SAMEORIGIN How can I solve this ? (FYI, I'ved not enabled any WAF firewall rules at all) -
how can i import a class Product from model.py in Shop app to the cart.py in the Cart pp
File "C:\Users\KARIM\Desktop\DjangoShop\online\Cart\cart.py", line 4, in from ..Shop.models import Product ImportError: attempted relative import beyond top-level package -
How to merge guest cart item and user cart Django?
I am trying to merge guest cart (session cart) items and existing user cart. if cart items repeating increase quantity else, create a new cart item. In my case user already have a cart. in it three products [<CartItem: The Book Thief>, <CartItem: Sapiens: a Brief History of Human Kind>, <CartItem: The Forty Rules of Love>] then the user logged out and add some products [<CartItem: The Alchemist>, <CartItem: Sapiens: a Brief History of Human Kind>] , then when he login again, the repeating product should add quantity, not as a repeating product. and the new product should show as new product in the cart. but my code results always repeating product in the cart? def user_login(request): if request.user.is_authenticated : return redirect('home') else: if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user= authenticate(email =email, password = password) if user is not None: try: cart = Cart.objects.get(cart_id = _cart_id(request)) is_cart_item_exists = CartItem.objects.filter(cart=cart).exists() if is_cart_item_exists: cart_items = CartItem.objects.filter(cart=cart) new_cart_items = [] for cart_item in cart_items: item = cart_item new_cart_items.append(item) print(new_cart_items) cart_items = CartItem.objects.filter(user=user) existing_cart_items = [] id =[] for cart_item in cart_items: item = cart_item existing_cart_items.append(item) id.append(cart_item.id) print(existing_cart_items) print(id) for new_cart_item in new_cart_items: print(new_cart_item) if new_cart_item in existing_cart_items: #i think … -
How do I label fields on a Django form?
I'm trying to figure out how to label my Django form fields- at the moment I'm unable to change them. I have tried amending the field names and adding labels within models.py, but it throws an error, I'm not sure where to add them. models.py: from django.db import models from django.contrib.auth.models import User class Stats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"You currently weigh {self.weight}, {self.user}" views.py: class UpdateHealth(View): def get(self, request, *args, **kwargs): stats = Stats update_form = StatUpdateForm context = { 'stats': stats, "update_form": update_form, 'user': stats.user, 'weight': stats.weight, 'date': stats.date, } return render(request, 'health_hub_update.html', context) def post(self, request, *args, **kwargs): stats = Stats update_form = StatUpdateForm(data=request.POST) context = { 'stats': stats, "update_form": update_form, 'user': stats.user, 'weight': stats.weight, 'date': stats.date, 'run time': stats.run_time, 'run distance': stats.run_distance } if update_form.is_valid(): update_form.save() return render(request, 'health_hub_update.html', context) forms.py: class StatUpdateForm(forms.ModelForm): class Meta: model = Stats fields = ('user', 'weight', 'run_distance', 'run_time') Any help would be appreciated! -
python3.10 RuntimeError populate() isn't reentrant
While upgrading it from python 3.6 (working file) to 3.10.4, I encounter the following error. File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/local/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant Observations: The code works file outside the docker and throws the error only in the container. -
Django ORM: Perform conditional `order_by`
Say one has this simple model: from django.db import models class Foo(models.Model): n = models.IntegerField() In SQL you can perform an order by with a condition e.g. select * from foo orber by n=7, n=17, n=3, n This will sort the rows by first if n is 7, then if n is 14, then if n is 3, and then finally by n ascending. How does one do the same with the Django ORM? It is not covered in their order_by docs. -
Connection reset by peer celery
When i create a long term tasks(1-2 days) some of them are run successfully, but some raises Connection Reset by peer error(104). For example tasks run at 11:30 failed(but some are successful), but tasks run at 12:00 or before 11:30 are successful. settings.py DATABASES['default']['CONN_MAX_AGE'] = 0 if REDIS_PRIMARY_URL: CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", REDIS_PRIMARY_URL) else: CELERY_BROKER_URL = _env_get_required("CELERY_BROKER_URL") # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_backend CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_WORKER_MAX_TASKS_PER_CHILD=500 # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-accept_content CELERY_ACCEPT_CONTENT = ["json"] # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-task_serializer CELERY_TASK_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_serializer CELERY_RESULT_SERIALIZER = "json" # http://docs.celeryproject.org/en/latest/userguide/configuration.html#beat-scheduler CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_ACKS_LATE = True How I run scheduler and worker on aws using containers ["celery","--app=app.celery_app","beat","--loglevel=INFO"] - start scheduler ["celery","--app=app.celery_app","worker","--loglevel=DEBUG","-n worker.%%h","--without-gossip","--without-mingle","--without-heartbeat","-Ofair","--pool=solo"] - start worker Celery version 5.2 -
Django couldn't find "django-filter" or "django-cors-headers" when I use Pantsbuild
I configured Pantsbuild for our Django projects, and everything worked neatly. Here my BUILD file: python_requirements( name="reqs", ) python_sources( name="lib", dependencies=[ ":reqs", ], ) pex_binary( name="manage", entry_point="manage.py", restartable=True, ) but when I added "django-filter", I faced an error: Traceback (most recent call last): File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/home/xurvan/monorepo/jango/manage.py", line 8, in <module> import django_filters ModuleNotFoundError: No module named 'django_filters' my manage.py file is like this: #!/usr/bin/env python import os import sys import django_filters def main(): os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'monorepo.jango.app.settings', ) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) if __name__ == '__main__': print(django_filters.__version__) main() The interesting point is that print(django_filters.__version__) works. And I can see the version correctly but then the error occurs. I also installed Django Rest Framework, and it works fine. But I have the same problem with "django-cors-headers". I don't understand the difference. # pip freeze django==4.1.1 djangorestframework==3.13.1 django-cors-headers==3.13.0 django-filter==22.1 -
Could not parse the remainder: '%if context %' from '%if context %' [duplicate]
This is my views.py : from django.shortcuts import render from django.http import HttpResponse posts= [ { 'author' : 'sahil tariq', 'title' :'Blog post 1', 'content': 'First blog post', 'date' : '12 sep , 2022' }, { 'author' : 'Hanan ', 'title' :'Blog post 2', 'content': 'Second blog post', 'date' : '13 sep , 2022' } ] def home(request): context = { 'posts': posts } return render(request, 'blog/home.html' , context) def about(request): context = { 'title' : 'About' } return render(request, 'blog/about.html', context) this is my home.html: <!DOCTYPE html> <html> <head> {{% if title %}} <title>Django Blog - {{ title }}</title> {{% else %}} <title>Django Blog</title> {{% endif %}} </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p> By {{ post.author }} on {{ post.date }}</p> <p> {{post.content}}</p> {% endfor %} </body> </html> So what I am trying to do is display the page title if there is one title present in the jinja if statement but it shows me an error when I try to run the if statement in home.html. -
django- login issue with AbstractBaseUser model
I've created the custom User model with AbstractBaseUser model. The creation of user works fine and i have checked on admin page. But the problem is... when I try to log-in existing users from the custom User model, the username seem to validate from the database, but it doesn't seem to be able to bring or validate the password from the database. here are my codes from my project. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, UserManager # Create your models here. class AccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("반드시 이메일 주소가 있어야 합니다.") if not username: raise ValueError("아이디는 반드시 있어야 합니다.") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Member(AbstractBaseUser): MALE = 'M' FEMALE = 'F' GENDER_CHOICE = [ (MALE, '남성'), (FEMALE, '여성'), ] YES = '동의' NO = '미동의' SMS_CHOICE = [ (YES, '동의'), (NO, '미동의'), ] FOREIGNER = '외국인' NATIVE = '내국인' FOREIGN_CHECK = [ (FOREIGNER, '외국인'), (NATIVE, '한국인'), ] no = models.CharField(verbose_name="스카이패스 회원번호", max_length=10, unique=True) username = models.CharField(verbose_name="회원 아이디", max_length=20, unique=True ) … -
how to check if object exist before adding in django api view
I have a favorite list but for course,user can add courses those like to see in future,I want to check course exist in list or not before adding it,if exist tell it exist before if not add it to list class AddtoMyCoursesView(viewsets.GenericViewSet): serializer_class = MyCoursesListSerializer def get_queryset(self, *args, **kwargs): pk = self.request.POST.get('pk') user = self.request.user print(user) courses = MyCoursesList.objects.filter(user=user.pk) print(courses) for course in courses: print(course) try: return MyCoursesList.objects.get_or_create(my_courses=course, id=pk) except: return Response("Item already exists", status.HTTP_400_BAD_REQUEST) model class MyCoursesList(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True) courses = models.ForeignKey(Courses, on_delete=models.CASCADE, blank=True,related_name='my_courses') added_date = models.DateTimeField(auto_now_add=True) teacher = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING, default=1) class MyCoursesListSerializer(serializers.ModelSerializer): class Meta: model = MyCoursesList fields = ['id', 'user', 'courses', 'added_date', 'teacher'] -
how to do search with pagination using Django
You can easily understand which functionality i'm trying to add this pagination Using option, i want to show limited data like if user select 10 then number of data should display 10 Next, if user enter page number 2 then it go to page number 2 form.html <form class="form-inline" method="GET" action="{% url 'bookings:cancelled_bookings_list' %}"> {% csrf_token %} <select class="form-control w-50" data-selected="Data" name="no_of_data"> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> <br> <div class="input-group"> <input type="text" class="form-control w-25" placeholder="Enter Page No" name="page_no"> <div class="input-group-append"> <button class="btn btn-primary" type="submit" id="button-addon2">Go</button> </div> </div> </form> views.py page = request.GET.get('page', 1) paginator = Paginator(bookings, PAGE_SIZE) try: bookings = paginator.page(page) except PageNotAnInteger: bookings = paginator.page(1) except EmptyPage: bookings = paginator.page(paginator.num_pages) if request.method == "GET": no_of_data = request.GET.get('no_of_data') page_no = request.GET.get("page_no") paginate_by = no_of_data