Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create or update a model with Django REST Framework?
I would like to create or update a model Account by specifying the fields id and params with the REST Framework. To begin with, I try to create the model but I'm constantly getting 400 or 500 error code. What am'I missing? client data = dict(id=18, params=dict(foo='bar')) res = requests.post('http://container-django-1:8002/api/account/', data=data, headers={'Authorization': 'Bearer {0}'.format(instance.bookkeeper.jwt_token)} ) server models.py class Account(TimestampedModel): active = models.BooleanField(null=True, blank=True, default=False) params = models.JSONField(default=dict, blank=True) views.py class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer queryset = Account.objects.all() http_method_names = ['post'] serializer.py class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('id', 'params',) def create(self, validated_data): return Account.objects.create(id=validated_data['id'], params=validated_data['params']) urls.py router = routers.DefaultRouter() router.register("account", AccountViewSet, basename="accounts-list") urlpatterns = [ path('', include(router.urls)), ] Output container-django-1 | 2022-09-03T18:14:22.785593661Z Starting development server at http://0.0.0.0:8002/ container-django-1 | 2022-09-03T18:14:22.785604944Z Quit the server with CONTROL-C. container-django-1 | 2022-09-03T18:17:09.252092179Z Bad Request: /api/account/ container-django-1 | 2022-09-03T18:17:09.253001155Z Bad Request: /api/account/ container-django-1 | 2022-09-03T18:17:09.261351802Z [03/Sep/2022 18:17:09] "POST /api/account/ HTTP/1.1" 400 40 -
Download and Install Software Application to client machine from hosted web application Django
I was working on scripts, I have added exe file to azure storage I have provided URL link on website, once local user click on that link, he should able to download and install application on his local machine. its was working fine when it was on development step because I was testing this on local webserver, once I hosted it was not working, It was downloading exe files on hosted virtual machine. if you guys have any idea or suggestions it would helps me alot, @login_required(login_url='/') def runcmd(request): import os import subprocess import getpass if request.method == 'POST': if 'app_url' in request.POST: app_dw_link = request.POST.get('app_url') app_obj = get_object_or_404(AppStore, id=int(app_dw_link)) url = app_obj.app_file.url usrname = getpass.getuser() messages.success(request, usrname) folder = 'Temp' dir_path = os.path.dirname(os.path.realpath(__file__)) messages.success(request, dir_path) destination = f"C:\\Users\\{usrname}\\AppData\\Local\\{folder}" if not os.path.exists(destination): os.makedirs(destination) destination = f'C:\\Users\\{usrname}\\AppData\\Local\\{folder}\\{app_obj.app_name}.exe' #add switches download = urlretrieve(url, destination) messages.success(request, download) subprocess.Popen([destination, '/Silent'], shell=True, stdout=subprocess.PIPE) else: destination = f'C:\\Users\\{usrname}\\AppData\\Local\\{folder}\\{app_obj.app_name}.exe' #add switches download = urlretrieve(url, destination) messages.success(request, download) subprocess.Popen([destination, '/Silent'], shell=True, stdout=subprocess.PIPE) messages.success(request, 'Download completed') return redirect("selfservice:it_store") -
How to solve .accepted_renderer not set on Response Error on POST Request, Django
got a problem when trying to call request using Postman, on POST request always get AssertionError at /v1/facility/33/court/ .accepted_renderer not set on Response Request Method: POST Request URL: On Get request other endpoints works fine. Django version - 3.2.15 Class that responsible for this endpoint already have APIView class class ItemAPIView( CSRFEnabledApiViewMixin, CreateAPIView, RetrieveUpdateDestroyAPIView): Even If I put APIView class as last nested class it not working. Who can help with this? what is wrong? Note: if I will doing curl request to such endpoint POST - error is the same -
OrderedDict in Django tests
I have such Django tests queryset = SomeModel.objects.all() response = self.client.get("some_url") serializer = SomeSerializer( instance=list(queryset[:10]), many=True ) self.assertEqual( serializer.data, response.json()["results"], ) And got such error E AssertionError: [OrderedDict([('uuid', 'e58fecc0-d559-41af[23258 chars]))])] != [{'uuid': 'e58fecc0-d559-41af-993b-9519309[17732 chars]0.0}] How can be OrderedDict be removed or transformed? -
Django convert CBV to json
I have this CBV class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' Im using _set to display all users data to staff. But I need to use the data for calculations, how can I convert this to json -
Is their any way to practice back-end? [closed]
How can I practice back-end? Is there any website where I can find front-end and attach back-end by my-self? -
DJANGO {{form.errors.title.as_text}} not working
a I have been watching a video which uses the following code to show errors. {% if form.errors %} <div class="alert alert-danger"> {{form.errors.title.as_text}} </div> {% endif %} But when I use it no errors show If I use: {% if form.errors %} <div class="alert alert-danger"> {% for error in form.errors %} <p>{{ error }}</p> {% endfor %} </div> {% endif %} I get a single word eg. 'email' but the whole error text does not display. It works fine on the video, Could anyone tell me what i am doing wrong? -
Django OperationalError when creating django_content_type table
With local MySQL was fine, but with the production is the error. After this error I see only the following tables in the database: auth_group, auth_group_permissions, auth_permission, django_content_type and django_migrations Operations to perform: Synchronize unmigrated apps: djoser, messages, rest_framework, staticfiles Apply all migrations: account, admin, auth, authtoken, blog, commands, contenttypes, faq, servers, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial...Traceback (most recent call last): File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Program Files\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute return self.cursor.execute(query, args) File "C:\Program Files\Python310\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Program Files\Python310\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Program Files\Python310\lib\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.OperationalError: (1142, "REFERENCES command denied to user 'test_user'@'22.161.40.219' for table 'django_content_type'") -
How do I add the path to python for vscode
My util.py file is sited at the same directory with views.py, why do I still have the ImportError: ImportError -
DJango Generic date views filtering
Hello I really need help with date views. I need a prediction based view on date. I have users and staff, users have their views while staff can see everything what a user did in their view right now I have a Dashboard for staff where they can choose the view of a user class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' the view {% for Ansicht in Dashboard %} <tbody> <tr> <th scope="row"></th> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.Konto}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.Schulname}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.SAB}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.GL}}</a></td> <td><a href="{% url 'Ansicht' Ansicht.Benutzer.pk %}">{{Ansicht.Teilstandort}}</a></td> </tr> </tbody> {% endfor %} Now when they view one view all the data that is show is a _set from user model (that is also why I just cant use simple django filter bc it is a set and I dont know how to filter only the set but thats just a side note) class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' the view in short {% for Ansicht in Ansicht.schulverzeichnistabelle_set.all %} {{Ansicht.Konto}} {{Ansicht.S_Form}} {{Ansicht.Schulname}} {{Ansicht.SAB}} {{Ansicht.GL}} basically the same, but not all entries … -
Multiple widgets for one form field in Django
I have the following form: class ExcipientForm(ModelForm): class Meta: model = Excipient fields = ( "Excipient_type", "Excipient_concentration", ) widgets = { 'Excipient_type': Select(attrs={ 'style' : 'width:100%;', 'class' : 'dropdowns', }), 'Excipient_concentration': TextInput(attrs={ 'class': 'slider', 'type': 'number', 'value':"20", 'max':"100", 'step': "0.1", 'id':"excipient_concentration" } ) } ExcipientFormSet = inlineformset_factory( Parameters, Excipient, ExcipientForm, can_delete=False, min_num=1, extra=0 ) This is the template to post to the form: <form action="" id="form-container" method="POST"> {% csrf_token %} <div class='row'> <div class='col'> <label for="id_API_batch_number" class="form-label">API batch number : </label> </div> <div class='col'> {{ parameter_form.API_batch_number }} </div> </div> <hr class="my-4"> <div class='excipient-form'> {{ excipient_form }} {{excipient_form.id.auto_id}} <input type="range" class="slider" name="slidervalue" value='20' max="100" step="0.1" onchange="updateTextInputRange(this.value);"> </div> <button id="add-form" type="button">Add Excipient</button> <hr class="my-4"> <label for="num6" class="form-label">Total Concentration: </label> {{ parameter_form.Total_concentration }} <br></br> <input type="submit" id="submit" class="btn btn-primary" value="Submit"> </form> I'm trying to get the sliders and it's corresponding number field to "sync". This is the JS I have at the moment. //Update Textbox value from slider value function updateTextInputRange(val) { document.getElementByID('excipient_concentration').value = val; // text input //checkValueSum(); } Some of the things I tried: Finding out the ID for each instance of the slider and number input. This failed as every instance has the same ID. Tried using multiple widgets in … -
How to fix 8000 port is already in use django runserver problem?
I am trying to run Django project in ubuntu 20.04 LTS but it shows 8000 port already in use. I can run using> python manage.py runserver 8080 But I want to free my 8000 port How can I do that? (env) amol@amol-Ideapad-320:~/My Code/Python/ecommerse-models/ecomm$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 03, 2022 - 15:12:45 Django version 4.1, using settings 'ecomm.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. -
How to save pillow processed image in already existing Django object
I have created a object model as below from django.db import models # Create your models here. class ImageModel(models.Model): image = models.ImageField(upload_to='images/') editedImg = models.ImageField(upload_to='images/') def delete(self, *args, **kwargs): self.image.delete() self.editedImg.delete() super().delete(*args, **kwargs) And here is what i am trying to do in a function from django.shortcuts import render from EditorApp.forms import ImageForm from EditorApp.models import ImageModel from django.http import HttpResponseRedirect from PIL import Image def edit_column(request): codArr = request.POST.getlist('codArr[]') imgs = ImageModel.objects.first() orgImage = ImageModel.objects.first().image orgImage = Image.open(orgImage) croppedImg = orgImage.crop((int(codArr[0]), int(codArr[1]), int(codArr[2]), int(codArr[3]))) # croppedImg.show() # imgs.editedImg = croppedImg # imgs.save() return HttpResponseRedirect("/editing/") What i am trying to do is the codArr consists of coordinates of top(x, y) and bottom(x, y) in the array form(Which is not an issue and is tested(croppedImg.show() showed the desired cropped image) and handled and used to crop the image). Image crop is working fine. But what i am trying to do is to save the cropped image in editedImg of the model used above. The above commented one is what i tried but throw a error AttributeError: _committed As i have not used any name for image in model as its not required. Kindly help please, Would be very thankfull. -
how to calculate rate of sale percentage for sales of product in python?
hi does anyone have sales growth source code with python? -
Object of type function is not JSON serializable in Django
I have been trying to pass this data in json format but i keep getting this error. I am getting all the data and passing it to a payment getaway for processing. But anytime I pass the data i get the error message raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type function is not JSON serializable def paytes(request): amount = 10 desc = "USSD" category = 'Robert' phone = "233244491909" vote = text slug = "test" award = "test" url = 'https://api.pays.co/charge' transaction_id = random.randint(100000000000, 999999999999) data = json.dumps({ "reference": transaction_id, "amount": amount, "phone": phone, "email":"customer@gmail.com", "mobile_money": { "phone" : "0244496709", "provider" : "MTN" }, "label" : desc, "metadata":{ "custom_fields": [ { "value": desc, "nominee_name": slug, "transaction_id": transaction_id, "amount": amount, "award": award, "category": category, "email": email, "phone": phone, "vote": vote, } ] } }) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer texk_002929992', 'Cache-Control': 'no-cache' } response = requests.post(url, data=data, headers=headers) return HttpResponse(response) -
How to determine what button was clicked in google chat bot
I can get event CardClicked but my buttons are generating on the fly, these names depend on data in db. How to get name of clicked button from request. class CardClickedEvent(Event): def __init__(self, request): super().__init__(request) self.message = request.get('message').get('text') self.space = request.get('space').get('name') @transaction.atomic def process(self): logger.info(self.request.get('type')['action']['actionMethodName']) -
Dinamic Form Validation - Django
I have a page with 3 forms, the forms are esentially the same in terms of fields but have different validation, I was wondering if instead of having multiple forms is there any way of having one form with dinamic validation, and then pass a keyword to the form to use one validation or another. Here is my forms.py: class FileTypeOneForm(forms.Form): statement = forms.FileField(label='') def clean_statement(self): statement_file = self.cleaned_data['statement_file'] # Check statement_file format and raise ValidationError in case of invalid format # ... return statement_file class FileTypeTwoForm(forms.Form): statement = forms.FileField(label='') def clean_statement(self): statement_file = self.cleaned_data['statement_file'] # Check statement_file format and raise ValidationError in case of invalid format ** required format is different than FileTypeOneForm and FileTypeThreeForm required format ** # ... return statement_file class FileTypeThreeForm(forms.Form): Options = [ ('', 'Select'), ('one', 'One'), ('two', 'Two') ] option = forms.ChoiceField(label='', choices=Options) statement = forms.FileField(label='') def clean_statement(self): statement_file = self.cleaned_data['statement_file'] # Check statement_file format and raise ValidationError in case of invalid format ** required format is different than FileTypeOneForm and FileTypeTwoForm required format ** # ... return statement_file All three forms have the same field statement_file, but with different validation, and the third form has a second field option. Currently these is views.py: … -
Django find duplicates in two tables
I am working on a database of public figures and their positions. I have the following models: class Person(models.Model): full_name = models.CharField() appointments = models.ManyToManyField('Appointment', through='PersonsNAppointments') class Appointment(models.Model): position = models.CharField() persons = models.ManyToManyField('Person', through='PersonsNAppointments') Names are not unique. So in situation when I have John Donne(id_1) and John Donne(id_2) and "John Donne" got appointed they both would get this appointment. I want to create an admin panel where only people with same names and same appointments are shown so the admin could handle these duplicates manually. I need help with writing get_queryset. So far I've figured out how to get duplicated names dup_names = Persons.objects.values('full_name')\ .annotate(name_count=Count('id'))\ .filter(name_count__gt=1).values('full_name') dup_objects = Persons.objects.filter(full_name__in=dupes_names) How to get only those persons who share same appointments? -
How can I join a thrid table to a queryset which already use select_related
I am working with Django and I need to create an API to retrieve the measures depending of three tables (image of the Schema of my tables) Measures contains all measures according to an ID of the sensors Sensors contains the sensor information and the type of the sensor sensor_types contains the information of the type (type name, unit, etc) I need to know the (at least) the sensor name and ID, the type of the sensor and the measures for the sensors. I first tried to retrieve the sensor information and the type the sensor belong to class TypeViewSet(viewsets.ReadOnlyModelViewSet): """ API: return the measures of several sensors according to a type of sensors and a date range. A type is generaly sensors with the same unit (°C, %, kPa) """ # See serializers.py serializer_class = TypesSerializer def get_queryset(self): # get the params idt = self.kwargs['idtype'] # get the date "from" start = self.request.query_params.get('start') # get the date "to" end = self.request.query_params.get('end') type = SensorTypes.objects.filter(id_sensor_type=idt) sensors = Sensors.objects.filter(sensor_types_id_sensor_type=idt)\ .select_related('sensor_types_id_sensor_type') print(sensors.query) return sensors my TypesSerializer file look like: class SensorTypeSerializer(ser.ModelSerializer): class Meta: fields = ("id_sensor_type","sensor_type_name","sensor_type_longname","measure_unit") model = SensorTypes class TypesSerializer(ser.ModelSerializer): sensor_types_id_sensor_type=SensorTypeSerializer( read_only=True ) #"sensor_type_name", "measure_unit", class Meta: fields = ("id_sensor","sensor_name","sensor_types_id_sensor_type") model … -
Why is my django-crispy AdminForm not able to resolve AdminSite url?
Setup I defined an new admin url: from django.contrib.admin import AdminSite from django.http import HttpResponse from django.urls import path class MyAdminSite(AdminSite): def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ path( "generate", admin_site.admin_view(self.my_view), name="generate", ) ] return urls def my_view(self, request): print(request.data) return HttpResponse("Hello!") admin_site = MyAdminSite() The url is successfully registered: print(admin_site.get_urls()) [ ..., ..., <URLPattern 'generate' [name='generate']>] # <-- here! Now in my django-crispy-form, I need to add a form action for multiple submit buttons. The library does not allow multiple form actions to be set, so I had to disable the form tag and add a new one manually: class PromptForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() # django-crispy-forms self.helper.form_method = 'post' self.helper.form_tag = False # <-- disable form_tag # Form layout self.helper.layout = Layout( # Add new form_tag HTML("""<form action="{% url 'admin:generate' %}"><input type="submit" class="btn btn-success" value="generate"></form>"""), ) Issue Neither {% url 'generate' %} nor {% url 'admin:generate' %} are able to reverse match the new url: `django.urls.exceptions.NoReverseMatch: Reverse for 'generate' not found. 'generate' is not a valid view function or pattern name. -
Django can't acces media files, 404 Page not found
I recently started to learn Django but I'm still struggeling with accessing media files. My settings.py file includes the following: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ My urls.py in the project directory contains the following. urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] if st.DEBUG: urlpatterns += django_Static(st.MEDIA_URL, document_root=st.MEDIA_ROOT) When I then try to load an image via a GET request I get the following message: " Page not found (404) ... Using the URLconf defined in ecommerce_project.urls, Django tried these URL patterns, in this order: admin/ [name='store_homepage'] ^media/(?P<path>.*)$ The current path, media/product_pictures/256132756_922283745365869_1303861998719790800_n.jpg, matched the last one. I really don't know what to do since I tried everything. Has someone also stumbled accross this problem? -
limit number of foreign key using Django CheckConstraint
I am using Django 4.1 and Postgresql and as stated in their documentation CheckConstraint accept Q object and Expression. Based on https://code.djangoproject.com/ticket/31646, I thought my solution would work, but when calling makemigrations nothing happens (Count inherit from Func). Goal: I would like to limit the number of Messages per Discussion. I did see a solution using a validators on the ForeignKey field but it is not robust (see Limit number of foreign keys). I would prefer not to have to create a SQL function and calling it (would like a Django solution only). from django.core.exceptions import ValidationError from django.db import models from django.db.models.lookups import IntegerLessThan class Discussion(models.Model): MAX_MESSAGES = 10 class Message(models.Model): discussion = models.ForeignKey( "discussion.Discussion", models.CASCADE, related_name="messages", ) constraints = [ models.CheckConstraint( name="limit_discussion_messages", check=IntegerLessThan( models.Count("discussion", filter=models.Q(discussion=models.F("discussion"))), models.Value(Discussion.MAX_MESSAGES), ), ), ] -
Getting null value in column "userId_id" of relation "pnrDB_run when sending a POST to django backend
Still very new to Django. I'm trying to send a post request to my backend from insomnia right now and I'm getting the error Getting null value when I'm passing in the ID value. Here is my seralizer: class RunSerialzer(serializers.HyperlinkedModelSerializer): gameId = GameSerialzer( read_only = True ) userId = UserSerialzer( read_only = True ) class Meta: model = Run fields=('id','name','isComplete','deaths','badges','userId','gameId') My view: class RunList(generics.ListCreateAPIView): queryset = Run.objects.all() serializer_class = RunSerialzer And my request I'm making: { "gameId":1, "userId": 1, "name":"testrun2", "deaths":0, "badges": 0, "isComplete": false } and the second one I tried { "gameId": { "id": 1, "name": "Vintage White", "photo": "https://archives.bulbagarden.net/media/upload/thumb/0/08/White_EN_boxart.png/250px-White_EN_boxart.png" }, "userId": { "id": 1, "name": "TestUser" }, "name":"testrun2", "isComplete": false, "deaths": 0, "badges": 0 } I feel like I need to create either a new Serailizer to get the instance I want in my Game model with the pk im passing in the request -
Django wrong imagefield.path
i have a model with an image field like this app_icon = models.ImageField(upload_to='icons/') the project has 'uploads' as media folder, which has subfolders, including 'icons'. The image is correctly uploaded to the 'icons' subfolder but when i try to access it using self.app_icon.path it returns .../uploads/imagename.jpg instead of .../uploads/icons/imagename.jpg so i get file not found error. Even the url doesn't include the 'icons' subfolder my settings: MEDIA_URL = '/uploads/' MEDIA_ROOT = BASE_DIR / 'uploads/' i can't find any answer to this problem, which seems so random to me. -
how to make models for user auth(use abstract user) for login and signup using django?
how to make models for user auth(use abstract user) for login and signup using Django? I want to make login OTP based for ecommerse website. from django.db import models class User(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) mobile = models.CharField(max_length=10) address = models.CharField(max_length=200) emailId = models.CharField(max_length=50) password = models.CharField(max_length=200) I tr above code. What should I have to add above?