Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up a Django web scraper using selenium
I'm a high school teacher trying to build a web scraper for other staff members to use. I want to use Django to build the UI, and then use Selenium to scrape a few password protected sites. I'm not sure how to configure Django and Selenium so that when other teachers use the app, the correct web driver is installed. I guess my question is this: how do I get the Django app to detect what browser other users are using, and then choose the appropriate web driver? Cheers. -
Django: TypeError: expected string or bytes-like object when assigning a datetime object to a DateTimeField
I'm running into a really strange issue with the Django ORM. I have a model with a DateTimeField declared like so: class AvailabilityRecord(models.Model): class Meta: ordering = ['pk'] publication_date = models.DateTimeField(auto_now_add=True) And am assigning a value to publication date like so: avail_record, created = AvailabilityRecord.objects.get_or_create( publication_date=datetime(2015, 10, 9, 23, 55, 59, 342380) ) When I try to do this, I receive the error: File "/opt/homebrew/lib/python3.9/site-packages/django/utils/dateparse.py", line 107, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object It appears Django doesn't accept datetime objects for the DateTimeField, which I find strange. Is this actually the case, that I need to convert it to a string every time before assigning a value? I am using Django 3.2.12 -
How can I fix this error "premium is not one of valid choices please select valid choice" from drop down in django?
Context: I was able to set a user to PREMIUM from the admin panel but after resetting the database I see this error. I'm unable to figure out what's going on or how to fix it. The error is: "Select a valid choice. PREMIUM is not one of the available choices". Here is code for my Profile class: class Profile(models.Model): PREMIUM_CHOICES = (("FREE",0),("PREMIUM",1)) user = models.OneToOneField(User,primary_key=True,on_delete=models.CASCADE) premium = models.IntegerField(choices=PREMIUM_CHOICES,default=0) due_date = models.DateField(null=True) I've looked at several answers on Stackoverflow: MongoDB database. Error "Select a valid choice. That choice is not one of the available choices." Here is screen capture of the error: -
I want to place a placeholder in my forms textarea in Django
I want to write a placeholder at the end of the textarea says: '*required'. How can I do this for my fields? forms.py class CustomerForm2(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') } -
Django-filter error: 'Meta.fields' must not contain non-model field names
I am working with Django REST framework and django-filters and and I'd like to use the reverse relationship annotation_set as one of filters for a GET API that uses the model Detection. The models are the following: class Detection(models.Model): image = models.ImageField(upload_to="detections/images") def local_image_path(self): return os.path.join('images' f"{self.id}.jpg") class Annotation(models.Model): detection = models.ForeignKey(Detection, on_delete=models.CASCADE) attribute = models.CharField(max_length=255) The serializer is: class DetectionSerializer(UniqueFieldsMixin, serializers.ModelSerializer): local_image_path = serializers.CharField() class Meta: model = Detection fields = '__all__' And the viewset is: class DetectionTrainingViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Detection.objects.all() serializer_class = DetectionSerializer filterset_fields = ('annotation_set__id', ) @action(methods=['GET'], detail=False) def list_ids(self, request): queryset = self.get_queryset() filtered_queryset = self.filter_queryset(queryset) return Response(filtered_queryset.values_list('id', flat=True)) When I make a call to the endpoint, I get the error: 'Meta.fields' must not contain non-model field names: annotation_set__id Shouldn't the field exist? Note: I tried to add other fields to the Annotation model and then use annotation_set__newfield but I still have the error. I can confirm that the newfield exists because it is correctly serialized and return by the API when I comment out the line that set the filterset_fields. -
Django server not starting after importing python project as package
I have a deep learning python project named 'predict'. I want to use it in my django views so I use from predict.Prediction import Prediction where predict = root directory of python project, Prediction.py is the file that I need to use. Whenever I run python manage.py runserver, I get the error as: Server not starting issue. I have the init file in the root folder predict (python project) structure. I am stuck on this from long and clueless as to what is the issue. -
CSS grid using DIVs that works on local server not wotking when uploded to Django site
I am trying to create a CSS grid using DIVs to display a row of 3 boxes. <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> html { font-size: 22px; } body { padding: 1rem; background-color: rgba(2, 26, 63); } .card { background-color: rgba(24,109,238, 0.7); transition: 0.5s; border-radius: 10px; color: white; padding: 1rem; height: 4rem; } .card:hover{ box-shadow: 0 0 20px 0px rgba(80, 230, 236, 0.8); } .card h3{ text-align: center; } .cards { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 1rem; font-size: small; } /* Screen larger than 600px? 2 column */ @media (min-width: 600px) { .cards { grid-template-columns: repeat(2, 1fr); } } /* Screen larger than 900px? 3 columns */ @media (min-width: 900px) { .cards { grid-template-columns: repeat(3, 1fr); } } </style> </head> <body> <Div class="cards"> <Div class="card" onclick="window.location='opnotener'"> <h3>NLP-NER 4 Op Notes</h3> <P>Natural Lanugage Processing - Named Entity Rrecognition tool for surgical Procedure Notes.</P> </Div> <Div class="card" onclick="window.location='#'"> <h3>Surgical EPR</h3> <P>Surgical EPR that covers the entire surgical landscape with sub-speciality pipeleines.</P> </Div> <Div class="card" onclick="window.location='opnoteannotator'"> <h3>Op Note Annotator</h3> <P>Surgical procedure notes Annotator with drag and drop speciality specific entities.</P> </Div> </Div> </body> </html> The intended output should be like below and … -
Using custom font in django Css
I'm trying to use a custom font in my Django app. Here are the relevant lines from my base.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'recipebook/style.css' %}"> Here are my relevant lines from the css file: @font-face { font-family: "FiraCode-Retina"; src: url("fonts/FiraCode-Retina.ttf") format("truetype"); } Here is my file structure: My CSS is working except for the font. What steps am I missing to get this working? -
QuerySet basic methods typing
Lets say i have a model Event, i want Event.objects.filter(blablabla) to return a QuerySet[Event], not just a QuerySet. For this purpouse, i created a Manager. I need the manager in a separate file, since i have many Managers. So an ideal thing to do would be something like class EventManager(models.Manager): def filter(self, *args, **kwargs) -> QuerySet[Event]: return super().filter(*args, **kwargs) But i can't import the Event model, since it would be a circular import (Event.objects is the EventManager). How can i provide type hints for the filter and get functions?. -
Django Jinja template display value from dictionary key
I have problem to display data in jinja template. I have a dictionary which looks like: data = { 'Game1': {'win': 0, 'lost': 2, 'all': 2}, 'Game2': {'win': 1, 'lost': 0, 'all': 1}, 'Game3': {'win': 2, 'lost': 0, 'all': 2} } This dictionary is passed to template as game_details. I want to display this data like: Game: Game1 Win: 0 Lost: 2 All: 2 Game: Game2 Win: 1 Lost: 0 All: 1 Game: Game3 Win: 2 Lost: 0 All: 2 Using python there is no problem, because I can call data by key, but in my template I'm trying to call them like: {% for key, value in game_details.items %} Game: {{ key }}<br/> Win: {{ value['win'] }} {% endfor %} which leads to TemplateSyntaxError. Could not parse the remainder: '['win']' from 'value['win']'. How can I call a specific value from dictionary using key in jinja template? -
I need to Ctrl-C/Pause after every manage.py command in Django
No, I'm not talking about runserver listening for requests. Whenever i run makemigrations, migrate or scripts i wrote using django-extensions command runscript, I need to stop the execution of the program before typing in another. This was not the case before restarting my PC this morning. I'm building a small QR code ticketing app and it was working up until this morning. I fixed a bug regarding opencv since and the app is functional again, but this command line issue is bothering me. I'm going to have to make the /admin and scripts available to a few of my colleagues tomorrow and i'm afraid we won't know when the script running is actually done since it doesn't prompt or allow another command. Having a script executed terminated early because of this would be catastrophic. Any help would be appreciated urgently! whenever i run a command, the blank line not accepting input appears -
Failed to build backports.zoneinfo
in terminal I run command docker build ., but dockerfile fail to install. Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [35 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-38 creating build/lib.linux-x86_64-cpython-38/backports copying src/backports/__init__.py -> build/lib.linux-x86_64-cpython-38/backports creating build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license file 'licenses/LICENSE_APACHE' writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' copying src/backports/zoneinfo/__init__.pyi -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/py.typed -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo running build_ext building 'backports.zoneinfo._czoneinfo' extension creating build/temp.linux-x86_64-cpython-38 creating build/temp.linux-x86_64-cpython-38/lib gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -I/usr/local/include/python3.8 -c lib/zoneinfo_module.c -o build/temp.linux-x86_64-cpython-38/lib/zoneinfo_module.o -std=c99 error: command 'gcc' failed: No such file or directory [end of output] note: This error originates from a subprocess, … -
Imported images in csv file not working in webpage
I imported csv file with multiple columns, one of them is for images and it's in this format <div class="parent"><img class="img" title="" src=" {% static 'assets/images/thumb/1537.png' %} "width="64" height="64"></div> Everything works when I include the model on my index.html, but the image line becomes like a string and not an image models.py class Account(models.Model): Code = models.IntegerField(__("Code")) Crystls= models.IntegerField(__("Crystls")) Price = models.IntegerField(__("Price")) Detail = models.CharField(__("Detail"), max_length=255) Image = models.ImageField(__("Image"), max_length=255) index.html {% for account in account %} <td style="text-align:center;vertical-align:middle;">{{account.Code}}</td> <td style="text-align:center;vertical-align:middle;"><img src=" {% static 'assets/images/assets/crystls.png' %} " width="22" height="22" style="padding-bottom:3px;" />{{account.Crystls}}</td> <td style="text-align:center;vertical-align:middle;">{{account.Price}}</td> <td style="text-align:center;vertical-align:middle;"><a target="_blank" href=" {% static 'account61f3.html?id_xml=001660' %} " ><input type="button" class="btn btn-success btn-sm" value={{account.Detail}} /></a></td> </tr> <tr> <td colspan="5"> {{account.Image}} </td> {% endfor %} </tr><tr > -
How to bind two models in __init__ via related_name when calling only parent, creating an empty object
I have two models, as below, linked by the OneToOneField relationship. How can I check by related_name that there is a link to x.RelName before I use x.save (). Everything below ... models.py class Parent(models.Model): name = models.CharField(max_length=255) member = models.ForeignKey(User, related_name="MemberUsr", blank=True, null=True, default=None, on_delete=models.CASCADE) class Child(models.Model): child_name = models.CharField(max_length=255, null=True, blank=True) parent_name = models.OneToOneField(Parent, related_name='RelName', null=True, on_delete=models.CASCADE) py manage.py shell >>> from app1.models import Parent, Child >>> x = Parent() And at this point there should be an artificial connection in _ _ init _ _ >>> x.RelName Should return that it is artificially bound to Child. If I run x.save () it obviously creates linkages. But I would like to be able to check with related_name before save () that there is a binding. -
A way in Django to have one model's parameters be a dropdown selection from another model
I'm creating a recipe app, and to avoid duplication I want to store the tools without using foreign keys to avoid duplicates. Currently, each ingredient uses a recipe as a foreign key, as ingredients can come in different measurements, but I'd like to have the tools only able to be in the database once. Here are the relevant models: class Recipe(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) servings = models.IntegerField(default=1, blank=False) def __str__(self): return self.name class Instruction(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) description = models.CharField(max_length=400) def __str__(self): return f"Step #{self.id} - {self.description[:20]}" class Tool(models.Model, unique=True): name = models.CharField(max_length=50) description = models.CharField(max_length=200) def __str__(self): return self.name For ingredients, I'm using a forloop to create a table (below), but I'm unsure how to do the same for tools related to a recipe without having multiple entries in the database for tools be the same, apart from the related recipe, i.e "Frying pan" more than once. <h3>Ingredients:</h3> <table id ="ingredients"> <tr> <th>Ingredient</th> <th>Quantity</th> </tr> <tr> {% for ingredient in recipe.ingredient_set.all %} </tr> <tr> <td> {{ ingredient.name }} </td> <td>{{ ingredient.quantity}} {% if ingredient.units == "UN" %}{% else %}{{ ingredient.get_units_display.title }}{% endif %}</td> </tr> {% endfor %} </table> <h3>Tools:</h3> Table for tools goes here -
Django Property to generate a list of tuples of field and its value but return forienkey value if it is a relation
Here are the models class Category(BaseModel): title = models.CharField(max_length=128) description = models.TextField() class Meta: verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): return str(self.title) class Service(BaseModel): category = models.ForeignKey(Category, limit_choices_to={"is_active": True}, on_delete=models.PROTECT) title = models.CharField(max_length=128) class Meta: verbose_name = "Service" verbose_name_plural = "Services" def __str__(self): return str(self.title) def get_absolute_url(self): return reverse_lazy("services:service_detail", kwargs={"pk": self.pk}) def get_fields(self): return [ ( field.verbose_name.title(), field.value_from_object(self) if field.is_relation else field.value_from_object(self), ) for field in self._meta.fields ] the get_fields model method will return the following list [ ('Id', UUID('3bde9003-32cb-44ed-89c2-0d7b962d41a9')), ('Category', UUID('cc2ecdf8-c8e5-4cfe-998b-906d12cbccf9')), ('Title', 'Baby sitters'), ] The result can be listed on template as follows {% for name, value in object.get_fields %} {% if value %} <strong> {{name}} : {{ value }} </strong> {% endif %} {% endfor %} Now I want the model method to return a list like follows [ ('Id', UUID('3bde9003-32cb-44ed-89c2-0d7b962d41a9')), ('Category', 'Cleaning'), ('Title', 'Car Wash'), ] That is, return the value of __str__ definition of the model the forienkey referring to, if the model field is a forienkey. The purpose is to create a reusable detail page compatible for every models -
Django channel or Django signals which one should i use to allow user to get notify when some action occur
I created an app where user's can be able to post Questions and get an Answers from some user's like how we do this in stackoverflow. I don't want user to refresh page just let him know that someone answers his question i want to implement the connections functions between these user. My models class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.title) class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) My views: class My_Question(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'body', 'category'] template_name = 'question.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Question, self).form_valid(form) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user form.instance.post_id = self.kwargs['pk'] return super (My_Answer, self).form_valid(form) def viewQuestion(request, pk): question = Question.objects.get(id=pk) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) I want to implement Notifications Function so that when a User answer a question, the author of that Question will get notify that will redirected He/She … -
HTML5 Page: Make all divs completly visible in browser without scrolling (Django)
I would like to create one indexview which content is completely visible with any browser (mobile and desktop) without the need of scrolling. So I need any function which scale the content of the page (shrink html5 elements) so that all elements have their place on the screen. At the moment I try to go with CSS. I tried to set the max-height: 94vh (6vh are for my navbar) of my main container. But sadly that not works. the included elements of the maincontainer are overlapping... So I have to scroll Maybe this has something to the with the bootstrap cards? The result looks like this: I have the undesirable scrollbar on the right (I would like to see all six cards without scroll, so the cards must be smaller...depending on the screensize): Here my django templates: Base template <!-- Load nessessary static files--> <!-- ===============================================================================================================================================--> {% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/base_style.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link href="//cdn.jsdelivr.net/npm/round-slider@1.5.1/dist/roundslider.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <script src="https://cdn.jsdelivr.net/npm/round-slider@1.5.1/dist/roundslider.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#"> <img src="{% static 'img/greencube2.png' %}" width="30" height="30" … -
Unable to upload multiple images with Django Rest Framework
I'm trying to create a view where I can upload images at to a single model which has a foreign key to another model. The below given API works but however it only uploads 1 image. What am I doing wrong that it only takes the first image from the list and uploads in the media folder? models.py class RoofImages(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) job = models.ForeignKey(JobDetails, on_delete=models.PROTECT) image = models.ImageField(upload_to=current_user_id) image_type = models.CharField(max_length=15, choices=ROOF_VIEW_TYPES) helpers.py def modify_input_for_multiple_files(user, job, image, image_type): image_dict = {} image_dict['user'] = user image_dict['job'] = job image_dict['image'] = image image_dict['image_type'] = image_type return image_dict views.py class RoofImagesView(APIView): serializer_class = RoofImagesSerializer parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): user = Token.objects.get(key=request.auth.key).user job = request.data['job'] images = dict((request.data).lists())['image'] image_type = request.data['image_type'] flag = True arr = [] for img_name in images: modified_data = modify_input_for_multiple_files(user.user_uid, job, img_name, image_type) serializer = RoofImagesSerializer(data=modified_data) if serializer.is_valid(): serializer.save() arr.append(serializer.data) else: flag = False if flag: response_content = { 'status': True, 'message': 'Images uploaded successfully.', 'result': arr } return Response(response_content, status=status.HTTP_201_CREATED) else: response_content = { 'status': False, 'message': 'Unable to upload images.', 'result': serializer.errors } return Response(response_content, status=status.HTTP_400_BAD_REQUEST) -
password_reset_confirm is not rendering
I have used Django's built-in password reset functionality. everything is working fine but when I open the password reset link it redirects me to Django's built-in "password_reset_confime " template instead of my custom template usrl.py Code app_name="accounts" urlpatterns=[ path('password_reset/',auth_views.PasswordResetView.as_view( template_name='password_reset.html', success_url=reverse_lazy('accounts:password_reset_done')),name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html',success_url=reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm.html'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), ] And I also want to implement a feature while entering an email id into the input field, I want to check if the user's entered email exists or not, if do not exist I want to show an error message "this email id is not exist" please help me to implement this feature and provide a solution for rendering my custom password_reset_confirm.html and password_reset_complete.html pages -
How to integrate an authenticated user profile data into Django Model
Hello Friendly People, I want to create an API which is able to serve the data using Django Rest framework. The objective is to create a model which can add the authenticated user profile data into custom model, so far I am able to serve the data using the views.py but it should have to be done implicitly like from the Models views.py class MessageView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request,*args, **kwargs): all_messages = Message.objects.all() message_serializer = MessageSerializers(data = all_messages, many=True) message_serializer.is_valid() current_user = request.user data = { 'user_id': current_user.id, 'messages': message_serializer.data, 'first_name': current_user.first_name, 'last_name': current_user.last_name, 'email': current_user.email, } return Response(data , status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): message_data = request.data current_user = request.user data = { 'user_id': current_user.id, 'first_name': current_user.first_name, 'last_name': current_user.last_name, 'email': current_user.email, } create_message = Message.objects.create(message=message_data['message'] , created_by_id=current_user.id) create_message.save() # serializer = MessageSerializers(create_message) data={ 'message': 'success', 'status': status.HTTP_201_CREATED } return Response(data ,status=status.HTTP_201_CREATED) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Message(models.Model): id = models.AutoField(primary_key=True) message = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.message Output that I am getting { "user_id": 2, "messages": [ { "id": 1, "message": "Testing message … -
MultiValueDictKeyError django, views.py error
I'm getting MultiValueDictKeyError while using the POST method with Django. this is my views.py submit function. it seems like there is an error with the candidateId field and I don't understand why. def submit_dept_member_application(request, application_id): cv = request.FILES['cv'] letter = request.FILES['letter'] candidate_id = request.data['candidateId'] rank_id = request.data['requestedRankId'] application_state = { 'candidate_id': candidate_id, 'rank_id': rank_id, 'cv_filename': cv.name, 'letter_filename': letter.name, } creator = Profile.objects.get(user=request.user.id) department = creator.department applicant = Profile.objects.get(user=candidate_id) rank = Rank.objects.get(id=rank_id) try: application = Application.objects.get(id=application_id) # TODO - update application except Application.DoesNotExist: application = None if application is None: application = Application(creator=creator, applicant=applicant, desired_rank=rank, application_state=application_state, department=department ) application.save() create_application_directory(application.id) ApplicationStep.objects.update_or_create( application=application, step_name=Step.STEP_1, defaults={'can_update': True, 'can_cancel': True, 'currentStep': True} ) copy_to_application_directory(cv, application.id) copy_to_application_directory(letter, application.id) addresee = 'devasap08@gmail.com' # TODO: change email to admin address email_headline = 'New Application Created' wanted_action = 'application_created' sendEmail(addresee, email_headline, wanted_action, creator) addresee = 'devasap08@gmail.com' # TODO: change email to creator address email_headline = 'Application Successfully Created' wanted_action = 'application_received' sendEmail(addresee, email_headline, wanted_action, applicant) return Response(application.id, status=status.HTTP_200_OK) any suggestions on how to solve it? Thank you! -
Django Rest API project architecture/design - What would a good design for my API be?
I'm new to Django and APIs in general and I want to create a Django based API using Django Rest Framework. The API must have the following: API with employees CRUD: - GET: /employees/ (employee list) - POST: /employees/ (employee create) - UPDATE /employees/ID/ (employee update) - DELETE /employees/ID/ (employee delete) - GET /employees/ID/ (employee detail) API with reports: - GET /reports/employees/salary/ (salary report) - GET /reports/employees/age/ (age report) Endpoint to employee list: curl -H "Content-Type: application/json" localhost:8000/employees/ Endpoint to salary range report:: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/salary/ It must persist data in a database and use authentication to access. How do I structure this project in terms of apps, folders, etc? So far I've figured I'd have something like this: root ├───backend (folder) │ │ manage.py │ │ │ ├───api (app) │ ├───django_project │ ├───employees (app) │ ├───reports (app) │ └───users (app) └───client my_client.py --> will consume the api Or maybe something like this?: root ├───backend (folder) │ │ manage.py │ │ │ ├───api (app) │ ├───applications (folder) │ │ ├───employees (app) │ │ ├───reports (app) │ │ └───users (app) │ └───django_project │ settings.py │ └───client (folder) my_client.py Obs: Just ignore the missing files for now. It's not a … -
How implement Hesh Id in Djnago RESTFRAMEWORK?
I'm trying to hide the id of my objects, but I don't know how to implement it in the correct way. What I did was this: hashids = Hashids(settings.HASHIDS_SALT, min_length=32) def parse_result(result) -> Union[int, None]: if result: if isinstance(result[0], int): return result[0] try: result = int(result[0]) return result except Exception as error: print("Couldn't parse the decodification!") print(error) def h_encode(id: int): return hashids.encode(id) def h_decode(h: str) -> Union[int, None]: return parse_result(hashids.decode(h)) class HashIdField(serializers.CharField): def to_representation(self, value): value = h_encode(value) return super(HashIdField, self).to_representation(value) def to_internal_value(self, data): data = h_decode(data) return int(super(HashIdField, self).to_internal_value(data)) class ProducerSerializer(serializers.HyperlinkedModelSerializer): id = HashIdField(read_only=True) class Meta: model = Producer view_name = 'api:producer-detail' fields = ( 'id', 'name',) Although it works, I can still access the objects by their integer ID. Obs: I'm using viewset. -
Why does the Django admin prompts "a LIST of values" for a DateTimeField with a DateTimeInput widget?
I'm trying to add an ability to edit DateTime fields "start" and "end" in Django admin with a microsecond resolution. I've tried an approach from this post : class SomeAdmin(ModelAdminWithJsonFields): """...""" list_display = ('id', ... , 'start', 'end') exclude = ['created_by', ... ] readonly_fields = ('created_by', 'created_on', ...) ... formfield_overrides = { models.DateTimeField: {'widget': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f')}, } Upon opening an admin page to edit the existing model that had permissible "start" and "end" values, I see a text field with pre-filled microseconds in seemingly correct format 2022-05-13 16:41:24.000000, proving that the model field works. Though, when clicking "save", the red font prompt above these models appears, saying Enter a list of values.. The same error happens with an approach from another SO answer: class DateTime(forms.DateTimeInput): start = forms.DateTimeField( input_formats=['%Y-%m-%d %H:%M:%S.%f'], widget=forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f') ) end = forms.DateTimeField( input_formats=['%Y-%m-%d %H:%M:%S.%f'], widget=forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f') ) class Meta: model = MachineAssignment fields = ['start', 'end'] class SomeAdmin(ModelAdminWithJsonFields): """...""" list_display = ('id', ... , 'start', 'end') exclude = ['created_by', ... ] readonly_fields = ('created_by', 'created_on', ...) ... formfield_overrides = { models.DateTimeField: {'widget': DateTime}, }