Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
serializer method to set the value of an attribute doesn't work in a post request. I am using Django Rest Framework
I have a model which has an attribute "transaction_id" which is a customized ID field and it's value has to be calculated in order to be saved in the database. I have a model: class Transaction(models.Model): field = models.IntegerField(default=0) transaction_id = models.UUIDField(unique=True) This is the seriaizer: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = '__all__' read_only_fields = ['id', 'transaction_id'] def set_tn_number(self): tn_number = "some_string/" #I have to perform some calculation in order to get the relevant value tn_number = tn_number + str(10) return tn_number Now in my post method of the view, i am performing the following: def post(self, request): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.tn_number = serializer.set_tn_number() serializer.save() message = {'message': "Transaction Created Successfully"} return Response(message, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) But i am still getting integrity error: NOT NULL constraint failed: transaction_transaction.transaction_id Can someone please help me with this? Thank you for your time -
Task freezes Celery + django + supervisor + redis
I've a Django app served by Gunicorn with Celery using celery-beat that's being launched by Supervisord Celery task hangs sometimes(maybe once a week) Software versions: Redis server v=4.0.9 celery 5.1.2 django 3.2 django-celery-beat 2.2.1 I put configuration files here https://gist.github.com/SergSm/43a1554b57968c5e35776ad55fdcf0ab What I do Everytime task freezes I run celery -A app inspect active to see an id of a frozen task so then I run python manage.py shell in my django directory to see a state of the running task >>> from app.celery import app >>> from celery.result import AsyncResult >>> result = AsyncResult(id='9bf01312-c2ff-4b1e-9fd5-6fa6b0c458f2', app=app) >>> result.state 'PENDING' the task is pending and can't be finished even by executing sudo supervisorctl stop latest_conf_celery so I have to kill -9 all Celery processes I've a suspicion that the reason can be in the name of the worker spawned by gunicorn. I made this conclusion due to the fact when I execute ps -aux | grep celery I see: serg 8641 0.2 8.4 262284 84948 ? Sl 10:09 0:05 /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/python /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/celery -A app worker -P threads --beat -S django.schedule -l INFO serg 8643 0.0 7.6 185800 76804 ? S 10:09 0:01 /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/python /home/serg/.cache/pypoetry/virtualenvs/latest-config-1c-lST7exov-py3.9/bin/celery -A app worker -P threads --beat -S django.schedule -l … -
Django - trying to use a queryset to create a queryset on a different model
I want to create a queryset for my model Student. I then want to use the students from this queryset to create a new queryset for my model DoNotPick. models: class Classroom(models.Model): classroom_name = models.CharField(max_length=30) students = models.ManyToManyField(Student) def __str__(self): return self.classroom_name class Student(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student_first = models.CharField(max_length=30) fullname = models.CharField(max_length=60) class Meta: ordering = ['student_first'] def __str__(self): return self.fullname class DoNotPick(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) do_not_pick = models.BooleanField(default=False) student = models.ForeignKey(Student, on_delete=models.CASCADE) The first queryset I create is: s = Student.objects.filter(classroom = some_pk) One thing I tried which didn't work is (from here in the docs): values = s.values_list('pk', flat=True) dontpick = DoNotPick.objects.filter(student__in=list(values)) On my development db, s returns 18 objects which is expected. However, dontpick seems to return all objects, it's not getting filtered. It returns all 26 objects in the db. I had some success with this view, I know that the donotpicks set is the correct size (18 objects): def donotpick(request, classroom_pk): classblock = get_object_or_404(Classroom, pk=classroom_pk) students = Student.objects.filter(classroom=classblock) dnp = DoNotPick.objects.all() donotpicks = set() for s in students: donotpicks.add(dnp.filter(student=s)) print(len(donotpicks)) DoNotPickFormSet = modelformset_factory( DoNotPick, fields=('do_not_pick',), extra=0) formset = DoNotPickFormSet(request.POST, queryset=donotpicks) if request.method == 'POST': formset = DoNotPickFormSet(request.POST, queryset=donotpicks) if formset.is_valid(): … -
ImportError: Could not import 'users.authenticate.jwt_response_payload_handler' for API setting
Set custom return error when using rest framework jwt token verification,ImportError: Could not import 'users.authenticate.jwt_response_payload_handler' for API setting 'JWT_RESPONSE_PAYLOAD_HANDLER'. users.authenticate def jwt_response_payload_handler(token, user=None, request=None): return { 'code': status.HTTP_200_OK, 'data': token, 'message': 'Success' } setting JWT_AUTH = { # Token失效时间 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7), # Token前缀 'JWT_AUTH_HEADER_PREFIX': 'JWT', # response中token的payload的部分处理函 'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.authenticate.jwt_response_payload_handler' } At that time commented out 'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.authenticate.jwt_response_payload_handler' can successfully run to obtain token Traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site- packages\rest_framework\settings.py", line 177, in import_from_string return import_string(val) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\lk\r\python\r\users\authenticate.py", line 4, in <module> from rest_framework_jwt.views import ObtainJSONWebToken ImportError: cannot import name 'ObtainJSONWebToken' from partially initialized module 'rest_framework_jwt.views' (most likely due to a circular import) (C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_jwt\views.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) … -
django 'Loginform' object has no attributes get_user
i have multiuser type app with usertype and usertype b i am trying to create a loginform where most of of login is and should be in form am getting this error forms.py class Loginform(forms.Form): username = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") try: user = models.User.objects.get(username=username) if user.user_a: if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError("Password is wrong.")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError("User does not exist.")) views.py class UseraView(LoginView): template_name = 'login.html' form_class = Loginform success_url = reverse_lazy("home") Note:There are some other stack post related to this which didn't help as those are for single type user here in my case it is multi user application so please dont provide any related links -
How I can check whether a user's email is verified or not in the Django template
I am using Django all auth, to implement email-based login, I am able to verify users with confirmation email but I want to render a conditional template for verified users, I tried this but it didn't work. {% if user.email_verified %} verified {%else%} not verified {%endif%} -
Sortable JS breaks upon htmx rendering a partial
I am trying to implement a drag and drop sortable list using SortableJS and htmx. I have it working once, but after dragging and dropping the first element (and the partial being re rendered) I can no longer use the drag and drop functionality. When a partial isn't rerendered the drag and drop functionality works as expected. I have tried using htmx.on("htmx:load",... as well as putting the script in the partial. I've used diff to check the differences between the html before and after the partial is rendered and as far as I can tell the only difference outside the reordered list is the csrf token. Any help would be appreciated! From views.py: def sort(request): event_pks_order = request.POST.getlist('event_order') events=[] for idx,event_pk in enumerate(event_pks_order,start=1): event = Event.objects.get(pk=event_pk) event.event_number = idx event.save() events.append(event) return render(request,'timing/partials/eventlist.html',{'events':events}) From eventlist.html: <form class="sortable list-group" hx-trigger="end" hx-post="{% url 'sort' %}" hx-target="#event-list"> {% csrf_token %} <div class="htmx-indicator">Updating...</div> {% for event in events %} <div> <input type="hidden" name="event_order" value="{{event.pk}}"/> <li class="list-group-item">{{event.event_number}} {{event.event_name}} </li> </div> {% endfor %} </form> From base.html: <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) htmx.onLoad(function(content) { var sortables = content.querySelectorAll(".sortable"); for (var i = 0; i < sortables.length; i++) { var sortable … -
Gunicorn Error when deploying python app on Contabo server unrecognized arguments
Dec 13 03:25:40 vmi720345.contaboserver.net systemd[1]: Started gunicorn daemon. Dec 13 03:25:41 vmi720345.contaboserver.net gunicorn[30601]: usage: gunicorn [OPTIONS] [APP_MODULE] Dec 13 03:25:41 vmi720345.contaboserver.net gunicorn[30601]: gunicorn: error: unrecognized arguments: -access-logfile /run/gunicorn.sock textutils.wsgi:appliction Dec 13 03:25:41 vmi720345.contaboserver.net systemd[1]: gunicorn.service: Main process exited, code=exited, status=2/INVALIDARGUMENT Dec 13 03:25:41 vmi720345.contaboserver.net systemd[1]: gunicorn.service: Failed with result 'exit-code'. root@vmi720345:~/projectdir# client_loop: send disconnect: Connection reset by peer -
Problem with response values with join in django query?
i have this models. class Product(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) PublicationDate = models.DateField() trend = models.IntegerField() class User_list(models.Model): product_id = ForeignKey(Product, on_delete=models.CASCADE) userid = models.IntegerField() i make a join query with select related data = User_list.objects.select_related('product_id') but the response don't get me Product fields value. it's get me only User_list values, like this "[{\"model\": \"app.user_list\", \"pk\": 1, \"fields\": {\"product_id\": 11916, \"userid\": 9}}]" What's the problem? -
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