Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to mock the response from a library api in pytest
Writing an pytest for a function that is making api call using an installed package. How do you mock the response from the api response? This is how the function looks like import hubspot from pprint import pprint from hubspot. import ApiException def get_clicked_events(): client = hubspot.Client.create(api_key="YOUR_HUBSPOT_API_KEY") try: api_response = client.events_api.get_page(limit=100, event_type="clicked") pprint(api_response) return api_response except ApiException as e: print("Exception when calling events_api->get_page: %s\n" % e) -
Worker isns't populating some apps on Django
The worker from my django project isn't detecting some apps but other yes. All of them are in INSTALLED_APPS. And thats makeing it restarting endless. What could be it? here is the directory structure: -project -worker -pycache -init.py -celery.py -tasks.py The traceback below is getting error on bootstrapform, if I take off that from installed apps, the next module go to the traceback which is crispy_forms and so on. here is the traceback: Checking for celery... OK Starting worker using broker at redis://broker Checking for celery... OK Starting worker using broker at redis://broker self.django_setup() File "/usr/local/lib/python3.9/dist-packages/celery/fixups/django.py", line 118, in django_setup django.setup() File "/usr/local/lib/python3.9/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrapform' Postgres is up - executing command wait-for-it.sh: waiting for broker:6379 without a timeout wait-for-it.sh: broker:6379 is available after 0 seconds wait-for-it.sh: waiting for webapp:8000 without a timeout wait-for-it.sh: webapp:8000 is available after 0 seconds Traceback (most recent call … -
Django REST how to not apply default permission for get request
I don't want to apply my permission_classes for get request. I tried @permission_classes(AllowAny) but didn't work. Here is my my code: class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup] @permission_classes(AllowAny) def list(self, request): if request.method == "GET": blog = Blog.objects.all().order_by("id") serializer = BlogSerializer(blog, many=True) return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) -
Django multi-table inheritance - make sure only one child exists (CheckConstraint)
How can I make sure that a parent object has only one child/type? class Property(...): class Meta: abstract = False class Flat(Property): pass class House(Property): pass class Land(Property): pass I want every property object to have none or at most one child. It can be either flat, house or land (or null). Is it possible to create a DB constraint for this? My idea was to create a constraint that checks: class Meta: constraints = [ models.CheckConstraint(check=Q(Q(flat__isnull=True) & Q(house__isnull=True)) | Q(Q(flat__isnull=True) & Q(land__isnull=True)) | Q(Q(house__isnull=True) & Q(land__isnull=True)), name="constraint")] But apparently, there are no such fields on a DB level (you can get flat by property.flat getter in Django but not in DB) EDIT: properties.Property: (models.E012) 'constraints' refers to the nonexistent field 'flat'. -
sitemaps returns NoReverseMatch at /sitemap.xml
I'm trying to add sitemaps in my application, but when i add a url that has slug, it throws me an error in http://127.0.0.1:8000/sitemap.xml Reverse for 'view-Question' with no arguments not found. 1 pattern(s) tried: ['questions/(?P[-a-zA-Z0-9_]+)/\Z'] i follow this Tutorial my urls: sitemaps = { 'static': StaticViewSitemap, } path('', views.Home, name='Home'), path('login', views.login, name='login'), path('register/', views.register, name='register'), path('Terms', views.rules, name='Rules'), path('questions/<slug:slug>/', views.viewQuestion, name='view-Question'), path('feedback/', views.PostFeedBack.as_view(), name='FeedBack'), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), my sitemaps.py file: from django.contrib import sitemaps from django.urls import reverse class StaticViewSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'daily' def items(self): return ['Home', 'login', 'register', 'Rules', 'FeedBack', 'view-Question'] def location(self, item): return reverse(item) Thanks. -
Can django-nested-admin sort the top level items in select-to-change list in addition to inline items?
I could sort inline items with django-nested-admin as shown below: But, I couldn't sort the top level items in select-to-change list as shown below: This is the code in "models.py" as shown below: # "models.py" from django.db import models class Country(models.Model): name = models.CharField(max_length=100) position = models.PositiveSmallIntegerField("Position", null=True, blank=True) class Meta: ordering = ('position',) def __str__(self): return self.name class Province(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) position = models.PositiveSmallIntegerField("Position", null=True) class Meta: ordering = ('position',) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=100) province = models.ForeignKey(Province, on_delete=models.CASCADE) position = models.PositiveSmallIntegerField("Position", null=True) class Meta: ordering = ('position',) def __str__(self): return self.name And, this is the code in "admin.py" as shown below: # "admin.py" from nested_admin import SortableHiddenMixin, NestedTabularInline, NestedModelAdmin from .models import Country, Province, City class CityInline(SortableHiddenMixin, NestedTabularInline): model = City sortable_field_name = "position" class ProvinceInline(SortableHiddenMixin, NestedTabularInline): model = Province sortable_field_name = "position" inlines = (CityInline,) @admin.register(Country) class CountryInlineAdmin(SortableHiddenMixin, NestedModelAdmin): sortable_field_name = "position" inlines = (ProvinceInline,) Are there any ways to sort the top level items in select-to-change list? Or, is it impossible to sort the top level items with django-nested-admin? -
How to store the form data into database in django?
#I have this code for a message form and I want to store each message into the database #I have the code below : #The View code : class Contact(LoginRequiredMixin , CreateView ): template_name = "business/contact.html" form_class = ContactUsForm success_url = reverse_lazy("home") def form_valid(self, form): form.save() return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["services"] = Service.objects.all() return context #The model code class ContactUs(models.Model): name = models.CharField(max_length=100) email = models.EmailField() telphone = PhoneNumberField() department = models.ManyToManyField(Service) message = models.TextField(max_length=1000) #the form code from django import forms from .models import ContactUs from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget class ContactUsForm(forms.ModelForm): telephone = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = ContactUs fields = "__all__" -
Django Apache setup - forbidden Error 403
Since it did not work on the first time, I created a fresh new venv for my django project. my folder structure looks like this: btw I used the Django/Apache Setup guide from digitalOcean (https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04) /home/pi/myproject/myprojectenv (this is where my env is located) /home/pi/myproject/myprojectenv/myproject/myproject (this is where the settings.py is located) I added this to the settings.py file (I use a pi, I only serve locally) ALLOWED_HOSTS = ['localhost', '127.0.0.1'] and at the bottom STATIC_ROOT = os.path.join(BASE_DIR, 'static/') my /etc/apache2/sites-available/000-default.conf looks like this: <VirtualHost *:80> #for django Alias /static /home/pi/myproject/myprojectenv/myproject <Directory /home/pi/myproject/myprojectenv/myproject/static> Require all granted </Directory> <Directory /home/pi/myproject/myprojectenv/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/pi/myproject/myprojectenv python-path=/home/pi/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/pi/myproject/myprojectenv/myproject/myproject/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> when I go to /static in the browser I get a http 403 forbidden Error. What am I doing wrong? -
how to check if input for barcode is valid using django?
I made an app to generate barcodes using python-barcode library (Python)(django framework) and there's two fields 1 - to let the user input the number that will used for generate the barcode 2 - options to let the user select which type of barcode he wants for now everything work fine it's generating the barcodes but some of the barcodes have its specific types of inputs like 12 digits or 8 digits and so on so how to check the inputs if its valid for that type of barcode or not?, then show error messages if it's wrong, or succes message if it generated fine I know I can use messages form django itself but how I can implement it with checking function? for views.py from sre_constants import SUCCESS from django.http import HttpResponse from django.shortcuts import redirect, render import barcode from barcode.writer import ImageWriter import tempfile from django.contrib import messages def index(request): context = {'barcode_types':barcode.PROVIDED_BARCODES} return render(request, 'index.html',context) def generate_barcode(request): inputs = request.POST['inputs'] types = request.POST['types'] barcode_class = barcode.get_barcode_class(types) file = tempfile.NamedTemporaryFile() code = barcode_class(inputs,writer=ImageWriter()) file_path = code.save(file.name) response = HttpResponse(open(file_path,'rb').read(), headers={'Content-Type': 'image/png','Content-Disposition': 'attachment; filename="'+inputs+'.png"'}) return response -
Django API feed linking to 'URL' instead of name
I am currently feeding an API to my django web page and a key value inside the first API contains a URL to another API My goal is to get the key: name under my second API - 'speciality' and not the url itself. html <div class="container-fluid p-2 bg-primary text-white text-center"> <h1>Users</h1> <a style="background: black;" href="http://localhost:8000/api/">Check out our API here</a> </div> <div class="container mt-5"> <table class="table"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Lastname</th> <th>Email</th> <th>Hiring Date</th> <th>Phone</th> <th>Job</th> <th>Speciality</th> <th>Salary</th> </tr> </thead> <tbody> {% for user in users %} <tr> <td>{{ user.id }}</td> <td>{{ user.name }}</td> <td>{{ user.last_name }}</td> <td>{{ user.email }}</td> <td>{{ user.hire_date }}</td> <td>{{ user.phone_number }}</td> <td>{{ user.job }}</td> <td>{{ user.speciality }}</td> <td>{{ user.salary }}</td> </tr> {% endfor %} views.py def home(request): response = requests.get('http://127.0.0.1:8000/api/workers/') worker = response.json() return render(request, "home.html", {'users': worker}) -
Django RestFramework api error ImproperlyConfigured at /api/ using HyperlinkedModelSerializer
hi friends I'm learning Django-Rest-framework, i try t build one small API but i'm Facing Some Error i tried to solve but i can't so kindly help to fix this Error i mention below code and error you can able to see here Error ImproperlyConfigured at /api/stream_list/ Could not resolve URL for hyperlinked relationship using view name "steamplatform-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. This is views.py i just create basic view code from rest_framework.decorators import api_view,APIView from rest_framework.response import Response from watchlist.models import Watchlist,SteamPlatform from watchlist.serializers import WatchlistSerializers, SteamPlatformSerializers # Create your views here. class Movie_list(APIView): def get(self,request): Watchlists = Watchlist.objects.all() serializer = WatchlistSerializers(Watchlists,many=True) return Response(serializer.data) def post(self,request): serializer = WatchlistSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) class Movie_details(APIView): def get(self,request, pk): try: movie = Watchlist.objects.get(pk=pk) serializers = WatchlistSerializers(movie) return Response(serializers.data) except Exception as e: data ={ "statuscode":401, "message":e } return Response(data) def put(self,request,pk): movie = Watchlist.objects.get(pk=pk) serializer = WatchlistSerializers(movie, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) def delete(self,request,pk): movie = Watchlist.objects.get(pk=pk) movie.delete() return Response() class Steam_list(APIView): def get(self,request): Steams = SteamPlatform.objects.all() serializer = SteamPlatformSerializers(Steams, many=True, context={'request': None}) return Response(serializer.data) … -
Django REST multiple permission class not working
I have two permission class. IsAuthorGroup will check if the user belongs from the author group and IsOwnerOrReadOnly will restrict the user to performing post and delete if he is not the object's owner. But the problem is anyone from IsAuthorGroup performing post and delete request event he isn't own of the object. How to restrict anyone from IsAuthorGroup performing post and delete request if he isn't owner of the object? here is my code: class IsAuthorGroup(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.groups.filter(name='AuthorGroup'): return True return False class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the blog. return obj.author == request.user or request.user.is_superuser class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup] -
Django CSS files not loading correctly in the application
In my Django application, I see that the code that is loaded is different from the code written in CSS files. What is the source of this change? How can it be resolved? -
How to set session with Django Rest Framework
For my Django project, I'm implementing RestAPI using DRF. To preserve some variables needed by two APIs, I wish to use a Django session. However, when I called Api2 after setting the session on Api1, it was None. Has anybody encountered it before? Thank you very much for your assistance! Here is an example of my API code: from rest_framework import viewsets class BaseViewSet(viewsets.ViewSet): @action(methods="post") def lookup(self, request): request.session['abc'] = 1 request.session.modified = True request.session.save() print(request.session.session_key) # p02sr0qlnzntagfkf9ekm8f8km4w82t4 return = {} @action(methods="post") def login(self, request): print(request.session.session_key) # None, it should be key p02sr0qlnzntagfkf9ekm8f8km4w82t4 print(request.session.get('abc') # None data = {} -
Django - Hide legend in Highcharts from Python script
I would like your help for a little project I'm doing with Django and Highcharts.js. My target: hide legend in Highcharts's chart from my script views.py From my views.py file I have managed to be able to correctly plot different types of charts. But I can't hide the legend from views.py. To give an example I have borrowed the code from this django-highcharts-example tutorial in Github. Here is the example code to replicate the behaviour of the script: views.py def ticket_class_view_3(request): dataset = Passenger.objects \ .values('ticket_class') \ .annotate(survived_count=Count('ticket_class', filter=Q(survived=True)), not_survived_count=Count('ticket_class', filter=Q(survived=False))) \ .order_by('ticket_class') categories = list() survived_series_data = list() not_survived_series_data = list() for entry in dataset: categories.append('%s Class' % entry['ticket_class']) survived_series_data.append(entry['survived_count']) not_survived_series_data.append(entry['not_survived_count']) survived_series = { 'name': 'Survived', 'data': survived_series_data, 'color': 'green' } not_survived_series = { 'name': 'Survived', 'data': not_survived_series_data, 'color': 'red', 'showInLegend': "false" } chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Titanic Survivors by Ticket Class'}, 'xAxis': {'categories': categories}, 'series': [survived_series, not_survived_series], 'plotOptions': {'column': {'showInLegend': 'false'}} } dump = json.dumps(chart) return render(request, 'index.html', {'chart': dump}) The html where I import Highcharts.js and create the charts. ticket_class_3.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Django Highcharts Example</title> </head> <body> <a href="{% url 'home' %}">Return to homepage</a> <div id="container"></div> <script src="https://code.highcharts.com/highcharts.src.js"></script> <script> … -
Django Rest Framework Nested Representation Not Showing
My models.py: class Brand(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name=_("brand name"), help_text=_("format: required, unique, max-100")) def __str__(self): return self.name class ProductOrService(models.Model): web_id = models.CharField(max_length=50, unique=True, verbose_name=_("product web id"), help_text=_("format: required, unique")) slug = models.SlugField(max_length=255, null=False, blank=False, verbose_name=_("product/service url"), help_text=_("format: required, letters, numbers, underscore or hyphen")) name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("product/service name"), help_text=_("format: required, max_length=250")) seller = models.ForeignKey(User, related_name="product_or_service", on_delete=models.PROTECT) description = models.TextField(verbose_name=_("product description"), help_text=_("format: required")) category = TreeManyToManyField(Category) is_visible = models.BooleanField(default=True, verbose_name=_("product/service visibility"), help_text=_("format: true->product is visiible")) is_blocked = models.BooleanField(default=False, verbose_name=_("product/service blocked"), help_text=_("format: true->product is blocked")) created_at = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_("date product/service created"), help_text=_("format: Y-m-d H:M:S")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("date product/service last updated"), help_text=_("format: Y-m-d H:M:S")) is_product = models.BooleanField(default=True, verbose_name=_("Is this product?"), help_text=_("format: true->product, flase->service")) users_wishlist = models.ManyToManyField(User, related_name='user_wishlist', blank=True) reported_by = models.ManyToManyField(User, related_name='reported_product', blank=True) def __str__(self): return self.name class Product(models.Model): brand = models.ForeignKey(Brand, related_name="brand_products", on_delete=models.PROTECT) show_price = models.DecimalField(max_digits=7, decimal_places=2, verbose_name=_("Cost of Product shown on the site."), help_text=_("format: max price = 99999.99")) available_units = models.IntegerField(null=False, default=0, verbose_name=_("available units")) sold_units = models.IntegerField(null=False, default=0, verbose_name=_("sold units")) product_or_service = models.OneToOneField(ProductOrService, related_name='product', on_delete=models.CASCADE, null=True) def __str__(self): return self.product_or_service.name class Service(models.Model): price_min = models.DecimalField(null=True, blank=True, max_digits=7, decimal_places=2, verbose_name=_("Minimum Cost of Service"), help_text=_("format: max price = 99999.99")) price_max = models.DecimalField(null=True, blank=True, max_digits=7, decimal_places=2, verbose_name=_("Maximum Cost of … -
Django problem if language string not in url
My Django site returns 404 if a language string is not attached to the URL as : https://web-***-uw.a.run.app However, when the language string is set, the page loads just fine. https://web-***-uw.a.run.app/en/ I am using Django i18n translation this way: urlpatterns = i18n_patterns( path("i18n/", include("django.conf.urls.i18n")), path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), path("", include("core.routes.urls", namespace="resumes"), name="resumes"), path("admin/", admin.site.urls), ) and my setting files language settings: TIME_ZONE = "Asia/Seoul" USE_I18N = True USE_L10N = True USE_TZ = True # Translate files LOCALE_PATHS = [ os.path.join(BASE_DIR, "locale"), ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", # Cors Headers App "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", # End Cors Headers App "django.middleware.locale.LocaleMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] I must be doing something wrong. What is it? -
Cannot add dynos on Heroku (usingDjango app)
Struggling to get my app available on Heroku. Which is strange because it used to work. When querying the error ("heroku logs --tail), this is what I get "at=error code=H14 desc="No web processes running" method=GET path="/"" I searched the problem and looks like I am not running any web dynos. I therefore, went with the following $ heroku ps:scale web=1 Unfortunately, I then came across the following error message: "Scaling dynos... ! ! Couldn't find that process type (web)." When checking with "heroku ps",it does say No dynos on "AppName" The Heroku webiste advises that this is related to the Procfile, which mine seem to be correct: Procfile web:gunicorn mysite.wsgi I have removed the buildpacks as suggested using heroku buildpacks:clear I retried to add some dynos, but still no joice. Would anyone be able to know tell me what I am doing wrong here? Did I miss a step? -
How to create and download a zip file with a list of images?
Here I have list of images with their url. I want to create a zip and store all the images inside zip. After extract the zip file I want the images inside folder. What's happening with the below code is: it creates zip and downloads but when I extract the zip file, there are so many folders like zipfoldername/home/user/my_project/img and only inside img folder there are files. I want is only zipfoldername/img. Also inside img folder files doesn't have images it has image_url only. I want to store image from that image url in the extracted file. image_list = ['https://example.com/media/file1.jpg', 'https://example.com/media/file2.jpg'] folder = os.path.join(settings.BASE_DIR, "imgs") if not os.path.exists(folder): os.mkdir(folder) for i, imgfile in enumerate(image_list): with open(os.path.join(folder, str(i)), 'wb+') as f: f.write(imgfile) response = HttpResponse(content_type='application/zip') s = StringIO.StringIO() zip_file = zipfile.ZipFile(s, "w") folder_files = os.listdir(folder) for filename in folder_files: file = os.path.join(folder, filename) zip_file.write(file) zip_file.close() resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=gik.zip' return resp -
Django - Trouble authenticating with a 2 form view (one is a login screen)
I'm attempting to create a login screen that features a search bar at the top. When attempting to log in, I receive this error: "'CustomAuthenticationForm' object has no attribute 'login'". I followed the advice in this post here. Here's my html: <form class="text-2xl" method="POST"> {% csrf_token %} {{ forms.login|crispy }} <button value="login" name="action" class="text-white flex text-xl mx-auto mt-4 max-h-10 stone-bg stone-bevel px-2 pt-1 drop-shadow-md hover:text-amber-200" type="submit"> Login </button> </form> Here's a link to the gist for my MultiFormsView class here. Here's my views: class CustomLoginView(MultiFormsView): form_classes = { 'login': CustomAuthenticationForm, 'search': SearchForm, } success_url = reverse_lazy('home') template_name = 'login.html' def get_context_data(self, **kwargs): context = super(CustomLoginView, self).get_context_data(**kwargs) context['search'] = SearchForm context['login'] = CustomAuthenticationForm return context def login_form_valid(self, form): return form.login(self.request, redirect_url=self.get_success_url()) Here's my forms: class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField( label = "", widget = forms.TextInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black my-1", 'placeholder': "Username *", 'size': "35", }) ) password = forms.CharField( label = "", widget = forms.PasswordInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black my-1", 'placeholder': "Password *", 'size': "35", }) ) class Meta(AuthenticationForm): model = CustomUser fields = ('username', 'password',) After looking into the inherited classes of AuthenticationForm, I didn't find a ".login()" method. … -
How do i add a display filter on queryset received on page with filtering options on a siderbar?
This is view function-based view for the page q=Q() context={'p_qtn':None,'h_qtn':None,'hu_qtn':None} p_qtn=request.GET.get('check1',None) h_qtn=request.GET.get('check3',None) hu_qtn=request.GET.get('check2',None) if p_qtn: q = q & Q(PQtn="None") context['p_qtn']=True if h_qtn: q = q & Q(HQtn="None") context['h_qtn']=True if hu_qtn: q = q & Q(HuQtn="None") context['hu_qtn']=True vessel=request.GET['vessel'] query_args={ f'{vessel}__exact':True} questions = ( Qtion.objects .exclude(q) .filter(**query_args) ) context['questions']=questions return render(request,'ques.html',context) class code: class Qtion(models.Model): Chapter=models.CharField(max_length=3) Stext=models.CharField(max_length=100) Ftext=models.CharField(max_length=400) Qno=models.CharField(max_length=10) HQtn=models.CharField(max_length=30) PQtn=models.CharField(max_length=30) HuQtn=models.CharField(max_length=30) Qtype=models.CharField(max_length=10) Chemical=models.BooleanField() LNG=models.BooleanField() LPG=models.BooleanField() Oil=models.BooleanField() Conditional=models.BooleanField() I want to add display filter by chapter on a siderbar. Code for the page: {% for question in questions %} <div class="question-div"> <div class="top-bar"> <div class="q-code">{{question.Qno}}</div> <div class="short-text">{{question.Stext}}</div> </div> <div class="middle-bar"> <span>{{question.Ftext}}</span> </div> <div class="bottom-bar"> {% if p_qtn %} {% if question.PQtn == 'Graduated' %} <div class="res"> <div class="res-d">Procedure Response</div> <div class="res-dr"><input type="range" id="grad" min="0" max="3" step="1"></div> <div class="res-dr"><span class="trans-text">Move slider..</span></div> </div> {% elif question.PQtn == 'Binary' %} <div class="res"> <div class="res-d">Procedure Response</div> <div class="res-dr"><input type="range" id="bin" min="0" max="1" step="1"></div> <div class="res-dr"><span class="trans-text">Move slider..</span></div> </div> {% endif %} {% endif %} {% if h_qtn %} {% if question.HQtn == 'Graduated' %} <div class="res"> <div class="res-d">Hardware Response</div> <div class="res-dr"><input type="range" id="grad" min="0" max="3" step="1"></div> <div class="res-dr"><span class="trans-text">Move slider..</span></div> </div> {% elif question.HQtn == 'Binary' %} <div class="res"> <div class="res-d">Hardware Response</div> <div class="res-dr"><input type="range" … -
Selecting one row from Foreign Key in Django
I have the following models in Django: class Kingdom(models.Model) : class Meta: ordering = ('kingdom_name', ) kingdom_name = models.CharField(max_length=128, null=True, blank=True) def __str__(self) : return self.kingdom_name class Phylum_Clade(models.Model) : class Meta: ordering = ('phylum_name', ) phylum_name = models.CharField(max_length=128, null=True, blank=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.phylum_name class Classe_Clade(models.Model) : class Meta: ordering = ('classe_name', ) classe_name = models.CharField(max_length=128, blank=True, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.classe_name class Ordre(models.Model) : class Meta: ordering = ('ordre_name', ) ordre_name = models.CharField(max_length=128, blank=True, null=True) classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.ordre_name class Famille(models.Model) : class Meta: ordering = ('famille_name', ) famille_name = models.CharField(max_length=128, blank=True, null=True) ordre = models.ForeignKey(Ordre, on_delete=models.CASCADE, null=True) classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.famille_name class Binomiale(models.Model) : class Meta: ordering = ('binomiale', ) nom = models.CharField(max_length=128, blank=True) name = models.CharField(max_length=128, blank=True) binomiale = models.CharField(max_length=128, blank=True) famille = models.ForeignKey(Famille, related_name='famille_names', on_delete=models.CASCADE, null=True) ordre = models.ForeignKey(Ordre, related_name='ordre_names', on_delete=models.CASCADE, null=True) classe_clade = models.ForeignKey(Classe_Clade, related_name='classe_names', on_delete=models.CASCADE, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, related_name='phylum_names', on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, … -
Djano UpdateView not rendering modelForm
I have a model assesment which is related to other models. i have created a UpdateView, Form based on the model assesment. The problem now is when I render the form in a template, no field is displayed except the submit button, so there is nothing to update. i only see a submit button with no form fields Here designs below models.py class assessment(models.Model): className = models.ForeignKey(all_class, on_delete=models.SET_NULL, null=True) student = models.ForeignKey(students, on_delete=models.SET_NULL, null=True) subjectName = models.ForeignKey(allsubject, on_delete=models.SET_NULL, null=True) firstCa = models.IntegerField(default=0) secondCa = models.IntegerField(default=0) exam = models.IntegerField(default=0) section = models.CharField(max_length=100, choices=section_choices) term = models.CharField(max_length=100 , choices=term_choices) session = models.CharField(max_length=1000) date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.className) class Meta: ordering = ['className'] views.py class assessmentEntry(UpdateView): model = assessment fields = '__all__' Form_class = AssessmentForm template_name = 'result/assessmentScore.html' success_url = reverse_lazy('result:index') Forms.py class AssessmentForm(forms.ModelForm): class Meta: model = assessment fields = ['className','student','subjectName','firstCa','secondCa','exam'] urls.py path('assessmentScores/<int:pk>/', assessmentEntry.as_view(), name='assessmentScores'), template(assessmentScore.html) <div > <form method="POST"> {% csrf_token %} {{ Form.as_p}} <button type="submit" class="px-2 text-white bg-indigo-500 rounded-md focus:bg-indigo-600 focus:outline-none"> Save Scores </button> </form> </div> Please what exactly am I doing wrong? and how do I correct it. -
Django Validation - Use Parent field validator and have subclass provide values
I have an abstract Parent model, and the subclasses inherit a field that has a validator. The validator takes in a list, and I would like each child to provide it's own list to validate against. I have something like this. Is there a way to do this? Am I over complicating it? app1.py @deconstrutible class ValidateInList(): def __init__(self, valid_items): self.valid_items = valid_items def __call__(self, value): if value not in self.valid_items: raise ValidationError() class Parent(models.Model): field = models.CharField(max_length=20, validators=[ValidateInList(something)]) class Meta: abstract = True app2.py class Child1(Parent): child_valid_items = [x,y,z] # would take the value of 'something' in Parent class class Child2(Parent): child_valid_items = [a,b,c] # would take the value of 'something' in Parent class -
How to save wallet address to user model in Django?
I have run into a bit of a hiccup here. I have a script which gets the user's Metamask wallet address which works fine. The problem arises when I need to save that wallet address to the user model in this field: ethereum_address = models.CharField(max_length=42, blank=True, null=True) I have a Javascript that fetches the wallet when the Connect button is pressed: function connect() { ethereum .request({ method: 'eth_requestAccounts' }) .then((account)=> saveAccount(account)) .catch((error) => { if (error.code === 4001) { // EIP-1193 userRejectedRequest error console.log('Please connect to MetaMask.'); } else { console.error(error); } }); } function saveAccount(account) { console.log(account); $.ajax({ url: '/connect-metamask/', type: 'POST', data: { 'account': account, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, }); } In the views.py I have this when I have a POST request: def connect_metamask(request): user = request.user if request.method == "POST": user.ethereum_address = request.POST.get("account") user.save() ......... But when I look at the database the ethereum_address is Null . How do I make this work?