Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto restart the server after capistrano deploy
I have nginx + nginx unit + django python application , and django project is is deployed by capistrano deploy.rb lock "~> 3.16.0" set :application, "mynavi" set :branch, 'master' set :deploy_to, "/var/www/html/mynavi" set :linked_dirs, fetch(:linked_dirs, []).push('static') set :keep_releases, 3 set :linked_files, %w{.env} set :repo_url, "ubuntu@git.viralworks.jp:/~/myGit/mynavi.git" production.rb set :stage, :production set :branch, 'master' server 'lion.viralworks.jp', user: 'ubuntu', roles: %w(app), primary: true namespace :deploy do desc 'Collec Static Files' task :collectImg do on roles(:app) do execute "source activate mynavi;/home/ubuntu/anaconda3/envs/mynavi/bin/python /var/www/html/mynavi/current/manage.py collectstatic --noinput" end end after :publishing, :collectImg end cap prodution deploy makes deployment successfully However, after deployment I need to restart unit manually. sudo systemctl restart unit Can I do this automatic after deployment? -
Django CSRF cookie not set error with React + Redux + Axios. Even though I added it to headers
I am using Django with React. I am fetching the csrf token from Django using get_token() method from from django.middleware.csrf import get_token. I am passing it while making post request from React using Axios. Here is the code return await Client.post(endpoint, { headers: { "Authorization": "Bearer " + getState().auth.accessToken, "X-CSRFToken": getState().auth.csrf, }, withCredentials: true, data, }); I am getting this error on my backend Forbidden (CSRF cookie not set.): I then tried to add cookie in the headers... headers: { "Authorization": "Bearer " + getState().auth.accessToken, "X-CSRFToken": getState().auth.csrf, "Cookie": getState().auth.csrf }, Still don't work Here is csrf setting in settings.py CSRF_TRUSTED_ORIGINS = [ "localhost:3000", ] CSRF_COOKIE_HTTPONLY = True -
Django REST and Pytest fixtures APIClient get_or_create alternative
I am trying to create a fixture for pytest for my client. The problem is I get the following error: ERROR tests.py::test_get_list_test - django.db.utils.IntegrityError: NOT NULL constraint failed: authtoken_token.user_id I guess I should be using an alternative to get_or_create when creating APIClient, but I am not sure how to implement something like that. This is my fixture: @pytest.fixture def client(db): api_client = APIClient() token = Token.objects.get_or_create(user__username='testuser') api_client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) return api_client -
Update on related fields throws FieldDoesNotExist
Import and export work as expected but when i try to reimport the same file (update), i get this error:enter image description here resources.py class ArticleResource(resources.ModelResource): number = fields.Field(column_name="GMC", attribute="number", widget=CharWidget()) name = fields.Field(column_name="Artikelbezeichnung", attribute="name") intern_name = fields.Field(column_name="Artikelbezeichnung_intern", attribute="intern_name") brand = fields.Field(column_name="Marke", attribute="brand") base_label_number = fields.Field(column_name="Grundetikettennummer", attribute="base_label_number") barcode = fields.Field(column_name="Barcode_Produkt", attribute="barcode") layers = fields.Field(column_name="Lagen", attribute="layers") formatclass = fields.Field( column_name="FCL", attribute="formatclass", widget=ForeignKeyWidget(FormatClass, "number") ) volume = fields.Field(column_name="Volumen_in_L", attribute="volume", widget=IntegerWidget()) height = fields.Field(column_name="Höhe", attribute="height", widget=IntegerWidget()) width = fields.Field(column_name="Breite", attribute="width", widget=IntegerWidget()) comment = fields.Field(column_name="Bemerkung", attribute="comment") group_code = fields.Field( column_name="Grundetikett_A-Code", attribute="group", widget=ArticleGroupWidget(ArticleGroup, "code") ) group_name = fields.Field( column_name="Bezeichnung_Grundetikett", attribute="group", widget=ForeignKeyWidget(ArticleGroup, "name"), readonly=True, ) class Meta: model = Article use_bulk = True use_transactions = True skip_unchanged = True report_skipped = True import_id_fields = ["number"] exclude = ["id", "group", "packsize"] -
Problem in Django cooperation with esp 8266
Hello i need help with my django project . I want to run program on ESP 8266 from django website. To test I create simple program with blink diode on ESP and I made button on my django website and it works but I use "webbrowser()" in views.py and it is not looks perfect (I need to stay on this webiste, a webiste made in django, not open a new one). I need help to create something what will work like: I click the button on my django website, program in "views.py" send something to esp what runs program on it or change something in the ESP code, which is only going to run the code, and it won't open web browser. my views.py: def espON(request): on = On.objects.all() off = Off.objects.all() menu = menu.objects.all() webbrowser.open("http://my_ip/turnOn") d = {'on':on, 'off':off, 'menu':menu,} return render(request, 'on/index.html', d) ESP code: #include <ESP8266WiFi.h> #include <Ticker.h> #include <Math.h> const char* ssid = "my_ssid"; //nazwa ssid sieci const char* password = "my_password"; //haslo #define LED 5 WiFiServer server(80); void setup() { Serial.begin(115200); delay(10); pinMode(LED, OUTPUT); //Laczenie z siecia wifi Serial.println(); Serial.println(); Serial.print("Laczenie z: "); Serial.println(ssid); IPAddress ip(my_ip); //ip IPAddress gateway(my_ip2); IPAddress subnet(my_ip3); WiFi.config(ip, gateway, subnet); WiFi.begin(ssid, … -
Stripe: Recurring payment increment by the number of licenses increase
I have Django app. That allows the users to buy licenses subscriptions with stripe as a recurring payment when they are paying the subscription. The licenses are use automatically when connecting to the API. I want to change the use case: Well the user put his card on the customer portal in stripe. I can use for debting his card as the number of licenses are increasing. Is it possible? if it is how can be done it? -
Django makemessage not updating .po files for installed apps
I'm working with a current project that has existing .po files in "locale" directories in multiple installed app directories. Currently each locale directory is explicitly mentioned in the LOCALE_PATHS even though the docs state it will search for locale directories in each installed app. I wanted to remove the values in LOCALE_PATHS and just let normal discovery work, but it's not working. If I clear out LOCALE_PATHS and run manage.py makemessages it appears like it's doing something (time is spent processing), but no file changes occur. If I do makemessages --keep-pot then I can see all the .pot files are actually being created, but it's not actually creating the .po files for each language. Only if I explicitly pass a -l de do I then get an updated .po file for the language stated and a message stating "processing locale de". It SHOULD be able to look at the LANGUAGES setting or what files already exist and properly update them, but that appears to only happen if every locale directory is explicitly added into LOCALE_PATHS. If I have all the locale paths in LOCALE_PATHS then I can just run manage.py makemessages and all .po files are properly updated. This is … -
How can I Make a post request to this endpoint with my authorization header and body with django and python
Good day guys, am trying to use django and python request to make a post request to this endpoint with the authorization header and body gotten from this website. check my code below to understand what am saying. i need your lovely help to get this issue right and to make this code work. the mobile number and other field should take my django form and model input. Kindly, Check this code out. class RechargeData(models.Model, Main): user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) phone_number = models.CharField(validators=[Main.phone_regex], max_length=10) network = models.CharField(choices=Main.OPERATORS, max_length=15) plan = models.IntegerField(choices=Main.PLANS) amount = models.DecimalField(max_digits=10, decimal_places=2) views.py import requests import json from .forms import RechargeForm def rechargedata(request): url = "http://127.0.0.1:8000/api/data/" payload = "{\"network\": network_id,\n\"mobile_number\": \"09037346247\",\n\"plan\": plan_id}" headers = {'Authorization': 'Token 5fd60vcdfddfxddsssfddff9a0a8742d','Content-Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=payload) if request.method == "POST": form = RechargeForm(request.POST) if form.is_valid(): phone_number = form.cleaned_data['phone_number'] network = form.cleaned_data['network'] amount = form.cleaned_data['amount'] plan = form.cleaned_data['plan'] form.save context = RequestContext(request, { 'phone_number': responsedata.mobile_number, 'network': response.data.network_id, 'mobile_number': response.data.network_id, 'plan': response.data.plan_id, }) return render(request, 'embeds.html', {'context': context, 'form'; form}) else: form = RechargeForm() return render(request, 'index.html', {'context': context, 'form'; form}) How do I fix this? -
Facing an error with django channels when deploying to elastic beanstalk
I am facing an issue with websockets. When I run the program locally it works fine but when I deploy it to aws elastic beanstalk I face the following issue. I have a simple code as mentioned below. django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: playzone.wsgi:application aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static Procfile web: gunicorn my_app.wsgi websocket: daphne -b :: -p 5000 my_app.asgi:application asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( routing.websocket_urlpatterns ) }) And there are 2 more simple files routing.py and consumers.py. I've even configured the load balancers on the environment's settings (80 - HTTP ; 5000 - HTTP). So once deployed, when I try routing to the webpage which has a websocket connection, I get an error saying WebSocket connection to 'ws://yyy.com/ws/' failed:. Please help me out on how I can fix it. Also am not using redis or any channel layer. Please help me out on how I can fix it. -
Proper way to create django rest endpoint without model
I have to create API endpoint that will take data from GET request body. It will find necessary data in already created database to perform calculation and then it should return calculation result as response. So I found a way to do it but I'm not sure if it should look like this. It works but you know :) urls.py schema_view = get_schema_view( openapi.Info( title="API Test", default_version='0.0.1', description="Test", ), public=True, ) urlpatterns = [ path('docs/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('equation/1/example', EquationView.as_view()), #... more paths to other equations... ] view.py def get_emission_val(req_emiss_fac): try: return Emission.objects.get(emission_factor=req_emiss_fac) except Emission.DoesNotExist: raise Http404("Emission value does not exist in database") equation_response = openapi.Response('response description', EquationResponseSerializer) @swagger_auto_schema( query_serializer=EquationRequestSerializer, responses={ '404':'Emission factor does not exist in database', '200': equation_response }, ) class EquationView(APIView): def get(self, request): emission_val = get_emission_val(request.data['emission_factor']) combusted_val = request.data['combusted_value'] emissions = combusted_val * emission_val.co2_emission return Response({'emissions':emissions}) serializers.py class EquationRequestSerializer(serializers.Serializer): emission_factor = serializers.CharField() combusted_value = serializers.FloatField() class EquationResponseSerializer(serializers.Serializer): emission = serializers.FloatField() What do you think about this approach? I'm not sure if I have to do it in this way. I'm using swagger and additional serializers for gerenerating api docs Example get request body: { "emission_factor":"Test", "combusted_value":1.0 } Example response: { "emissions": 1.5129 } -
Iterating over the keys of a dictionary, when keys are integer, now I am getting this error "TypeError: argument of type 'int' is not iterable"
I am working on pay raise of employees with particular ids. Suppose, I have 5 employees in my company. I have shown them in a employee_id_list. I want python to take input from me which consists of the particular ids of the employees, I want to raise the pay, along with their salary. Then, I am creating the dictionary out of these inputs. Now I want to iterate over the employee_id_list such that it matches with of the input ids. If it matches, I want to take the respective value of key which is salary and raise the pay. But I am getting an error. I have searched for everything present on stackoverflow but nothing matches my problem employee_id_list = [27, 25, 98, 78, 66] employee_dict = dict() while True: x = input("Enter an key to continue and 'r' for result: ").lower() if x== 'r': break try: employee_id = int(input("Enter key the Employee id: ")) salary = int(input(f"Enter the {employee_id}'s salary: ")) employee_dict[employee_id] = salary except ValueError: print("Please Enter the Integers!") continue print(employee_dict) for e_ids in employee_id_list: for key, value in employee_dict.items(): if e_ids in employee_dict[key] : employee_dict[value] = 0.8*value + value print(employee_dict) I am getting this error TypeError: argument … -
Add a dynamic initial value in Filter
I want to add a dynamic initial value for django-filter or django-autocomplete-light to my DetailView. I don’t know how best to build it with django-filter, django-autocomplete-light or without third app. I have a dependency dropdown (in my case, this is journal → journal year → journal volume) for each JournalDetailView. Dependency dropdown works with django-autocomplete-light and filter works with django-filter. I want to pass dynamic field for journal so I have ForeignKey which is used for depends dropdown for journal year and journal volume For example, In this case I have three fields: journal, journal year and journal volume. I want to pass value depends on DetailView for journal. For instance, for journal “Nature” it will pass field “Nature”; for journal “Ca-A Cancer Journal for Clinicians” it will pass “Ca-A Cancer Journal for Clinicians”. I have this I want to build this models.py class Journal(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=100, blank=True, null=True) class Article(models.Model, HitCountMixin): slug = models.SlugField(unique=True) journal = models.ForeignKey( "Journal", on_delete=models.SET_NULL, null=True, blank=True ) journalyear = models.ForeignKey( "JournalYear", on_delete=models.SET_NULL, null=True, blank=True ) journalvolume = models.ForeignKey( "JournalVolume", on_delete=models.SET_NULL, null=True, blank=True ) def __str__(self): return self.title class JournalYear(models.Model): journal = models.ForeignKey( "Journal", on_delete=models.SET_NULL, null=True, blank=True ) name = models.CharField(max_length=10, … -
"Uncaught ReferenceError: user is not defined at" in Django
I am trying to make an e-commerce website by following the guide of Dennis Ivy in YouTube. But in applying some logic in the checkout form, I've been facing an error that says "Uncaught ReferenceError: user is not defined at". ["Uncaught ReferenceError: user is not defined at" in the console] What I want to do is remove the 'user-info' if the user is not "AnonymousUser". And remove the 'form' if you don't need to ship the products (digital) and the user is not "AnonymousUser". Here's the checkout.html code: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name.."> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email.."> </div> </div> <div id="shipping-info"> <hr> <p>Shipping Information:</p> <hr> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address.."> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City.."> </div> <div class="form-field"> <input class="form-control" type="text" name="state" placeholder="State.."> </div> <div class="form-field"> <input class="form-control" type="text" name="zipcode" placeholder="Zip code.."> </div> <div class="form-field"> <input class="form-control" type="text" name="country" placeholder="Zip code.."> </div> </div> <hr> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue"> </form> </div> <br> <div class="box-element hidden" id="payment-info"> <small>Paypal Options</small> <button id="make-payment">Make Payment</button> </div> … -
How to use dart sass in python
Is there any python library to compile sass which uses the Dart Sass implementation? Currently I am using the libsass-python library. But Libsass is now deprecated Which is the current best choice to compile sass in python? -
I cannot retrieve the corresponding data when I want to relate the foreign key with the User object
models.py class Order(models.Model): PAYMENT_OPTIONS = ( ('VISA','VISA'), ('Master','Master'), ('Octopus','Octopus'), ('Cash','Cash'), ) STATUS = ( ('Pending','Pending'), ('Delivered','Delivered'), ) user = models.ForeignKey(User,models.CASCADE,null=True,blank=True) customer = models.CharField(max_length=200,null=True,blank=True) card_id = models.IntegerField(null=True,blank=True) mobile = models.IntegerField(null=True,blank=True) email = models.CharField(max_length=200,null=True,blank=True) total_price = models.DecimalField(decimal_places=2,max_digits=7) payment_method = models.CharField(max_length=50,choices=PAYMENT_OPTIONS,null=True,blank=True) status = models.CharField(max_length=50,choices=STATUS,default='Pending') date = models.DateTimeField(auto_now_add=True) address = models.CharField(max_length=350,null=True,blank=True) def __str__(self): return str(self.customer)+'\'s Order' views.py def order_summary(request,order_id): customer_order = Order.objects.get(id=order_id) food_order = OrderDetail.objects.filter(order=customer_order) context = { 'customer_order':customer_order, 'food_order':food_order} return render(request,'menu/order_summary.html',context) navbar.html <li><a class="dropdown-item" href="{% url 'order_summary' [order_id]%}我的訂單</a></li> For the above code, I may want to have the hyperlink that can access the order_summary method with filtering the correct User object. However, if I want to filter out the object in Order model with the user equals to the current request.user, I am not sure what should I put in the order_id in the hyperlink because the navbar could not recognize the correct object in the Order model so can anyone explain? -
create API by using generic.ListAPI take too much time
I am creating API in django by using generic.ListAPI when i hit this API it take too much time approx. 5 min. Below is my code what mistake i did can anybody help me class KeyMarket(generics.ListAPIView): queryset = UserAddress.objects.all() serializer_class = UserAddressSerializer def list(self, request, *args, **kwargs): b = [] add = [] filter_data=UserAddress.objects.filter(address_type='1') serializer = self.get_serializer(filter_data, many=True) b.append(serializer.data) for i in range(len(serializer.data)): c = serializer.data[i] add.append(c['address']) re = set(add) return Response(re) -
How to keep the razorpay id secret in the html that is being passed as a context for processing the payment?
I am using an .env file to keep the variables out of the settings.py but the razorpay_id that is supposed to be a secret can still be seen by inspecting the element of the page in which the id is being passed in the context. How I can keep it a "secret" or what is the process to keep that id a "secret" in the html too during the entire payment process. this is the codes that I am using. .env RAZORPAY_ID=test_id RAZORPAY_ACCOUNT_ID=test_id settings.py RAZORPAY_ID = env('RAZORPAY_ID') RAZORPAY_ACCOUNT_ID = env('RAZORPAY_ACCOUNT_ID') views.py client = razorpay.Client(auth=(settings.RAZORPAY_ID , settings.RAZORPAY_ACCOUNT_ID)) context={ 'razorpay_merchant_id': settings.RAZORPAY_ID, } html <script> var options = { "key": "{{razorpay_merchant_id}}", } </script> -
Django access information model with foreign key
my models.py class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): found_articles = models.ForeignKey( Information, on_delete=models.CASCADE, default=None, primary_key=True) search_details = models.ForeignKey( Search, on_delete=models.CASCADE) my views.py def show_articles_with_this_filter_id(request): alles = Article_search.objects.all() print(alles) the error i get: (1054, "1054 (42S22): Unknown column 'database_article_search.found_articles_id' in 'field list'", '42S22') if i make my models.py Article_search class like this: class Article_search(models.Model): found_articles = models.ForeignKey( Information, on_delete=models.CASCADE, default=None) search_details = models.ForeignKey( Search, on_delete=models.CASCADE) I get this error: (1054, "1054 (42S22): Unknown column 'database_article_search.id' in 'field list'", '42S22') It seems like I need to specify an ID or so. Please can someone help me to access the data from this model -
Django custom admin template has_change_permission is always None
I have a custom admin template where I need to check has_add_permission and has_change_permission values. I can see that the has_add_permission has True/False according to the permission assigned to the user. The value of has_change_permission is always None. For instance: {% if has_add_permission %} {# The condition has a True/False value #} ... {% endif %} {% if has_change_permission %} {# Never executed because the condition is always None #} ... {% endif %} How can I determine if the user can change a table? -
Nginx not serving static files and user uploaded files in Django Kubernetes
Hi i am working on a kubernetes and can't get static files or user documents. This runs behind nginx ingress all queries and django works as expected. But unable to figure out why images and other documents cant be obtained via url. Application gets installed using helm charts and functionality seems to be okay other than serving files. FROM python:3.8.12-alpine3.15 ADD ./requirements.txt /app/requirements.txt RUN set -ex \ && apk add --no-cache --virtual .build-deps postgresql-dev build-base linux-headers jpeg-dev zlib-dev\ && python -m venv /env \ && /env/bin/pip install --upgrade pip \ && /env/bin/pip install --no-cache-dir -r /app/requirements.txt \ && runDeps="$(scanelf --needed --nobanner --recursive /env \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u)" \ && apk add --virtual rundeps $runDeps \ && apk del .build-deps ADD ./ /app WORKDIR /app ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH RUN apk add nginx RUN rm /etc/nginx/http.d/default.conf COPY helm/nginx.conf /etc/nginx/nginx.conf ENTRYPOINT ["sh", "helm/run.sh"] run.sh nginx -g 'daemon on;' gunicorn main_app.wsgi:application --bind 0.0.0.0:8080 --workers 3 nginx.conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; # default_type application/octet-stream; access_log /var/log/nginx/access.log; upstream … -
Configuration of MYSQL connectivity in django framework
Well, I'm trying to connect MYSQL database to Django , I have installed mysql installer 8.0 version, after installation in the Accounts and Roles section its not taking root account password and also I m not getting to change the password option, please help if anyone faced the same problem , let me know if any solution for this . How do I change the MYSQL root account password -
ValueError: Cannot query "sohanur": Must be "CustomUser" instance
I am trying to filter my vendor list as per request.user.vendor. It is working and get the requested user but here I can't query through my Vendor list. Vendor has a onetoone relation with my custom user. How to query?? #this is my model class CustomUser(AbstractUser): number = models.CharField(max_length=200, blank=True, null=True) isVendor = models.BooleanField(default=False, blank=True, null=True) class Vendor(models.Model): user = models.OneToOneField(CustomUser, related_name='vendor', on_delete=models.CASCADE, null=True, blank=True) distributor_for = models.ManyToManyField(Distributor, null=False, blank=True) name = models.CharField(max_length=200, blank=True, null=True) profile_picture = models.ImageField(null=True, blank=True) address = models.TextField(max_length=2000, blank=True, null=True) latitude = models.DecimalField(max_digits = 13, decimal_places = 7, blank=True, null=True) longitude = models.DecimalField(max_digits = 13, decimal_places = 7,blank=True, null=True) is_verified = models.BooleanField(default=False) createdAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) def __str__(self): return self.name #this is my api view @api_view(['GET']) @permission_classes([IsVendor]) def getVendors(request): user = request.user.vendor print(user) vendor = Vendor.objects.all().filter(user=user) serializer = VendorSerializer(vendor, many=False) return Response(serializer.data) #this is my serializer class VendorSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField(read_only=True) class Meta: model = Vendor fields = '__all__' def get_user(self, obj): user = obj.user serializer = UserSerializer(user, many=False) return serializer.data -
How can i get all related object's manytomany related field's records in Django by single query
class Author(models.Model): name = models.CharField(max_length=50) class Chapter(models.Model): book = models.ForeignKey(Album, on_delete=models.CASCADE) author = models.ManyToManyField("Author") class Book(models.Model): author = models.ManyToManyField("Author") I can get Author.objects.get(id=1).chapter_set.all() and append each chapters author to the List but how can i achieve this by query in Django -
Django unable to save FloatField value to 0.0
I have a method on a model that updates a value to 0.0 and calls save(). Problem is save() is never saving the value if it is 0. Here is the code: class Item(models.Model): stock_quantity = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0)] ) class Meta: abstract = True ordering = ["-id"] def mark_as_finished(self) -> None: self.stock_quantity = 0.0 self.save() I have a submodel which extends this one. class Instance(Item): expiration_date = models.DateField(null=True, blank=True) Now the mark_as_finished() is called in the view: @action(detail=True, methods=["patch"], url_name="mark-as-finished") def mark_as_finished(self, request: Request, pk: int) -> Response: pi_instance = get_object_or_404(Instance, id=pk) pi_instance.mark_as_finished() pi_instance.refresh_from_db() return Response( data=self.serializer_class(pi_instance).data, status=HTTP_200_OK, ) Upon running the test the stock value never becomes 0. def test_mark_as_finished(self): pink_ins = self.create_sample_instance() self.assertNotEqual(pink_ins.stock_quantity, 0) url: str = reverse(self.mark_finished_url, kwargs={"pk": pink_ins.id}) res: HttpResponse = self.client.patch(url) self.assertEqual(res.status_code, 200) self.assertEqual(res.data["stock_quantity"], 0) self.assertEqual(res.data["stock_quantity"], 0) AssertionError: 10.5 != 0 I am debugging the program and can see that after the save runs the value is never being saved. If I put the value as 0.1 then it saves. So actually it is not saving 0 value in the float field. I even removed the MinimumValueValidator still it won't save 0 value. -
Django Forms ChoiceField is not showing options; remains hidden
views.py def rank(request): if request.method == 'POST': form = RankRegisterForm(request.POST or None) if form.is_valid: form.user = request.user form.save(commit=False) return redirect('matches/rank.html') else: form = RankRegisterForm() return render(request, 'matches/rank.html', {'form': form}) forms.py class RankRegisterForm(forms.ModelForm): rank = forms.ChoiceField(choices=rankChoices) class Meta: model = Rank fields = ( "rank", ) html {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} <div class="container"> <p> Belt Rank Status </p> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="red-text text-darken-1" type="submit">Submit</button> <br></br> </form> </div> {% endif %} {% endblock content %} models.py class Rank(models.Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True, ) rank = models.CharField("rank", max_length=20, choices=rankChoices) rankPoints = models.IntegerField("rank points", default=0) certificateOfLegitimacy = models.BooleanField(default=False) promoted = models.BooleanField(default=False) def __str__(self): return self.rank + ", " + self.user.email DOM <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="ITC0cjPUCmvhuYD2K1eDgjPOt1daSRJbi8mbpLmv6ETGVe9akMI2SOfjEJQcXJ9A"> <p> <label for="id_rank">Rank:</label> <select name="rank" id="id_rank"> White Blue Purple Brown Black thanks, this sucks. I've been looking everywhere and there isn't a question related to mine that has been answered. It's hidden, i suspect it's because of the csrf shit. but idk. help a brother out.