Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why is there an error while rendering django files
I did or tried, like here https://github.com/kottenator/django-compressor-toolkit and https://gist.github.com/brizandrew/685a588fbefbd64cd95ed9ec4db84848 But after the command "python manage.py compress" comes out this "CommandError: An error occurred during rendering accounts\profile.html: 'utf-8' codec can't decode byte 0xad in position 9: invalid start byte", at the same time, after each command, the name "profile.html" of the html file is different my settings.py COMPRESS_ENABLED = True COMPRESS_CSS_HASHING_METHOD = 'content' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) COMPRESS_FILTERS = { 'css': [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter', 'compressor.filters.template.TemplateFilter' ], 'js': [ 'compressor.filters.jsmin.JSMinFilter', ] } COMPRESS_PRECOMPILERS = ( ('module', 'compressor_toolkit.precompilers.ES6Compiler'), ('text/x-scss', 'compressor_toolkit.precompilers.SCSSCompiler'), ) HTML_MINIFY = True KEEP_COMMENTS_ON_MINIFYING = True COMPRESS_OFFLINE = True my template {% extends 'base-page.html' %} {# Django template #} {% load compress %} {% load static %} {% load pages %} {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static 'accounts/css/base-profile.css' %}"> {% endcompress %} {% compress js %} <script type="module" src="{% static 'accounts/js/base-profile.js' %}"></script> {% endcompress %} my package.json { "name": "mysite", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "type": "module", "author": "", "license": "ISC", "devDependencies": { "autoprefixer": "^10.4.14", "babel-preset-es2015": "^6.24.1", "babelify": "^10.0.0", "browserify": "^17.0.0", "node-sass": "^8.0.0", "postcss-cli": "^10.1.0", "sass": "^1.59.3" }, "dependencies": { "jquery": "^3.6.4" } … -
Difference between ViewSet and GenericViewSet?
I have been a little confused lately with GenericViewSets and ViewSets. It started off by thinking what is the difference between APIView and GenericAPIView. A little search and I found out that APIView uses HTTP verbs(get, put post, etc) as their method names and they have to be explicitly implemented, whereas in GenericAPIView the method names are actions (list, create, destroy, update, etc) which are automatically mapped to the correct method call. But even these HAVE to be implemented. However, we can add mixins on top of GenericAPIView or use generics and then we do not have to implement the methods if they follow a basic CRUD pattern. Declaring just the queryset (get_queryset) and serializer_class(get_serializer) will suffice. My question is if the difference between ViewSets and GenericViewSets is same as APIView and GenericAPIView? Also, what if I want my class to inherit only the GenericViewSets( or GenericAPIView, for that matter), without using any mixins? How would GenericViewSets be any different from ViewSets then? PS. This is the image that got me thinking about everything. -
Using ForeignKey and ManyToManyField in Django model
I'm trying to set up this Django endpoint to create a new post. MODEL class UserPosts (models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='posts_created') text = models.CharField(max_length=300) likes = models.ManyToManyField(User, related_name='posts_liked') timestamp = models.DateTimeField(auto_now_add=True) SERIALIZER class UserPostsSerializer(serializers.ModelSerializer): class Meta: model = UserPosts fields = ['id', 'user', 'text', 'likes', 'timestamp', 'user_id'] depth = 1 user_id = serializers.IntegerField(write_only=True) likes = UserSerializer(read_only=True, many=True) #NOT SURE IF RELEVANT, BUT THE USERSERIALIZER LOOKS LIKE THIS class UserSerializer(serializers.ModelSerializer): class Meta: model = User VIEWS @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def get_all_posts(request): if request.method == 'GET': posts = get_list_or_404(UserPosts) serializer = UserPostsSerializer(posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = UserPostsSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=request.user, user_id=request.user.id) return Response(serializer.data, status=status.HTTP_201_CREATED) If I test the endpoint in Postman, I get a 400 error Bad Request saying "user_id": "this field is required". I've set up ForeignKey fields exactly like this in the past and it worked. But I haven't used a ManyToMany field in this way before. I'm thinking the issue is in my serializer? -
How to return a QuerySet of 2 models via reverse ForeignKey lookup in Django?
I have "Parameter" and "ParameterChoice" models where I define multiple choices for each parameter. The end goal is to have some sort of assessment where I have a list of parameters where each parameter has a specific fixed set of choices available for selection from a dropdown list within the HTML template. I want to somehow pass one or two querysets to the template where I will render a table of all parameters and available choices next to it. Unfortunately, I really struggle to come up with logic in Django on how to achieve this. Ideally, result would look like this: Parameters Choices Param1 ChoiceA ChoiceB ChoiceC Param2 ChoiceY ChoiceZ How can I make this happen without a raw SQL query? Current setup: models.py class Parameter(models.Model): text = models.CharField(blank=False, null=False, max_length=200) class ParameterChoices(models.Model): text = models.CharField(blank=False, null=False, max_length=200) parameter = models.ForeignKey(Parameter, related_name='parameterchoices', on_delete=models.CASCADE, blank=False, null=False) views.py def parameters(request): params = Parameter.objects.all() param_choices = ParameterChoices.objects.all() context = { 'parameters': params, 'parameter_choices': param_choices, } return render(request, 'questionnaire/parameters.html', context) -
Issue: NOT NULL constraint failed
So I'm currently building an online webshop for my school project. In the webshop, the user should be able to submit a review on each product. Tho I'm having issues when trying to submit the review. It gives me this error: NOT NULL constraint failed: Ive been stuck on this for about 15 hours I cant seem to solve it. I would appreciate all the help I can get. Traceback: Traceback (most recent call last): File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: products_reviewrating.user_id) was the direct cause of the following exception: File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/workspace/webster00/products/views.py", line 91, in submit_review newreview.save() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1410, in execute_sql cursor.execute(sql, … -
How to write out an object from a relationship in django
I don't know how to describe this exactly in database jargon. I would like to output an object that is in a relationship with another like this. order__orderitem.product.title models.py class Order(models.Model): status_types = [ ("Ordered", "Ordered"), ("Sent", "Sent"), ("Delivered", "Delivered"), ("Extended", "Extended"), ("Returned", "Returned"), ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order_date = models.DateTimeField() return_date = models.DateTimeField(null=True) status = models.CharField(choices=status_types, default="Ordered", max_length=100) total = models.IntegerField(null=False) payment = models.OneToOneField(Payment, on_delete=models.CASCADE, null=False, blank=False) shipping = models.ForeignKey(Shipping, on_delete=models.CASCADE, null=False, blank=False) first_name = models.CharField(max_length=255, null=False, blank=False) last_name = models.CharField(max_length=255, null=False, blank=False) phone = models.CharField(max_length=12, null=False, blank=False) city = models.CharField(max_length=255, null=False, blank=False, default=None) zip_code = models.CharField(max_length=10, null=False, blank=False, default=None) street = models.CharField(max_length=255, null=False, blank=False, default=None) building_number = models.CharField(max_length=10, null=False, blank=False, default=None) apartment_number = models.CharField(max_length=10, null=True, blank=True, default=None) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) price = models.IntegerField(null=False, blank=False, default=15) debt = models.IntegerField(null=True, default=0) orders.html {% for item in object_list %} {% for it in item__OrderItem %} {{ it.product.title }} {% endfor %} {% endfor %} Is it possible in such a way? -
How to fix Page not found in Django?
I have created a template for menu showing, but when I run my server, I got an error that my page is not found. Any suggestions? from django.urls import path from restaurant import views app_name = 'restaurant' urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name = 'about'), path('menu/<slug:menu_name_slug>/', views.show_menu, name='show_menu'), path('restricted/', views.restricted, name='restricted'), ] Error Message: Using the URLconf defined in WAD_Group_Project.urls, Django tried these URL patterns, in this order: [name='index'] restaurant/ [name='index'] restaurant/ about/ [name='about'] restaurant/ restaurant/menu/<slug:menu_name_slug>/ [name='show_menu'] restaurant/ restricted/ [name='restricted'] admin/ accounts/ ^media/(?P<path>.*)$ The current path, restaurant/menu/, didn't match any of these. -
How to use vuejs with django
I'm trying to use vue (with a cdn) in an html file located in home(the django app)/templates/index.html. I included the cdn in the body, here is the code: <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app">{{ message }}</div> <script> const { createApp } = View createApp({ data() { return { message: 'Hello Vue!' } } }).mount('#app') </script> Nothing is displayed on the page and I have this error in the console: [Vue warn]: Component is missing template or render function. at <App> What's wrong with this code? -
Django-NextJS not rendering webpages properly
I have a Django server which I am trying to integrate NextJS into using the django-nextjs python package. Everything works fine except that when I open the Django server on port 8192, it renders the path to the webpage instead of the actual webpage itself i.e. http://localhot:8192/home renders '/home' in the browser. No HTML tags, no JS, just the string /home. The NextJS server however does not do this: it renders the whole page as expected so I think that this is something to do with django-nextjs and not the NextJS server itself. The strangest thing is that it was working just fine before. I have tried printing the output from django-nextjs and have confirmed that it is either django-nextjs or the NextJS server that is causing the issue. However as previously stated the Next server returns the pages, while Django does not. Any pointers are appreciated :) Files mainserver/asgi.py import os from channels.routing import ( ProtocolTypeRouter, URLRouter, ) from django.core.asgi import get_asgi_application from django_nextjs.proxy import ( NextJSProxyHttpConsumer as NextHttpConsumer, NextJSProxyWebsocketConsumer as NextWebsocketConsumer, ) from django.urls import path, re_path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainserver.settings') http_urls = [ re_path(r'', get_asgi_application()), #re_path(r"^(?:_next|__next|next).*", NextHttpConsumer.as_asgi()), ] websocket_urls = [ path("_next/webpack-hmr", NextWebsocketConsumer.as_asgi()) ] application = ProtocolTypeRouter({ 'http': URLRouter(http_urls), … -
Django view and serializer of manyToMany using through
I have the following structure: Each account has list of stores, and each store has list of lines. models: class Account(models.Model): name = models.CharField(max_length=50, unique=True) lines = models.ManyToManyField('Line', through='AccountLine', related_name='accounts') class Store(models.Model): type = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255) class ExtendedData(models.Model): x1 = models.BooleanField(default=False) x2 = models.IntegerField(default=0) class Line(models.Model): name = models.CharField(max_length=255) store = models.ForeignKey('Store', on_delete=models.DO_NOTHING) class Meta: unique_together = ('store', 'name') class AccountLine(models.Model): account = models.ForeignKey('Account', on_delete=models.DO_NOTHING) line = models.ForeignKey('Line', on_delete=models.DO_NOTHING) extended_data = models.ForeignKey('ExtendedData', on_delete=models.DO_NOTHING) is_active = models.BooleanField(default=False) class Meta: unique_together = ('line', 'account') I need to create a list view of account's stores, and for each stores the list of connected lines, including the 'through' extra fields 'is_active' , like the following json: [ { "id": 0, -- Store id "type": "store_type_1", "name": "Store1", "lines": [ { "id": 0, -- Line id "name": "Line1", "extended_data": { "x1": true, "x2": 0 }, "is_active": true } ] } ] -
Django quiz form
I have page with some article and some kind of quiz below. I have questions and choices(options in my program) in db. I need to make quiz form where labels are questions from db and choices are options from db. I was looking for some solution and found. But it doesn't work, on page I have nothing, just submit button without form fields forms.py from django import forms from .models import QuestionOption class TestForm(forms.Form): def __init__(self, allQuestions, *args, **kwargs): self.questions = allQuestions for question in allQuestions: field_name = question.question choices = [] for choice in QuestionOption.objects.filter(question=question.id): choices.append((choice.id, choice.option)) field = forms.ChoiceField( label=question.question, required=True, choices=choices, widget=forms.RadioSelect) return super(TestForm, self).__init__(*args, **kwargs) models.py from django.db import models class Topic(models.Model): topic = models.TextField() def __str__(self): return self.topic class Question(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) question = models.TextField() def __str__(self): return self.question class QuestionOption(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.TextField() is_correct = models.BooleanField() def __str__(self): return self.option class TopicMaterials(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() presentation = models.TextField() def __str__(self): return self.topic views.py from django.contrib.auth.decorators import login_required from .forms import TestForm from django.http import HttpResponseNotFound from django.shortcuts import render from .models import Topic, Question, QuestionOption, TopicMaterials @login_required def article(request): topicNum = request.GET.get('topic') if Topic.objects.filter(id=topicNum).exists(): … -
Is there a way to conditionally require a field in a Django Filterset?
Let's say I have a Filterset: class AnimalFilter(filters.FilterSet): animal_family = filters.CharFilter(required=True) is_land_animal = filters.BooleanFilter(required=True) But what if I only want to set required=True for one or the other. Like if someone passes in animal_family, I don't need to receive is_land_animal or vise versa. -
Django mySQL database insert query using .save() and .validate_unique with a composite primary key
I am trying to insert directly into a mySQL database table that has a composite primary key value consisting of 'Fname', 'Lname' and 'DOB'. I want to allow the user to be able to add to the database directly from the web application though using a request.POST form method in Django and getting the user input to insert into the database if it does not violate a duplicate primary key value. However, Django only allows you to assign one primary key value to a model field. This is the table model Athlete_T that also has a Meta class with a unique_together field specifying the composite primary key. class AthleteT(models.Model): fname = models.CharField(db_column='Fname', primary_key=True, max_length=30) # Field name made lowercase. lname = models.CharField(db_column='Lname', max_length=30) # Field name made lowercase. dob = models.CharField(db_column='DOB', max_length=10) # Field name made lowercase. sportsteam = models.CharField(db_column='SportsTeam', max_length=30, blank=True, null=True) # Field name made lowercase. position = models.CharField(db_column='Position', max_length=30, blank=True, null=True) # Field name made lowercase. year = models.CharField(db_column='Year', max_length=15, blank=True, null=True) # Field name made lowercase. height = models.FloatField(db_column='Height', blank=True, null=True) # Field name made lowercase. #upload_to='staticfiles/images' image = models.TextField(db_column='Image', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Athlete_T' unique_together … -
How do I implement reset password link in Django admin of if superuser forgot password then he can reset password using reset_password html template
I want to add forgot password link in django admin panel if superuser forgot password then he don't have to use terminal when project is on product so how to add forgot password option in django admin panel?Django admin login page I've added paths in urls.py and created reset password pages in templates/registration/reset_password_form.html. Please see the images given belowHTML templates for reset passwordpath in urls.pyextended base.html did all this but didn't work -
Django, how i can add item corectly in my cart?
I have a online shop project, in my product detail view i can add to cart items and also this is a cart page which can increase or decrease item there too. the problem is that when i add one myb item in cart page it work like fibonacci sequence and it's add the new number if I have 3 item and use plus one it's gonna be 3+4=7 and if add one more it give me 7+8=15 item. this is my cart.py : def add(self, product, quantity=1): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0} else: self.cart[product_id]['quantity'] += quantity self.save() and this is view.py def add_to_cat_view(request, product_id): cart = Cart(request) product = get_object_or_404(Products, id=product_id) form = AddToCartProductForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data quantity = cleaned_data['quantity'] cart.add(product, quantity) return redirect('cart_detail') and this is cart_detail_view.html <form action="{% url 'cart_add' item.product_obj.id %}" method="post"> {% csrf_token %} <div class="quantity"> <input type="number" class="quantity-input" name="quantity" id="qty-1" value="{{ item.quantity }}"min="1"> {{item.product_update_quantity_form.inplace }} <button type="submit">update</button> </div> </form> -
ImportError: attempted relative import with no known parent package (import from nonexistent parent directory)
I have the following django project structure: └──text_modifier ├── scripts │ ├── reformat.py │ └── upload.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py ├── views.py └── main.py` I want to import a class (Posts) from models.py to upload.py. I do the following: from ..models import Posts However, it returns an error "attempted relative import with no known parent package" I have tried importing sys and running the following: import sys sys.path.append(r"C:\path\to\your\project") Also, I have tried to rearrange the relative import statement in a different way (from text_modifier.models import Posts, from .models import Posts, etc.) I have flicked through python documentation and some tutorials on relative import, as well as posts here with the same error, but found no solution for my particular set of files. -
How to update Foreign Key, but save data for the old instances
My situation: every student can have at least one Annual Review( if student has changed Department during this year - system has to create new independent Annual Review). As a result we will have 2 reviews: 1 - when student was in dep A, and 2 - for dep 2. But using my code of course I have the same department in both cases. How to prevent first Annual Review instance of Department updates? In step of creation the AnnualReview model I want to extract department from current Student instance. class AnnualReview(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey('Student', verbose_name='Student', on_delete = models.CASCADE, related_name='+') class Student(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30, verbose_name='Name') surname = models.CharField(max_length=100, verbose_name='Surname') department = models.ForeignKey('Department', on_delete=models.SET_NULL, null=True, related_name="+", blank=True) -
Errno 10013 An attempt was made to access a socket in a way forbidden by its access permissions
I'm currently working on a django project - real estate app. It's based on internet tutorial from API-Imperfect on youtube. Basically i have been following the steps of that tutorial from the very beginning and this is the err i came across while trying to test api endpoint with insomnia. "[Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions" I tried to create new user and everything works fine, user has been created and so on but the email confirmation which should be sent after each particular user is registered is actually not being sent whatsoever. I googled the err and it showed me few solutions which i tried. was just to off my antivirus and firewall. was to change my dev server to run on different port. 1+2. i checked if the port that i use was occupied by any other process and it wasn't. I am not using Docker YET but i was planning to, anyway i heard it could potentially be because od docker but as i said i've not been using one yet I tried to find a way to restart hns but i can't find it … -
How to sort the context in def get_context_data | Django Views
I have class based view And i need to sort context of this view I want to show 3 tables: 1. Tasks where author is current user + excluding tasks with complete='Done' 2. Tasks where author is any user but not current user + excluding tasks with complete='Done' 3. All Tasks with complete='Done' Final result should be like this: web page example And it works when veiws.py looks like that class TaskList(LoginRequiredMixin, ListView): model = Task def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list_complete'] = context['object_list'].filter(complete='Done') context['object_list_own'] = context['object_list'].filter(author=self.request.user).exclude(complete='Done') context['object_list'] = context['object_list'].exclude(complete='Done').exclude(author=self.request.user) return context Code that in views.py now works correctly, BUT if change the order of the context lines then everything breaks and looks like this: web page example And it DOESNT work when veiws.py looks like that: class TaskList(LoginRequiredMixin, ListView): model = Task def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list'] = context['object_list'].exclude(complete='Done').exclude(author=self.request.user) context['object_list_own'] = context['object_list'].filter(author=self.request.user).exclude(complete='Done') context['object_list_complete'] = context['object_list'].filter(complete='Done') return context I don't know how to fix that please halp T_T models.py class Task(models.Model): STATUS = ( ('Done', 'Done'), ('In progress', 'In progress'), ('Waiting', 'Waiting'), ) author = models.ForeignKey( User, on_delete=models.SET_NULL, null=True ) implementer = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True, related_name='implementer' ) title = models.CharField(max_length=64) desc = models.TextField() complete = … -
How to centre flex with css
Fairly new to CSS & HTML, I am trying to centre display: flex; and having no luck up to now, I have tried multiple things, justify-content: center; align-items: center; And a few others, the issue I am having is no matter what I change it to the divs stay to the left of the screen, I will add a screenshot of this below HTML PIC Probably something I am doing wrong so any help would be much appreciated, if I can use something else apposed to Flex then I am happy to change this to something else if that is recommended, I just need the divs to be displayed centred at the top of the screen. Here is my CSS: body { background-color: #ffffff; min-height: 120vh; height: 100%; margin: 0; max-width: 120vh; overflow: hidden; } .grid-container{ display: flex; align-items: center; margin: 0; flex-direction: row; height: 440px; width: fit-content; max-width: 880px; flex-wrap: nowrap; gap: 10px; } .grid-container-2{ display: flex; align-items: center; margin: 0; flex-direction: row; height: 440px; width: fit-content; max-width: 880px; flex-wrap: nowrap; gap: 10px; } .Divheaders{ color: #ffffff; padding: 3px; border: 3px solid #000000; } .divONE{ background-color: #ffffff3b; height: 650px; width: 650px; max-width: 50%; max-height: 50%; margin-left: auto; margin-right: auto; … -
CURL -X GET does not return any data
I want to make a get request using CURL, but CURL doesn't return any data. **I have 2 dedicated servers with Ubuntu 20.04. ** First one has API (Django framework), other one handling the game server. So, I'm trying to get info from api, by making get request on machine with game server with curl like that: curl -k https://ymasandbox.ru. And here is the result: CURL request from game server Also, I tried to do this on my main machine, and it works just fine! CURL request from main machine -
Django query with annotated accumulative multiplication
I have these 3 models class Nomenclature(models.Model): name = models.CharField(...) class Price(model.Model): nmc = models.ForeignKey(Nomenclature, ...) price = models.DecimalField(...) year = models.SmallIntegerField(..., verbose_name='Year when price was idicated') class InflationRate(models.Model): year = models.SmallIntegerField(...) coefficient = models.DecimalField(...) In "Price" i put nomenclature, its' price and year when this price was indicated. In InflationRate I have records for each rate which indicates for me how high there is inflation in xxx.xx format. For example product A has price 113.34 in 2022, inflation rate coefficient in 2023 was 113.3, in 2024 predicted and recorded value is 120.5, so the price of product in 2024 is 113.34 * 120.5 / 100 * 113.34 / 100 = 154.79. My question how can I annotate predicted price calculated in the way described above to Price queryset? And furthermore this queryset should be also a part of another Subquery I tried to perform something like this: prediction_year = 2024 inflation = RawSQL( """select exp(sum(ln(coefficient/100))) from app_name_inflationrate where year > %s and year < %s """, [F('year'), prediction_year]) price = Price.objects.filter( nmc_id=OuterRef('id') ).annotate( price=ExpressionWrapper(inflation*F('price'), output_field=DecimalField(max_digits=10, decimal_places=2)) ).values_list('price', flat=True) My idea was to do accumulative multiplication of coefficients starting from year when price was indicated in Price table. The problem … -
Sending mail using django
I keep trying to send a mail using the send_mail funtion from "django.core.mail" but my brower keeps throwing this error. SMTPConnectError at / (421, b'Service not available') Please why is this happening. settings.py DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemailaddress' EMAIL_HOST_PASSWORD = 'myapppassword' views.py from django.core.mail import send_mail from django.conf import settings def index(request): if request.method == "POST": heading = request.POST['heading'] message = request.POST['content'] email = request.POST['email'] print(settings.EMAIL_HOST_USER) send_mail( subject=heading, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[email], fail_silently=False ) return render(request, 'index.html') How do I go about to resolve this issue -
Django: Disable CSRF on debug not working
I am debugging my Django project deployed in the cloud. It does not have a domain name yet. I cannot login though the /admin/ page because of the CSRF error: CSRF verification failed. Request aborted. I am also trying to debug it using my frontend deployed in machine at localhost:3000. The same case, I get a 403 response signifying the CSRF verification failure. I want to bypass this on DEBUG=True for the purpose of debugging my APIs. I found this thread, and followed one of its answers: https://stackoverflow.com/a/70732475/9879869. I created a Middleware supposedly disabling the CSRF when DEBUG=True. #utils.py from project import settings from django.utils.deprecation import MiddlewareMixin class DisableCSRFOnDebug(MiddlewareMixin): def process_request(self, request): attr = '_dont_enforce_csrf_checks' if settings.DEBUG: setattr(request, attr, True) I added it to my MIDDLEWARE. It is the last entry in the list. MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "project.utils.DisableCSRFOnDebug" ] After all of this, I still cannot login to my Django admin and my locally deployed frontend still gets the CSRF verification failure. I do not want the csrf_exempt option since it does not make sense placing it on an important endpoint/view -- the Login. Here are my additional configuration on settings.py. X_FRAME_OPTIONS … -
how to get angular form input value using django api?
Here is the Django Login API Code from django.views.decorators.csrf import csrf_exempt @csrf_exempt def login(request): try: response_data = {} if request.method == 'POST': return HttpResponse(request) // {"user":"Umair","pwd":"12345"}(by returning the request it shows angular form input values) user = request.POST['user'] pwd = request.POST['pwd'] Emp = Employee.objects.filter(Emp_Name=user, Emp_Pwd=pwd).exists() if Emp is True: if 'UserName' not in request.session: request.session['UserName'] = user response_data['response'] = "LOGIN SUCCESS!" response_data['IsLogin'] = "TRUE" return HttpResponse(json.dumps(response_data), content_type="application/json") return HttpResponseRedirect('Dashboard') else: response_data['response'] = "Invalid UserName Or Password!" response_data['IsLogin'] = "FALSE" return HttpResponse(json.dumps(response_data), content_type="application/json") else: response_data['response'] = "Request Method must be POST rather than GET" response_data['REQUIRED METHOD'] = "POST" return HttpResponse(json.dumps(response_data), content_type="application/json") except Exception as e: return HttpResponse("Error !" + str(e)) As you can see in the image given below The API returns angular form input values how to get the POST form values and saved in these variables given below: user = request.POST['user'] pwd = request.POST['pwd'] Here is the attached screenshot