Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django permissions are present but has_perm() returns False
I'm working on the permissions on a Django 4.1 application. All these permissions are given by groups. First permission first problem: Permission codename: can_see_all_images appname for the permission: dating group having this permission: X-Gold As you can see on the screenshot it seems that all the informations are correct: First line: User is in the group Second line, the group has the permission Third line: The permission has the good codename but line4: the user doesn't have the perm. I restarted the server disconnected the user and reconnected it, nothing changed. Note that if I give the permission directly to the user, it doesn't work. So I guess the problem does not come from the group. Any idea? Here is how the permission is created in the model: permissions = [('can_see_all_images', _('Can see all images'))] Thanks in advance -
Trying to get and update or create model from json in Django
Im trying to get and update or create object in model from json list of dicts but i got an error: "TypeError: Tried to update field authentication.CounterParty.GUID with a model instance, <CounterParty: CounterParty object (3)>. Use a value compatible with UUIDField. " models.py class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150) customer = models.BooleanField(default=False) contractor = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Counter Party' tasks.py def create_counter_party(): response = [ { "CounterpartyGUID": "e58ed763-928c-4155-bee9-fdbaaadc15f3", "CounterpartyName": "name1", "Customer": False, "Contractor": True }, { "CounterpartyGUID": "123e4567-e89b-42d3-a456-556642440000", "CounterpartyName": "name2", "Customer": False, "Contractor": False }, ] rep = response for item in rep: try: counter_party = CounterParty.objects.get(GUID=item['CounterpartyGUID']) updated_counter_party = CounterParty.objects.update(GUID=counter_party, name=item['CounterpartyName'], customer=item['Customer'], contractor=item['Contractor']) updated_counter_party.save() except CounterParty.DoesNotExist: counter_party = CounterParty.objects.create(GUID=item['CounterpartyGUID'], name=item['CounterpartyName'], customer=item['Customer'], contractor=item['Contractor']) counter_party.save() errors: [2023-01-28 15:29:31,894: ERROR/ForkPoolWorker-8] Task authentication.tasks.create_counter_party[a86333d9-e039-479e-8d35-37fa6b17dbfa] raised unexpected: TypeError('Tried to update field authentication.CounterParty.GUID with a model instance, <CounterParty: CounterParty object (3)>. Use a value compatible with UUIDField.') Traceback (most recent call last): File "/home/zesshi/.local/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/home/zesshi/.local/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/mnt/c/Users/Shalltear/Desktop/Python/unica_django/authentication/tasks.py", line 27, in create_counter_party counter_party = CounterParty.objects.update(GUID=counter_party, name=item['CounterpartyName'], File "/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/query.py", line 1191, in update rows = … -
Reference a custom user model in views.py
I am trying to save to a model named Blog from inside Django's views.py file. This Blog model is itself linked to the custom user model that I created. How exactly do I do that? Below are the models.py file (custom user model is here) models.py file (Blog model created here - in another Django app) views.py file where I try to save to the Blog model. How do I reference the user here? Please excuse the noob-ness of this question. I'm just starting out :) Inside models.py, I have a custom user model: class UserExtended(AbstractUser): is_email_verified = models.BooleanField(default=False) company = models.CharField(null=True, blank=True, max_length=255) position = models.CharField(null=True, blank=True, max_length=255) email = models.EmailField(unique=True) I also created a model for blog articles in models.py: class Blog(models.Model): title = models.CharField(max_length=200) blogSubject = models.CharField(null=True, blank=True, max_length=200) keywords = models.CharField(null=True, blank=True, max_length=300) audience = models.CharField(null=True, blank=True, max_length=200) # connection to custom user model profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) In views.py, I am trying to save to the Blog model: def saveBlogTopic(request, blogTopic): # create a Blog model instance blog = Blog.objects.create( title = blogTopic blogSubject = request.POST['blogSubject'] keywords = request.session['keywords'] audience = request.session['audience'] profile = request.user ### ???????? ### ) I have no idea how to … -
static files not loading when DEBUG is False
I set my DEBUG variable to False in setting.py and deployed my project in cpanel,used collectstatic command but static files not loading. setting.py STATIC_URL = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [( BASE_DIR / 'static/') ] MEDIA_ROOT = os.path.join(BASE_DIR, "static_cdn", "media_root") else: STATIC_ROOT = "/home/smartsbi/public_html/static" MEDIA_ROOT = "/home/smartsbi/public_html/media" urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('contact_us.urls')), path('', include('service.urls')), ] if settings.DEBUG: # add root static files urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # add media static files urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to fix python: can't open file '//manage.py': [Errno 2] No such file or directory in Django
How to fix Remainder of file ignored python: can't open file '//manage.py': [Errno 2] No such file or directory when use command docker-compose up This is all my code, and I've also attached an image file. dockerfile files FROM python:3.10 ENV PYTHONUNBUFFERED 1 COPY requirements.txt . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD = mariadb - MYSQL_DATABASE = mariadb - MYSQL_USER = mariadb - MYSQL_PASSWORD = mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 3306:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: context: . dockerfile: Dockerfile restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:3306/mariadb ports: - "8000:8000" depends_on: - db adminer: image: adminer restart: always ports: - 8080:8080 depends_on: - db volumes: mysqldata: setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mariadb', 'USER': 'mariadb', 'PASSWORD': 'mariadb', 'HOST': '127.0.0.1', 'PORT': 3306, } } file image Django -
django.db.utils.OperationalError: no such column: blog_follow.followed_me_id
I tried delete migration file and python manage.py makemigrations [appname]. However, this is not solve my problem models.py class User(AbstractUser): followers = models.ManyToManyField("Follow",blank=True,related_name="follow_user") class Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.CharField(max_length=500,null=True,blank=True) timestamp = models.DateField(auto_now_add=True) like = models.ManyToManyField(User,blank=True,related_name="liked_user") @property def number_of_likes(self): return self.like.all().count(), def __str__(self) -> str: return self.post class Follow(models.Model): followed_me = models.ForeignKey(User, on_delete=models.CASCADE,related_name="followed_me", default=None) followed_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followed_by", default=None) def __str__(self) -> str: return f"{self.followed_by.username} start following {self.followed_me.username} " views.py def profile(request,username): my_account = get_object_or_404(User,username=username) my_post = Post.objects.filter(user=my_account).order_by("id") following = False if request.user.is_authenticated: followers = my_account.followers.filter(followed_by_id=request.user.id) if followers.exists(): following = True return render(request,"blog/profile.html",{ "posts":my_post, "post_count": my_post.count(), }) def follow(request,username): all_user = User.objects.all() my_account = get_object_or_404(User,username=username) my_post = Post.objects.filter(user=my_account).order_by("id") following = False if request.user.is_authenticated: followers = my_account.followers.filter(followed_by_id=request.user.id) if followers.exists(): following = True return render(request,"blog/following.html",{ "al_us": all_user, "following":following }) def follow_or_unfollow_user(request,user_id): followed = get_object_or_404(User,id=user_id) followed_by = get_object_or_404(User,id=request.user.id) follow,created =Follow.objects.get_or_create(followed_me=followed,followed_by=followed_by) if created: followed.followers.add(follow) else: followed.followers.remove(follow) follow.delete() return redirect('index') urls.py path("profile/<str:username>",views.profile,name="profile"), path("follow/<str:username>",views.follow,name="follow"), path("follow_or_unfollow/<int:user_id>",views.follow_or_unfollow_user,name="follow_or_unfollow") profile.html <div>total Post {{post_count}} <span>total follower {{currently_followed}}</span> <span>total following {{following_count}}</span></div> {%for pst in posts%} {%if user.id == pst.user.id%} <div class="post-outer-container"> <div class="post-container"> {{pst.post}} {{pst.user}} {{pst.timestamp}} <a href="{%url 'edit-post' pst.id%}" style="margin-left:15px ;"> Edit</a> <a href="{%url 'delete' pst.id%}" style="margin-left:15px ;"> Delete</a> </div> </div> {%endif%} {%endfor%} {%endblock%} following.html <h1>All user</h1> {%for i … -
django deploy nginx auto log out
I am experiencing an issue with my Django application where I am automatically logged out when trying to access my admin panel. I suspect that the problem may be related to session preservation. To further investigate, I have included my nginx configuration and my Django settings file below. map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } server { listen 80; listen [::]:80; server_name www.khalimbetovulugbek.com khalimbetovulugbek.com; return 301 https://khalimbetovulugbek.com; } server { listen 443 ssl http2; ssl_certificate /etc/nginx/ssl/server.crt; ssl_certificate_key /etc/nginx/ssl/server.key; server_name khalimbetovulugbek.com www.khalimbetovulugbek.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/benku/portfolio/src; } location /media/ { root /home/benku/portfolio/src; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } expires $expires; }``` and is it correct location for media file? seems like my session is not preserved and that is why i am logging out settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Connection to Postgresql server on socket "/var/run/postgresql/.s.PGSQL.5432" failed. OperationalError on railway.app
I deployed my Django app on railway.app recently. After deployment, I tried to login into my app when I was confronted by this OperationalError. The Traceback looks something like this: Environment: Request Method: POST Request URL: http://optimuscore.up.railway.app/ Django Version: 4.0 Python Version: 3.10.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', 'dhule', 'solapur', 'mathfilters', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/opt/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/opt/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/opt/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/opt/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) The above exception (connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? ) was the direct cause of the following exception: File "/opt/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/accounting/account/views.py", line 72, in login print('fm: ', fm) File "/opt/venv/lib/python3.10/site-packages/django/forms/utils.py", line 55, in render context or self.get_context(), File "/opt/venv/lib/python3.10/site-packages/django/forms/forms.py", line … -
How to send data from list to create?
I have a problem, I would like to transfer the appropriate field parameters from one list to the form for creating something else. The names of the fields match but they are not the same in both and I would like to send only those that are the same. Example - I have a list of requests and on this list I have a button next to each record. After press the button i would like to redirect to add customer form where I will have autofill data from list request. What can I do? def add_customer_from_list(request, pk): application = Contact.objects.get(id=pk) #data from Contact list form = CustomerForm(request.POST, instance=application)#to CustomerForm if form.is_valid(): name = form.cleaned_data['name'] #same email = form.cleaned_data['email'] #same phone_number = form.cleaned_data['phone_number']#same address = form.cleaned_data['address'] dog_name = form.cleaned_data['dog_name']#same dog_age = form.cleaned_data['dog_age'] service_type = form.cleaned_data['service_type']#same (multi choice) training_place = form.cleaned_data['training_place'] contact_date = form.cleaned_data['contact_date'] source = form.cleaned_data['source'] status = form.cleaned_data['status'] notes = form.cleaned_data['notes'] customer = Customer(name=name, email=email, phone_number=phone_number, address=address, dog_name=dog_name, dog_age=dog_age, service_type=service_type, training_place=training_place, contact_date=contact_date, source=source, status=status, notes=notes) customer.save() return redirect('xxx') return render(request, 'xxx', {'form': form}) I try do somethin in view and templates -
Add an endpoint for borrowing return
I have this tasks for borrowing books in the library: Implement return Borrowing functionality Make sure you cannot return borrowing twice Add 1 to book inventory on returning Add an endpoint for borrowing books POST: borrowings//return/ - set actual return date (inventory should be made += 1) I can not understand how to make a return endpoint. book/models.py from django.db import models class Book(models.Model): COVER_CHOICES = [("HARD", "Hard cover"), ("SOFT", "Soft cover")] title = models.CharField(max_length=255) authors = models.CharField(max_length=256) cover = models.CharField(max_length=15, choices=COVER_CHOICES) inventory = models.PositiveIntegerField() daily_fee = models.DecimalField(max_digits=7, decimal_places=2) class Meta: ordering = ["title"] def __str__(self): return ( f"'{self.title}' by {self.authors}, " f"cover: {self.cover}, " f"daily fee: {self.daily_fee}, " f"inventory: {self.inventory}" ) def reduce_inventory_book(self): self.inventory -= 1 self.save() def increase_inventory_book(self): self.inventory += 1 self.save() borrowing/models.py from django.conf import settings from django.contrib.auth.models import AbstractUser from django.core.exceptions import ValidationError from django.db import models from book.models import Book class Borrowing(models.Model): borrow_date = models.DateField(auto_now_add=True) expected_return_date = models.DateField() actual_return_date = models.DateField(null=True, blank=True) book = models.ForeignKey(Book, on_delete=models.PROTECT, related_name="borrowings") user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="borrowings" ) @staticmethod def validate_book_inventory(inventory: int, title: str, error_to_raise): if not (inventory > 0): raise error_to_raise( {"book": f"There is currently no book: {title} to borrow"} ) def clean(self): Borrowing.validate_book_inventory( self.book.inventory, self.book.title, ValidationError ) … -
Request Handling at backend (Django)
I have two api endpoints 1- stockpurchases/ || stockpurchases/{id}/ 2- stockpurchases/{id}/stocks/ || stockpurchases/{id}/stocks/{id}/ So if some one want to purchase he should create a stockpurchase first and than add a stock to it and when someone POST stock I plus quantity and amount of stockpurchase. The problem is if some one call POST request consecutively for a loop the amount operation will goes incorrect. I want handle multiple request at the backend. Supose if the server gets consecutive request to perform operation how can i make others request wait till completion of first procedsed. After that second request is processed and so on. StockPurchase Model class StockPurchase(models.Model): qty = models.IntegerField(default=0) amount = models.IntegerField(default=0) Stock Model class Stock(models.Model): stockpurchase = models.ForeignKey("StockPurchase", on_delete=models.CASCADE, related_name='stocks') product = models.ForeignKey("Product", on_delete=models.CASCADE, related_name='stocks') project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name='stocks') rate = models.IntegerField() def save(self, *args, **kwargs): if not self.pk: self.stockpurchase.amount += self.rate self.stockpurchase.qty += 1 self.stockpurchase.save() super().save() So if I Call like this with await no issue async function create() { for (let i = 0; i < 10; i++) { let response = await fetch( "http://localhost:8000/api/stockpurchases/2/stocks/", { method: "POST", body: bodyContent, headers: headersList, } ); } } but if call it without await async function the … -
How to style the validation error list display by changing the error class by overwriting built-in form templates. error_class errorlist ErrorList
I couldn't find an up-to-date answer, so I'll write my own solution based on the Django documentation https://docs.djangoproject.com/en/4.2/ref/forms/api/#how-errors-are-displayed. Explain: I override built-it templates of ErrorList using TemplatesSetting() which refers to the template engine. Now I can change HTML in custom templates. `from django.forms.renderers import TemplatesSetting from django.forms.utils import ErrorList class CustomErrorList(ErrorList): def __init__(self, initlist=None, error_class=None, renderer=None): super().__init__(initlist, error_class="list-group", renderer=TemplatesSetting()) template_name = "forms/errors/default.html" template_name_text = "forms/text.txt" template_name_ul = "forms/errors/ul.html" class OfferForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_class = CustomErrorList class Meta: model = Offer exclude = ['city', 'user', 'is_active', 'count_of_views', 'in_favorites']` settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] in ul.html: {% if errors %}<ul class="list-group">{% for error in errors %}<li class="list-group-item text-white bg-danger">{{ error }}</li>{% endfor %}</ul>{% endif %} -
Unable to reset password in Django
I have an app which allows the user to reset password. I user the django authentification system but everytime I want to send an email I get the error ' 535, b'5.7.8 Username and Password not accepted. '. I have already generated and app password and replace the password in my "settings.py" but I still get this error. -
Sort objects in django admin panel based on a charfield which also have certain characters like $, Euro Symbol, comma, etc.,
In the Django Admin panel, I want a functionality for admin that allows him to Sort the car based on price. Here price is a CharField and contains different characters other than numbers in string format. which makes it difficult to sort. I want to filter the Cars based on price but price is a string and contains characters like $, comma and Euro symbols. I don't understand how to filter this. class MostExpensiveCars(admin.SimpleListFilter): title = _("Most Expensive Cars") parameter_name = "most_expensive_cars" def lookups(self, request, model_admin): return ( ("today", _("Today")), ("yesterday", _("Yesterday")), ("this_week", _("This Week")), ) def queryset(self, request, queryset): if self.value() == "today": # get today's date today = datetime.today().date() # get the most expensive cars sold today queryset = queryset.filter(sold_on=today) if self.value() == "yesterday": # get yesterday's date yesterday = datetime.today().date() - timedelta(days=1) queryset = queryset.filter(sold_on=yesterday) # get the most expensive cars sold yesterday # return queryset if self.value() == "this_week": # get the most expensive cars sold this week seven_days_ago = datetime.today().date() - timedelta(days=7) queryset = queryset.filter(sold_on__gte=seven_days_ago) # TODO: code to filter queryset by price since the price is a string # and contains many characters like $, commas, etc. ........... @admin.register(Car) class CarAdmin(admin.ModelAdmin): list_display = [ … -
Doesn't the parent model's object of "one to one relationship" have "_set" in Django?
I have Person and PersonDetail models below which have one-to-one relationship: class Person(models.Model): name = models.CharField(max_length=20) class PersonDetail(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE) age = models.IntegerField() gender = models.CharField(max_length=20) But, when using persondetail_set of a Person object as shown below: obj = Person.objects.all()[0] print(obj.persondetail_set.all()) # ↑ ↑ Here ↑ ↑ There is the error below: AttributeError: 'Person' object has no attribute 'persondetail_set' So, I changed one-to-one relationship to one-to-many relationship as shown below: class PersonDetail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) # ... Then, there was no error: <QuerySet [<PersonDetail: 32 Male>]> Or, I changed one-to-one relationship to many-to-many relationship as shown below: class PersonDetail(models.Model): person = models.ManyToManyField(Person) # ... Then, there was no error: <QuerySet []> So, doesn't the parent model's object of one-to-one relationship have _set in Django? obj = Person.objects.all()[0] print(obj.persondetail_set.all()) # ↑ ↑ Here ↑ ↑ -
Cannot render values in django template using for loop
So i have a zipped list inside my view and I have passed it into context like this: combined_data = zip(hostnames_list, values, values1, values2, values3, values4, values5) context = {'combined_data': combined_data} return render(request, 'base/snmp-table.html', context) but when i try to render this data into the django template like this, the data is not displayed: <table> <thead> <tr> <th>Hostname</th> <th>Value1</th> <th>Value2</th> <th>Value3</th> <th>Value4</th> <th>Value5</th> <th>Value6</th> </tr> </thead> <tbody> {% for host, val1, val2, val3, val4, val5, val6 in combined_data %} <tr> <td>{{host}}</td> <td>{{val1}}</td> <td>{{val2}}</td> <td>{{val3}}</td> <td>{{val4}}</td> <td>{{val5}}</td> <td>{{val6}}</td> </tr> {% endfor %} </tbody> </table> </table> <script type="text/javascript"> setTimeout(function () { location.reload(); }, 2 * 1000); </script> The lists which are zipped are not empty because when i do this inside my view: for host, val1, val2, val3, val4, val5, val6 in combined_data: print(host, val1, val2, val3, val4, val5, val6) I get the output in my console 10.1.1.1 not found not found not found not found not found not found 10.1.1.2 not found not found not found not found not found not found Note: 'not found' is the value inside list. Any insight please? thank you -
How to get an X from a range (1000, 0) in Django Template when you run through a for loop (0, 1000)?
Actually, I run through a regular loop: {% for post in posts %} And I need here X = 1000 then 999 then 998. {% endfor %} How to do it? Do you have any ideas? I tried: {% with x=1000 %} {% for post in posts %} {{ x|add:"-1" }} {% endfor %} {% endwith %} But it doesn't save that x. It shows 999 each time. -
How to serve two projects on same server one is django and another is django
I have created two projects one is python django and another is on Php as the backend. I want to connect its front end which is on flutter and put it on live .Suggests some ideas on how to do it. Please share some feasible ideas -
Add filtering parameters in drf_yasg Swagger in django-rest-framework Viewsets
I am using django-rest-framework Viewset and i have one list API in that i have to add filtering parameters start_date and end_date in request body in swagger. class SchoolManagementView(ViewSet): def __init__(self, *args, **kwargs): super().__init__(**kwargs) self.payload = {} self.college_list_service = CollegeListService(view=self) @swagger_auto_schema( operation_description="Listing Inward Document", responses={status.HTTP_200_OK: "Success"} ) def list(self, request, *args, **kwargs): self.payload = self.college_list_service.execute(request) return ResponseHandler.success(payload=self.payload) Note: Here i am using all my filter backends in "college_list_service" file -
Is it possible to feed data from a React POST request into a Django form without rendering that form on the frontend?
I am working on a basic login form for a hybrid React/Django web app. I would like to use the built in data-cleaning and validating methods of the Django LoginForm, but our frontend is pure React. Everything works as far as logging in, but I am feeding the raw body data into the authenticate function as shown here. def login_view(request): if request.method == "POST": form_data = json.loads(request.body.decode('utf-8')) user = authenticate(request, email=form_data["username"], password=form_data["password"]) if user == None: request.session["invalid_user"] = 1 logging.warning("Login form contains no user") login(request, user) My question is, is there any way to feed this form_data into the Django native LoginForm when I instantiate it? I would prefer to not recode all of the input validation that Django does already. I've tried instantiating a LoginForm like so: form = LoginForm(data=form_data) And then tried running form.full_clean(), but it doesn't seem to work. Any help would be greatly appreciated, thank you! -
Site downtime becuase of gunicron cpu utilization is 96%
We have djanog application that run with gunicorn. We eware facing site downtime because of high trafic. Gunicorn is utilizng 96 % of the cpu that what cauing the issue. Our system specification: 8 GB ram, 4 cpu How to setup gunicron in such way that it can handle more than 100 request per second ? What are the system specifcation required for handling 100 request per second ? Is gunicorn workers are cpu count ? -
model register but not creating table
on my django application I try to register model , python manage.py makemigrations , migrate works , but no database table found on admin.. `from django.contrib import admin.. << admin.py >> from .models import Product class ProductAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('product_name',)} list_display = ('product_name', 'price', 'stock', 'category', 'modified_date', 'is_available') admin.site.register(Product, ProductAdmin) ` -
Celery executing only one task at a time
I'm running celery on windows through this command celery -A project worker --concurrency=1 --loglevel=info -E -P gevent -Ofair but it only executes one task at a time, even tried to add some configurations import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") app = Celery("django_celery") app.conf.worker_prefetch_multiplier = 1 app.conf.task_acks_late = True app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() I've no idea what I'm doing wrong -
How Django process the post request sent from React? I have extracted the data from the POST request, but how show the data in a web browser?
I'm absolutely new to the field of frontend and backend. I sent a request from React to Django using "POST" and I have extracted data from the request I can print it in the terminal, but how to show the result in web browser from Django (i.e.8000/result/) it seems to use "GET" method but it fails because my data is extracted from POST request. So basicacly, I input a text and submitted to localhost:8000/result, so I want to show the result on this url or redirect to another and send it back to React. I don't know how to achieve this I used a pretty dumb method I save the data of request in tempory json and read the json in another function to render a browser through "GET". I tried to render or redirect to some url pages directly after process the "POST" request, but it apprently fails. views.py @api_view(["GET","POST"]) #class SubmitTextView(View): def post(request): if request.method =="POST": #print(True) text = request.body #print(type(text)) result = json.loads(text)["text"] json_data = json.dumps({"text":result}) #return HttpResponse(json_data, content_type='application/json') #return JsonResponse({"text":result}) #context = {'result':result,'headline':'Result Searched from Wikipedia'} #return render(request, 'my_template.html', context) with open("sample.json", "w") as outfile: outfile.write(json_data) return JsonResponse({"status":"success"}) def upload(request): with open('sample.json', 'r') as openfile: # … -
Django 'STATIC_ROOT' url giving PermissionError
I'm running collectstatic with docker-compose and nginx. When I run the command python manage.py collectstatic, I get a Permission denied error such as this: PermissionError: [Errno 13] Permission denied: '/project/static' I'm trying to link it also with nginx. Trying different combinations it doesn't seem to accept my static files and this error is popping out most of the times. I tried using changing ownership with chown but it tells me I'm not allowed to change ownership, and when adding sudo in before it says sudo: not found (I'm running the scripts through a .sh script file). This is django settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') And this nginx configuration: server { listen ${LISTEN_PORT}; location /static { alias /static/; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Also changing the name of the folder in STATIC_ROOT didn't work. What am I doing wrong?