Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I called a view within another view django
Currently, I have a view that essentially closes a lead, meaning that it simply copies the information from one table (leads) to another (deals), now what I really would like to do is that after clicking close, the user is redirected to another page where the user can update some entries (sales forecast), I have a view that updates the lead, so I thought that I can do something like below: @login_required def close_lead(request): id = request.GET.get('project_id', '') keys = Leads.objects.select_related().get(project_id=id) form_dict = {'project_id': keys.project_id, 'agent': keys.agent, 'client': keys.point_of_contact, 'company': keys.company, 'service': keys.services, 'licenses': keys.expected_licenses, 'country_d': keys.country } deal_form = NewDealForm(request.POST or None,initial=form_dict) if request.method == 'POST': if deal_form.is_valid(): deal_form.save() obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) ## Changing the Forecast Table Entry forecast = LeadEntry.objects.filter(lead_id=id) for i in forecast: m = i m.stage = "Deal" m.save(update_fields=['stage']) messages.success(request, 'You have successfully updated the status from open to Close') update_forecast(request,id) else: messages.error(request, 'Error updating your Form') return render(request, "account/close_lead.html", {'form': deal_form}) This view provides the formset that I want to update after closing the lead @login_required def update_forecast(request,lead_id): # Gets the lead queryset lead = get_object_or_404(Leads,pk=lead_id) #Create an inline formset using Leads the parent model and LeadEntry the child model FormSet … -
Displaying the correct django authentication framework information in custom admin page
I am trying to display the password in the Admin backend table in the following way, containing the algorithm, iterations, salt and hash: However, my current page looks like the following: As you can see it is just the hashed password, not displaying any of the information unlike the above. Can anyone see where I am going wrong? Please find my code below: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from hobbies.models import extendedUser, User, Hobby from .forms import LoginForm, SignUpForm from django.forms import ModelForm from django.contrib.auth.forms import ReadOnlyPasswordHashField #admin.site.register(User,UserAdmin) class CustomUserAdmin(UserAdmin): add_form = SignUpForm form = LoginForm model = extendedUser readonly_fields = ["password"] list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password', 'city')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(User, CustomUserAdmin) Thank you for your time, Alex -
Display image of players of players app in teams app Django
Trying to display the profile pictures of members (players) of a team but instead getting all the profile pictures. From the long searches I decided to use context_processors as many suggested that approach. (New to Django. Still learning) context_processors.py from .models import Profile def subject_renderer(request): return { 'all_subjects': Profile.objects.all(), } models.py title = models.CharField(max_length=255) team_logo = models.ImageField( null=True, blank=True, upload_to='logos/', default="logos/logo.png", validators=[validate_file_size]) members = models.ManyToManyField(User, related_name='teams') created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=CHOICES_STATUS, default=ACTIVE) 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', 'players.context_processors.subject_renderer' ], }, }, ] template.html {% for team in teams %} <button class="accordion"> <div class="accor"> <img src="{{ team.imageURL }}" alt="" class="logo"> {{team.title}}</div> </button> <div class="panel"> <p> <div class="row"> {% for member in team.members.all %} <div class="column"> <a href="#"> {% for profile in all_subjects %} <img src="{{profile.imageURL}}" style="width:100%"> {% endfor %} <div class="plr-name"> <span> </span> {{ member.username }} </div> </a> </div> {% endfor %} </div> </p> </div> {% endfor %} -
I'm new to using django web framework, during one of my development session using tastypie one error keeps on popping up
[here's the error][1] [1]: https://i.stack.imgur.com/vbfzz.png [my app][2] [2]: https://i.stack.imgur.com/RM9EZ.png [project's url][3] [3]: https://i.stack.imgur.com/sePK0.png -
How to query using the tables with unique field names in django
I have try tables which have somehow connection together using the name fields as bellow: ClassA: name = models.CharField(_("Group name"), max_length=256, unique=True) location = models.ForeignKey(verbose_name=_("Location")) classB: identifier = models.CharField(_("Unique identifier"),max_length=256, db_index=True, unique=True) name = models.CharField(_("Group name"), max_length=256) and the view for classA is: class ClassAListAPIView(ListAPIView): """ Returns list of ClassA's. """ serializer_class = ClassAListSerializer model = ClassA queryset = ClassA.objects.all() def get_classb_objects(self, request): lst_of_classb_identifier = get_queryset.select_related('classb', 'classa').values('identifier') return lst_of_classb_identifier On class base view ClassAListAPIView, I need to define a method (called get_classb_objects) to return a list of all identifier of classB which have a name equal to their name in classA. Is my approach for get_classb_objects correct and if not can you please give me the points? -
How to get rid of 500 error after deploying my django application on heroku and make the site works correctly
I have made a django application. I have used heroku documentation https://devcenter.heroku.com/articles/getting-started-with-python to deploy my project. Everything looked like it works when i finally deployed this app: static files are applied and site works. But, as turned out just after 30 seconds, my site has worked only with GET requests, and with each POST method site has returned 500 error: for example when i have been trying to login, register or authorize my superuser in myapp/admin. I understand that there are troubles with database, but i certainly have no idea what was happening. After 5 minutes my app stoped to work at all. Now it returns 500 error even when i just try to GET any page. I did everything what documentation, link on that i have leaved above, required to do. I think there is no sense to list it, because i DID EVERYTHING and i have checked it out 3 times. And as you can see below the database is included on heroku: There is my settings.py below(if you need any a part of code, just tell): from pathlib import Path import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # … -
django import-export-celery cannot import resource
I'm following this repo but I got this error: Error: Import error cannot import name 'ProfileResource' from 'crowdfunding.models' (C:\_\_\_\_\_\crowdfunding\models.py) which supposedly makes an asynchronous import. The problem is it cannot detect my ProfileResource. I have specified in my settings.py that my resource be retrieved from admin.py. def resource(): from crowdfunding.admin import ProfileResource return ProfileResource IMPORT_EXPORT_CELERY_MODELS = { "Profile": { 'app_label': 'crowdfunding', 'model_name': 'Profile', 'resource': resource, } } but it can't seem to do that. My celery.py is this: from __future__ import absolute_import, unicode_literals import os import sys from celery import Celery # sys.path.append("../") # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainapp.settings') from django.conf import settings app = Celery('mainapp', broker='amqp://guest:guest@localhost:15672//', # broker='localhost', # backend='rpc://', backend='db+sqlite:///db.sqlite3', # include=['crowdfunding.tasks'] ) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() and the broker and backend are working fine so it's just the config not being recognized. What could be the problem? -
django automated scheduler function for patient
I´m new in Django and Python. I need to make a function which add a "non-occupied" schedule (vaccine) to patient according to his age(<1- TBC, Tetanus, whatever.; > 13 - Covid, HIV, .. it´s only example). The point is that object Doctor must have some predefined schedule for example [8:00, 9:00, 10:00, 11:00, 12:00] but max 10 and the occupied ones can´t occupy again. Models: class Doctor(models.Model): name = models.CharField(max_length=100) schedule = models.ForeignKey("Schedule", on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Schedule(models.Model): time = models.CharField(max_length=27) occupied = models.BooleanField() def __str__(self): return self.time I add some predefined time to Doctor in the admin panel. But I really don´t know to make this autimatization. Views: //could start like this def scheduling(request): Schedule = Bed.objects.filter(occupied=False) if user.age < 1 set_schedule [first ava from Schedule] ... Can you please help me? -
have text appear under picture in smaller "mobile" view
I have a site that works great on the desktop mode but when I shrink the page the font stays over the picture and makes it so I cant see the picture and words. How would I adjust the html or css (or both?) to make it so that the font goes below the picture when the site is viewed on a smaller device? Here's my html and css code: {% load static %} <!DOCTYPE html> <html lang="en"> <!-- {% load static %} --> <head> <!--Meta --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="{% block meta_description %} Welcome to Performance Painting's website {% endblock %}"> <title> {% block title %}Performance Painting {% endblock %}</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="Free HTML Templates" name="keywords"> <meta content="Free HTML Templates" name="description"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- Favicon --> <link href="{% static 'website/img/favicon.ico' %}" rel="icon"> <!-- Google Web Fonts --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@400;700&family=Roboto:wght@400;700&display=swap" rel="stylesheet"> <!-- Icon Font Stylesheet --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.0/css/all.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css" rel="stylesheet"> <!-- Libraries Stylesheet --> <link href="{% static 'website/lib/owlcarousel/assets/owl.carousel.min.css' %}" rel="stylesheet"> <!-- Customized Bootstrap Stylesheet --> <link href="{% static 'website/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Template Stylesheet --> <link href="{% static 'website/css/style.css' %}" rel="stylesheet"> </head> <body> <!-- … -
Django Migrations Issue that cause my django admin panel to error out
I am working on a backend for some web app Using Django and it is working 100% fine on my local machine, However; I had to deploy on digital ocean apps and i followed a guide and it went perfectly well but when i try to open the admin panel and access some of my tables i get this error. Below is a small log portion related to error. django.db.utils.ProgrammingError: column myapi_schedule.Start_Time does not exist [scheduler-live] [2021-12-12 21:51:50] LINE 1: ...."Start_Date", "myapi_schedule"."Products_Array", "myapi_sch... [scheduler-live] [2021-12-12 21:51:50] ^ [scheduler-live] [2021-12-12 21:51:50] HINT: Perhaps you meant to reference the column "myapi_schedule.Start_Date". -
reverse query GeoJSONLayerView Django GeoJson
I have a model that looks like this: class Site(models.Model): site_id = models.TextField(primary_key=True) site_name = models.TextField() region = models.TextField(blank=True, null=True) ccamlr_id = models.TextField() latitude = models.DecimalField(max_digits=5, decimal_places=3) longitude = models.DecimalField(max_digits=6, decimal_places=3) centroid = models.GeometryField(blank=True, null=True) class SiteSpecies(models.Model): site_species_id = models.AutoField(primary_key=True) site = models.ForeignKey(Site, models.DO_NOTHING, blank=True, null=True,related_name="sites") species = models.ForeignKey('Species', models.DO_NOTHING, blank=True, null=True) class Species(models.Model): species_id = models.TextField(primary_key=True) common_name = models.TextField() genus = models.TextField(blank=True, null=True) species = models.TextField(blank=True, null=True) And I'm rendering these sites as a GeoJSONLayerView like this: class MapLayer(GeoJSONLayerView): def get_queryset(self): X = Site.objects.all() return X geometry_field = 'centroid' srid = '3031' properties = ['site_name','ccamlr_id'] What I'm trying to do is use the reverse lookup here so when I get the properties for this layer view, I also get Species in the output JSON. I was thinking something like this: class MapLayer(GeoJSONLayerView): def get_queryset(self): X = Site.objects.all() return X geometry_field = 'centroid' srid = '3031' properties = ['site_name','ccamlr_id','sites.all.species_id'] But that doesn't seem to work. Nor does 'sites__all__species_id' Thanks in advance, folks. -
Django 3.x - field in model should not be sent from client but only from admin
I am using a Django model with a field named "status". This field should not be sent from the client and this should be validated by the server. Once the object is created an admin can update this field as the object undergoes different status. How is this best implemented? So far I could not come up with a good idea (readonly fields? Using http methods? ...) -
Cannot get values from request in Django - Empty QueryDict
I’m new to ViewSets and am trying to get the values sent from the front-end fetch method to Django’s request object in the create function. I don’t know whether it’s just a simple syntax error or whether the data isn’t being sent properly from the front-end, but I think it’s a back-end issue. The stringified data in the post method seems to log correctly at the front-end like with this test: {"title":"test","type":"landing","slug":"","notes":""} Printing variables in the ViewSet’s create function however shows these: print(request.POST["title"]) # fails with keyerror: 'title' MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'title' print(request["title"]) # fails with TypeError: 'Request' object is not subscriptable print(request.POST.get("title", “test”)) # fails as print test print(request.POST.get("title")) # fails as it just returns None print(request.get("title")) # fails with AttributeError: 'WSGIRequest' object has no attribute 'get' print(self.request.query_params.get("title", None)) # prints None print(self.request.query_params) # prints empty QueryDict: <QueryDict: {}> Here’s the create function: class PagesViewSet(viewsets.ViewSet): def create(self, request): # printing went here page = Page.objects.create( title="testing", type="other", slug="test-slug", notes="test notes" ) serializer = PageSerializer(page) return Response(serializer.data) I’ve just chucked in demo data inside the page create method to ensure it works, which it does, and now want to use the real data which should be in the request. Does anyone … -
What's the best way to define a particular number with special characters in a database django
I have a specific requirement for a Django model field, essentially I want to create this type of series: 0025-0007 Essentially 4 integer fields, one character, and 4 integer fields thereafter, I don't need an auto-increment as the number changes, is there anything available in Django already that handles such fields, ideally something with automatic validation? -
Query lookups in SQLAlchemy
I can’t find any information about lookup api in the SQLAlchemy, is it supported? I’m talking about this feature in Django ORM: https://docs.djangoproject.com/en/4.0/ref/models/lookups/ It’s very useful for my case because I have a table on frontend with many filtering options, and in Django I can just queryset.filter(**kwargs). If this is not supported, is there any way to achieve it? -
400 http error on all post method of a blueprint
So I have this project that I have added a blueprint to it... everything worked fine and I tested the endpoints. All good All ok . Now after 2 weeks I'm debugging and testing the tasks I have done in the sprint and now all of my requests getting 400 HTTP Error.... Any idea what could have caused the problem ? app file from my_bp import bp app.register_blueprint(bp,url_prefix="/test") my_bp file bp = Blueprint("my_bp",__name__) @bp.route("/test",methods=["GET","POST"] def test(): return {"test":"helloworld"} Now if I send a get request via postman it's all good, but when I try to send a simple post request without a body ( or with the body ) I get the 400 Error response... Thanks in advance P.S. All other blueprints are doing fine but this one is returning 400 on all of my post requests P.S. I use Post-man for sending requests -
Django: How to delete a group which is related to a team?
I want to extend Django's group model. To do so I've created a Team class, which references the group model with a OneToOne field. Create and update work as expected, but I fail to delete the team. # teamapp/models.py from django.db import models from rules.contrib.models import RulesModel from django.contrib.auth.models import Group class Team(RulesModel): group = models.OneToOneField( Group, on_delete=models.CASCADE, primary_key=True, ) name = models.CharField(max_length=80) def save(self, *args, **kwargs): self.update_or_create_group() return super().save(*args, **kwargs) def update_or_create_group(self, *args, **kwargs): group, _ = Group.objects.update_or_create( id=self.pk, defaults={"name": self.name}, ) # teamapp/signals.py from django.db.models.signals import post_delete from django.dispatch import receiver from django.db import transaction from django.contrib.auth.models import Group from teamapp.models import Team @receiver(post_delete, sender=Team) def delete_group(sender, instance, created, **kwargs): # TODO: Use celery for async operation: https://docs.djangoproject.com/en/3.2/topics/db/transactions/ transaction.on_commit(lambda: delete_group(instance)) def delete_group(team_instance): Group.objects.filter(id=team_instance.group).delete() Somehow the signal doesn't trigger. Is there an other way? -
Django REST Framework - the best way to use POST request to other model API endpoint?
I have two models - with users profiles and with events. When the user profile is creating, I want to create for him the timetable with events. When I get the events[] list - I want to send all events using POST to Event model API's in url 127.0.0.1:8000/api/all-events/. What is the simplest way to do that? Event models.py: class Event(models.Model): user_name = models.CharField(max_length=128, default='') event = models.CharField(max_length=128, default='') date = models.DateField(default='') Profiles view.py: class ProfilesList(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['user_name'] def post(self, request, format=None): saveserialize = AccountSerializer(data=request.data) if saveserialize.is_valid(): saveserialize.save() timetable = Timetable(request.data["user_name"], 2021) events = timetable.create_timetable() for event in events: // Here I want to put the .post request to every event. I want to send // {'username': event[0], 'event': event[1], 'date': event[2]} to // Event model API's on url /api/all-events/ return Response("it's working") -
Infinite loop caused by ordering error Django
Faced an issue in Django 3.1.10. It used to work fine for me, however, when deploying the database, when I execute the Payments.objects.all() request, I get the following error. Infinite loop caused by ordering. ['File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/app/bot/assets/BaseRequests.py", line 42, in handle\n await self.__handler(callback, path_args, bot, user)\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/app/bot/commands/subscription.py", line 291, in _\n await subscription_cmd(bot=bot, callback=callback, user=user, path_args=path_args)\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/app/bot/commands/subscription.py", line 227, in subscription_cmd\n for num, pd in enumerate(payment_data, start=1):\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__\n self._fetch_all()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all\n self._result_cache = list(self._iterable_class(self))\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__\n results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql\n sql, params = self.as_sql()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 513, in as_sql\n extra_select, order_by, group_by = self.pre_sql_setup()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 56, in pre_sql_setup\n order_by = self.get_order_by()\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 356, in get_order_by\n order_by.extend(self.find_ordering_name(\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 765, in find_ordering_name\n results.extend(self.find_ordering_name(item, opts, alias,\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 765, in find_ordering_name\n results.extend(self.find_ordering_name(item, opts, alias,\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 765, in find_ordering_name\n results.extend(self.find_ordering_name(item, opts, alias,\n', ' File "/Users/wezzyofficial/PycharmProjects/subscriber_tgbot/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 755, in find_ordering_name\n raise FieldError(\'Infinite loop caused by ordering.\')\n'] The model itself from the models.py: class Payments(models.Model): rate = models.ForeignKey(Rates, help_text='Rate', blank=True, null=True, on_delete=models.CASCADE, related_name='rate_Payments') coupon … -
How to populate database data into multiple modal windows based on ID in Django?
I want to fetch the data of database to the modal window based on their IDs. User Storage is the model name contains multiple IDs based on users. for example, ID -1 should have data A. For ID -2, there should be data B and so on till it iterate IDs of specific user. In views.py file, @csrf_exempt def profile(request,module_id): if request.user.is_authenticated: user_storage_main = user_storage.objects.filter(custom_user=module_id) user_storage = user_storage.objects.get(id=module_id) return render(request, 'profile.html',{"user_storage_main":user_storage_main,"user_storage":user_storage}) and in HTML page, <table> {% for objects in user_storage_main %} <tr> <td><li class="dsi"><a title="" href="#{{ forloop.counter }}"><i class="fa fa-edit"></i></a></li></td> <td><a href="#"><i class="fa fa-trash"></i></a></td> <td>{{objects.store_name}} , {{objects.store_category}}, {{objects.store_start_date}}</td> </tr> {% endfor %} </table> <!-- MODAL WINDOWS STARTED HERE --> <div class="dsi_popup" id="{{ forloop.counter }}"> <div class="new-popup"> <span class="close-popup"><i class="la la-close"></i></span> <h3>Heading</h3><br><br> <form id="www_id" method="post"> <div class="row"> <div class="col-lg-10"> <span class="pf-title">Update Store Name</span> <div class="pf-field"> <input id="sn" type="text" value="{{user_storage.store_name}}" /> </div> </div> <div class="col-lg-4"> <span class="pf-title">Update Store Category</span> <div class="pf-field"> <input id="sc" type="text" value="{{user_storage.category}}" /> </div> </div> <div class="col-lg-4"> <span class="pf-title">Update Start Date</span> <div class="pf-field"> <input id="sd" type="date" name="sd"> </div> </div> <div class="col-lg-12"> <button type="submit">Update</button> </div> </div> </form> </div> </div><!-- MODAL WINDOW END HERE --> EXPECTED OUTPUT : Currently in my database, there are 3 user storages of user with … -
Django get data from included html page
I have a website, where on the "search" page I search for a user in a database, on the "results" page, the data appears, and on this site, I want to make a filtering option. I make this with a "filtered.html" page, which is included in the "results.html" and is having checkboxes. I want to get the checkbox value and according to that, filter the "results.html". If I could get the data from the checkboxes! I don't get any error message, simply nothing shows. (I know that my results page doesn't filter, but I just want it to print my filtered.html data for a start) results.html {% extends "base_generic.html" %} {% block content %} {% include "filtered.html" %} {% csrf_token %} <table> {% for dictionary in object_list %} <td><tr> {% for key, value in dictionary.items %} <td>{{ value }}</td> {% endfor %} </tr></td> {% endfor %} </table> {% endblock %} filtered.html <form method="GET" name="FormFilter"> <div class="form-check"> <input type="checkbox" value="apple" name="fruits" checked> <label for="scales">apple</label> </div> <div class="form-check"> <input type="checkbox" value="plum" name="fruits" checked> <label for="scales">plum</label> </div> <button type="submit">submit</button> </form> view.py def filter(request): fruits = request.GET.getlist('fruits') print(fruits) if fruits == ['apple']: print('you selected apple') if fruits == ['plum']: print('you selected plum') return render(request,'results.html') … -
Why getting .accepted_renderer not set on Response error in django?
I want to return response to my react Js frontend here is my code def save_stripe_info(request): email = 'testing@gmail.com' payment_method_id = 'pm_1K5xfXBbWBJ638dR1WMitwx1' # creating customer customer = stripe.Customer.create( email=email, payment_method=payment_method_id) return Response(status=status.HTTP_200_OK, data={ 'message': 'Success', 'data': {'customer_id': customer.id} } ) but getting error AssertionError: .accepted_renderer not set on Response How can I resolve this. I saw this How to resolve AssertionError: .accepted_renderer not set on Response in django and ajax but this is for only django and returning an HTML page as a template How can I solve this error -
Fetching static files failed in nginx when same route exists
I'm now deploying an django app with nginx and gunicorn on ubuntu. And I configure the nginx virtual host file as below: location /admin { proxy_pass http://admin; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/static/; } I can request the django admin well, but when request a admin static file, it response with 404 status. I'm sure the root path of static file and permissions are correct. Can anyone help? /admin/... (works) /static/admin/... (not works) /static/others (works) -
How can I a Djanog auth user on the command line and not have to manually enter the password?
I'm using Django 3.2 and the auth module. I would like to create a super user on the command line (for eventual inclusion in a docker script). When I try this $ python manage.py createsuperuser --username=joe --email=joe@example.com I'm prompted for a password. The module does not seem to support a "--password" argument ... $ python manage.py createsuperuser --username=joe --email=joe@example.com --password=password usage: manage.py createsuperuser [-h] [--username USERNAME] [--noinput] [--database DATABASE] [--email EMAIL] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] manage.py createsuperuser: error: unrecognized arguments: --password=password Is there a way I can auto-create a user without manual intervention? -
Math in Django ORM and SQLite: decimal ignored if round number, correct result if not round
In a complex query, I have an annotate like this one: result.annotate(test=ExpressionWrapper(485.00 / F( 'period_duration' ), output_field=DecimalField())) This gives me the correct result: Decimal('8.01917989417989E-10') However, if I replace 485.00 with 485: result.annotate(test=ExpressionWrapper( 485 / F( 'period_duration' ), output_field=DecimalField())) I get: Decimal('0') This wouldn't be a problem, if it wasn't that 485 also comes from a field, called "value". My query looks like this: result.annotate(test=ExpressionWrapper( F( 'value' ) / F( 'period_duration' ), output_field=DecimalField())) Value is a MoneyField, basically just a fancy wrapper around DecimalField. I can force my users to always use proper decimals (485.00 as opposed to 485), which in itself would be bad design but... even then, if the database value is 485.00, Django behaves as if it is 485 and thus returns 0 while doing floating point math. I have tried Casting value to a DecimalField, to no avail. result.annotate( res=ExpressionWrapper( Cast('value', output_field=DecimalField()) / F( 'period_duration' ), output_field=DecimalField() )).last().res Result is always: Decimal('0') Instead of the correct one: Decimal('8.01917989417989E-10') How can I force Django to always use floating point math? p.s. period_duration is 604800000000, if it's of any help.