Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding Radio buttons for gender field and check box for T&C in django registration form
I try to make registration form. I'm having difficulty settings up the views.py file to include a radio for gender and check box for agree terms and conditions. I looked at the documentation but was having no luck applying the correct syntax. Here is what i currently have in my views.py def registration(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password= request.POST['password1'] password2 = request.POST['password2'] gender = request.POST['gender'] TAC = request.POST['tac'] if password == password2: if User.objects.filter(username=username).exists(): messages.info(request,'Username is already Taken .Try different One') elif User.objects.filter(email=email).exists(): messages.warning(request,'Email is already registered') else: user = User.objects.create_user(first_name=first_name,last_name=last_name,username=username,password=password,gender=sex) user.save(); messages.success(request,'Successfully Registered ..!Now you can Log in') return redirect('/') else: messages.error(request,'Password Does not Match..') else: return render(request,'registration.html') return render(request,'registration.html') And this is my HTML code snippet.. <div class="btn-group" data-toggle="buttons"> <label class="btn btn-info"> <input type="radio" name="goptions" id="option1" > Male </label> <label class="btn btn-info"> <input type="radio" name="goptions" id="option2"> Female </label> </div> Help me to add radiobutton for gender field and check box for t&c .(it must be registered only if the t&c check box is checked. -
Why Django ModelViewSet returns empty Dictionary?
I have this simple code that should return the queryset but when I call GET in postman it returns an empty dictionary. Model class Project(models.Model): filename = models.CharField(max_length=200) author = models.ForeignKey(User, related_name='author', on_delete=models.CASCADE) Serializer class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' REST FRAMEWORK REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } Views class ProjectAPI(viewsets.ModelViewSet): serializer_class = ProjectSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return self.request.user.author.all() def perform_create(self, serializer): serializer.save(author=self.request.user) URLS router = DefaultRouter() router.register(r'projects', ProjectAPI, basename='projects') urlpatterns = [ path('', include(router.urls)), ... ] I found some related questions but none of them solved my problem yet. And also when I just print self.request.user.author.all() there is data so I have no clue what is the problem, but in Postman I get this response: [ {} ] -
why is the server in Django not running?
i have hosted static files on AWS services and configured in my Django settings but when i try to run server its showing this error"runserver can't serve media if MEDIA_URL is within STATIC_URL." django.core.exceptions.ImproperlyConfigured: runserver can't serve media if MEDIA_URL is within STATIC_URL[error here][1] -
Problem with Django-crispy-forms: No module named 'crispy_forms'
Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/init.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' -
Uploading multiple images at once in Django without external sources
before I continue with my question, I have looked at all previous answers to related questions and came to find that a lot of people have directed individuals to django projects like photologue. I have looked at all of these and am still very confused I am just trying to find a simple solution without any error handling or file exceptions. So I have a model of Pictures like the following. class Picture(models.Model): asociated_event = models.CharField(max_length=64, default='Picture', help_text=("Source of the event")) description = models.CharField(max_length=64, default='Picture', help_text= ("Describe your images so they can easily be identified to be added into appropriate gallery ")) image = models.ImageField(upload_to='pre-image') image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(125, 125)], format='JPEG', options={'quality': 80}) I want a way to upload a multiple images at once. All the uploaded images can have the same associated_event and description this is not a problem. I want to iterate through uploads and want each of the uploaded images to be their own object in the database. -
Not redirecting to my own view after login with Django and AllAuth
I'm getting familiar with Django and I'm trying to use django-allauth and the issue I found is that I cannot redirect to my own view after login. Let me share a piece of code: this is the form I have in the login.html template: <form action="{% url 'webapp:home' %}" method="post" class="margin-bottom-0"> {% csrf_token %} ... </form> Here is my url.py defined inside my app: app_name = 'webapp' urlpatterns = [ path(route='', view=views.HomeView.as_view(), name='home'), ] I also defined my namespace: path("workspace/", include("picnic.webapp.url", namespace="webapp")), Now, every time login succeeds, I got the URL: http://127.0.0.1:8000/accounts/login/?next=/workspace/ which matches with login and it's redirecting me to the login page again... How can I force allauth to send me to http://127.0.0.1:800/workspace instead the url is currently sending me? Regards -
Case types integer and time without time zone cannot be matched
I have my code as below: Songs.objects.filter(clients__id__in = client).annotate(logic_value = Case(When(after_n_values__isnull=False,then="aftervals_songs"), When(specific_time__isnull = False,then=F('specific_time')),distinct = True,output_field=models.TextField())).values('logic_value') Here, I am getting an error due to - When(specific_time__isnull = False,then=F('specific_time')) This is because specific_time is TimeField() in the Django model and after_n_values is an Integer. I actually want to check when a value between (after_n_values or specific_time exists)then it should return that corresponding value. But, I get the following error: Error: ProgrammingError: CASE types integer and time without time zone cannot be matched LINE 1: ... WHEN "core_songs"."specific_time" IS NOT NULL THEN "core_songs"... Could anyone suggest how can I check here using when clause whether a date is present or empty as shown above? -
How should data be shared between webapp and IOS?
I'm about to build a review site using AWS and plan to use python, django, MySQL and S3 for webapp. If I'm going to build an IOS app after this, how should I share AUTHENTICATION and will the BEST solution be AWS COGNITO? Also, is it okay to share MySQL via api for database? Should I prepare something else? Thanks, motohiro -
How to restrict number of elements in many side in Django ORM?
I have a model A and model B. They are connected as follows. class modelA(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) class modelB(models.Model): title = models.CharField(max_length=255) model_a = models.ForeignKey(A, on_delete=models.CASCADE) As far as I understand there is a one to many connection between model B and model A or model B can have many model A. Question: How can I restrict the many side to some specific number? -
Dynamic Calculations Displayed To User In Django
I am wanting to create a webpage which has four inputs, each can take a 1 digit number. The user can enter a number 0-9 in each of the boxes, and as they do, the total is displayed at the end (updated dynamically, likely using javascript). Example: |1| + |2| + |3| + |4| = # numbered 1, 2, 3, 4 |2|....|7|..|1|...|3| = 13 # calculated total (user input) Thank you -
Django static file not found - 404
This question has been asked a lot of time but I couldn't fix my issue. Sorry about asking same question and thanks for your help in advance In my project something is wrong with the static files but not always. For example, last night when I closed the project it was loading the static files but not today. And it happened a lot of time. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # BASE_DIR = os.path.join(BASE_DIR, 'MyApp') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'MyApp/templates/')], ... }] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MyApp/urls.py from django.conf import settings # from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^admin/', admin.site.urls), url('', include('OneApp.urls')), ] urlpatterns += staticfiles_urlpatterns() # if settings.DEBUG: # urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) OneApp/urls.py urlpatterns = [ path('OneApp/', views.index, name='index'), ] master_page.htm {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'assets/css/style.css' %}"> <img src="{% static 'assets/images/avatar-4.jpg' %}" alt="image sample"> Project Folders: MyApp MyApp static assets css style.css Thanks again -
Djanog re-route with NGinx
I have my first website running properly under Apache Web Server which shows homepage and it can be accessed at http://localhost:8989/. I also have my second website which is a Django application (run under uWsgi) running properly at http://localhost:8000/ and each page is shown properly. Now, I wanted to use Nginx to serve all static resources of both websites. Since I want to use my the only one domain for both website, so called www.test.com (TEST), I configure it as follows: server { listen 80; server_name _; location / { root /var/www/statics; index index.html index.htm; try_files $uri @home; } #for request: https://www.test.com/ , it should go to the 1st website location @home { proxy_pass http://localhost:8989; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } #for request: https://www.test.com/abc , it should go to the 2st website location /abc { rewrite ^/abc(.*) $1 break; try_files $uri @abc; } location @abc { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Not sure whether there is a better configuration, my requirement is as follows: having a website running on TEST If I go to TEST/ --> it should show my 1st website … -
Django REST framework: want to switch API processing depending on conditions
I want to replace all processes of a specific API according to specific conditions (settings or database value). Example : it usually returns a value from the DB, but returns a fixed value for a specific client. I thought that it is possible by using middleware, I implemented the following, but it does not work. error content "The response content must be rendered before it can be accessed" I would like to render it, but please tell me how to do it. # extensions.test_middleware from extensions.hoge import hogehoge class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path == '/api/v1/hogehoge/': return hogehoge(request) response = self.get_response(request) return response # extensions.hoge from rest_framework import status from rest_framework.response import Response def hogehoge(request): return Response(status=status.HTTP_200_OK) # settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'extensions.test_middleware.SimpleMiddleware' ] [ERROR] 2020-05-21 12:58:53,658 log 1320 /usr/local/lib/python3.7/site-packages/django/utils/log.py 228 Internal Server Error: /api/v1/hogehoge/ Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/usr/local/lib/python3.7/site-packages/django/middleware/common.py", line 112, in process_response response['Content-Length'] = str(len(response.content)) File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 128, in content 'The response content must be rendered before it can be accessed.' django.template.response.ContentNotRenderedError: … -
How to store the onclick events in a Django database?
I have a list of audio files displayed in my Django webpage displayed using ... tag. When a registered user clicks the play button of the audio file, it should start playing the audio and behind the scene, I want to store the audio file id as well as the user details in the database, like submission of a Django form. But after the user clicks the play button, I don't want the page to get refreshed, neither do I want the audio file to be paused. I guess this has to do something with the Ajax, but I can't figure it out. -
Multiple bootstrap collapse panel opens at one button click
I am working on a blog kind of web app using Django. On my home page, I want to show all the posts. Every post contains one collapse panel. Initially, id's to trigger collapse panel was hardcoded so all the collapse panel opens on clicking on one post-collapse panel. So I changed the id's that are used to trigger collapse panel. I used post id as HTML id or triggering the collapse panel. But the problem is the collapse panel is not working at all. This is how I changed hardcoded id's. {% for post in posts %} <div class="container shadow mt-4 pl-3 pr-3 pb-3" style="border-radius: 10px;"> <div class="user row p-3"> <img class="rounded-circle img-avatar" src="{{ post.author.profile.image.url }}" alt=""> <p class="author-name font-weight-bold font ml-4 mt-3">Username</p> </div> <div class="question"> <p>{{ post.question }}</p> </div> <button class="mb-2" style="border: none; background-color: transparent" type="button" data-toggle="collapse" data-target={{ "#"|join:post.id }} aria-expanded="false" aria-controls={{ post.id|slugify }}> <i class="fas fa-angle-down pl-1 pr-1"></i> </button> <div class="collapse" style="overflow: hidden" id={{ post.id|slugify }}> <div class="card card-body options"> <li class="options"><input type="radio" name="options"><span class="pl-2 pr-3">{{ post.option1 }}</span></li> <li class="options"><input type="radio" name="options"><span class="pl-2 pr-3">{{ post.option2 }}</span></li> <li class="options"><input type="radio" name="options"><span class="pl-2 pr-3">{{ post.option3 }}</span></li> <li class="options"><input type="radio" name="options"><span class="pl-2 pr-3">{{ post.option4 }}</span></li> {% if post.option5 %} <li … -
Cannot resolve keyword 'id' into field
Hello i am new in python/django I am having a problem in creating forms here is my code as reference. please help. thanks. models.py class RFP(models.Model): ref_no = models.CharField(primary_key=True, max_length=17, unique=True, default=increment_rfp_number, editable=False, null=False) rfp_category = models.ForeignKey(RFPCategory, verbose_name="RFP Category", on_delete=models.CASCADE, null=True, blank=True, related_name='rfp_category_name') project = models.ForeignKey(ProjectCode, verbose_name="Project", related_name='rfp_project', on_delete=models.CASCADE) requestor = models.ForeignKey(User, on_delete=models.CASCADE) date_requested = models.DateTimeField(default=timezone.now) date_needed = models.DateField(auto_now_add=False, auto_now=False, blank=False) amount = MoneyField(max_digits=14, decimal_places=2, default_currency='PHP') purpose = models.TextField(null=False, blank=False) status = models.CharField(default='Open', max_length=10) supervisor = models.CharField(max_length=50, blank=True, null=True) supervisor_is_approved = models.BooleanField(default=False) supervisor_date_approved = models.DateTimeField(default=timezone.now) budget_reviewer = models.CharField(max_length=50, blank=True, null=True) budget_reviewer_is_approved = models.BooleanField(default=False) budget_reviewer_date_approved = models.DateTimeField(default=timezone.now) budget_approver = models.CharField(max_length=50, blank=True, null=True) budget_approver_is_approved = models.BooleanField(default=False) budget_approver_date_approved = models.DateTimeField(default=timezone.now) manager_approver = models.CharField(max_length=50, blank=True, null=True) manager_approver_is_approved = models.BooleanField(default=False) manager_approver_date_approved = models.DateTimeField(default=timezone.now) cfo_approver = models.CharField(max_length=50, blank=True, null=True) cfo_approver_is_approved = models.BooleanField(default=False) cfo_approver_date_approved = models.DateTimeField(default=timezone.now) vp_approver = models.CharField(max_length=50, blank=True, null=True) vp_approver_is_approved = models.BooleanField(default=False) vp_approver_date_approved = models.DateTimeField(default=timezone.now) current_approver = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.ref_no def get_absolute_url(self): return reverse('rfp-view', kwargs={'pk': self.ref_no}) class Meta: ordering = ['-date_requested'] views.py def rfp_create(request): if request.method == 'POST': form = RFPCreateForm(request.POST) notif = CreateRFPNotification(request.POST) if form.is_valid(): ref = form.cleaned_data['rfp_category'] category = RFPCategory.objects.get(category_name=ref) form.instance.requestor = request.user form.instance.supervisor = request.user.profile.supervisor form.instance.current_approver = request.user.profile.supervisor form.instance.budget_reviewer = category.budget_reviewer form.instance.budget_approver = category.budget_approver form.instance.manager_approver = category.manager_approver form.instance.cfo_approver … -
Displaying search result relevance score alongside a QuerySet search result in Django
I have a working implementation of Django and Elastic Search (using the django-elasticsearch-dsl module). The way the integration works is that ordered Docket results are stored in a QuerySet instance returned from self.search.to_queryset() while the relevant search metadata - key information like relevance score of each document - is stored in a list of dictionaries returned from self.search.execute() which I call in the get_context_data() function. This is not the same as combining two QuerySets - the search results are derived from an Elastic Search query, not a Django model. They are also temporary, meaning for each query the relevance score is different, so it doesn't make sense to try and add those scores as a Model property. I'm using django-tables2 to display the output, but I can't figure out how to pass the list with relevance scores together with the QuerySet to the django table object for rendering. I can easily return 2 separate tables, one with documents and one with relevance scores but I want to avoid doing that. class DocketsView(SingleTableView): 80 form_class = SearchDocketForm 81 template_name = 'dockets/detail.html' 82 paginate_by = 20 83 ordering = ['-date_filed'] 84 context_object_name = 'documents' 85 table_class = DocumentTable 86 search = DocumentDocument.search() … -
Adding Crispy Error Messages To Forms Rather Than Flash Errors Messages
I am using crispy forms and would like to add error messages. The problem is that when I add extra validation the error messages appear as flash messages. I would like to make the error messages the same as the crispy error messages for consistency (for example the 'this field is required' crispy message). This is an example of validation I added (which is displayed as a flash message) # check age > 14 && < 110 def clean(self): data = self.cleaned_data born = data.get('dob') today = date.today() age = (today.year - born.year - ((today.month, today.day) < (born.month, born.day))) if age > 110 or age < 0: raise forms.ValidationError('You entered a date of birth outside of the accepted range. Please try again') elif age < 14: raise forms.ValidationError('Sorry, you must be atleast 14 years old to register') return data Thank you. -
Customizing Stripe Pay Button
I have added a stripe pay button using the following javascript: <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" ta-key="{{ key }}" data-description="Select" data-amount="10000" data-locale="auto"> </script> I got the pay button but i can't customize it.If anyone can refer me any post of links please let me know. -
Hello, Is there any free job, for junior Python developer?
I want to be a Python programmer, there fore I'm looking for projects or jobs where, someone will require a hands and help, I'm ready to spent all my free time, is there any one who can help me? Of course I will work for knowledge only. -
Accessing 1:N relationship in Django-table2
I am stuck in this step. Maybe quite easy for you. I am 4 tables as below. basically wanted to display the times in a single django-table2. Could you please guide me on this? models.py class A(models.Model): name = models.CharField() timeA = models.DateTimeField(auto_now=True) class B(models.Model): name = models.ForeignKey(A) timeB = models.DateTimeField(auto_now=True) class C(models.Model): name = models.ForeignKey(A) timeC = models.DateTimeField(auto_now=True) class D(models.Model): name = models.ForeignKey(A) timeD = models.DateTimeField(auto_now=True) Now I created a table2 as below: tables.py class A_table(table2.Table): timeA = tables.LinkColumn( 'link1', kwargs={"id": A("pk")}, text=lambda record: record.timeA.strftime('%l:%M %p') ) timeB = tables.LinkColumn(???) timeC = tables.LinkColumn(???) timeD = tables.LinkColumn(???) class Meta: model = A fields = ['Name', 'timeA', 'timeB','timeC', 'timeD'] -
How can i make Mezzanine 4.3 work with django 3 without errors?
How to make Mezzanine 4.3 work with django 3 on AZURE without issues l've made a mezzanine blog and i'm facing challenges deploying it in AZURE cloud. Everything goes well but, when bind the blog with Engine X it requires me to Update Django for static files (css, js, images to show). When i update django I have the worst problems. It needs me to change lots of file settings some of which i dont even understand. May someone help me if there is a way to Deploy Mezzanine 4.3 and any version of Django without such challenges. It seems building was better than deployment Now. I will be glad to be help in simple steps possible for this to work. Thank you very much in advance -
Using data returned from forms in Django
Sorry for being a little new. My goal is to use the data collected from a user form to output a graph. The user inputs an initial 'price' then submits this number, it then goes into my formulas written in python and then django should display a chart in the same HTML file. I'm currently stuck on how to use data from 'POST'. For example, if I'd like to take the cleaned_data from 'strike1' and multiply it by 4, then display it on the webpage, how would I go about doing that? views.py from django.shortcuts import render from .forms import DataForm # Create your views here. def data(request): if request.method == 'POST': form = DataForm(request.POST) if form.is_valid(): strike1 = form.cleaned_data['strike1'] strike2 = form.cleaned_data['strike2'] strike3 = form.cleaned_data['strike3'] strike4 = form.cleaned_data['strike4'] strategy = form.cleaned_data['strategy'] price = range(0,50) premium1 = form.cleaned_data['premium1'] premium2 = form.cleaned_data['premium2'] premium3 = form.cleaned_data['premium3'] premium4 = form.cleaned_data['premium4'] contracts = form.cleaned_data['contracts'] form = DataForm() return render(request, 'form.html', {'form': form}) forms.py from django import forms class DataForm(forms.Form): strategy = forms.ChoiceField( choices=[('Long Call', 'Long Call'), ('Long Put', 'Long Put'), ('Short Call', 'Short Call',), ('Short Put', 'Short Put'), ('Bull Call Spread', 'Bull Call Spread'), ('Bear Put Spread', 'Bear Put Spread'), ('Straddle', 'Straddle'), ('Butterfly Spread', … -
Get Authenticated user on many=True serializer Viewset
I'm writing a rest api using Django Rest Framework, I have an endpoint to create objects on POST method and this method is overridden in order to allow bulk adding. However, the object is an "intermediate table" between Pacient and Symptoms and in order to create it I need to provide the pacient object or id and the same for the symptom. I get the Symptom id in the request, so that's not an issue, however the pacient is the authenticated user (who's making the request). Now, how do I edit the create method in the serializer in order to do that? Here's my view: class PacienteSintomaViewSet(viewsets.ModelViewSet): serializer_class = SintomaPacienteSerializer queryset = SintomaPaciente.objects.all() permission_classes = (IsAuthenticated, ) http_method_names = ['post', 'get'] def create(self, request, *args, **kwargs): many = True if isinstance(request.data, list) else False serializer = SintomaPacienteSerializer(data=request.data, many=many) if serializer.is_valid(): sintomas_paciente_lista = [SintomaPaciente(**data) for data in serializer.validated_data] print(serializer.validated_data) SintomaPaciente.objects.bulk_create(sintomas_paciente_lista) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) And this is my serializer: class SintomaPacienteSerializer(serializers.ModelSerializer): def create(self, validated_data): sintoma_paciente = SintomaPaciente.objects.create( sintoma_id=self.validated_data['sintoma_id'], paciente_id=THIS NEEDS TO BE FILLED, data=self.validated_data['data'], intensidade=self.validated_data['intensidade'], ) return sintoma_paciente class Meta: model = SintomaPaciente fields = ('id', 'sintoma_id', 'paciente_id', 'intensidade', 'data', 'primeiro_dia', 'ativo') -
Django Api Project(Postman Methods Throwing Errors)
Just started learning on Api's and using Postman, so I am working on a Django Movie Rating App Here are my models: class Movie(models.Model): name = models.CharField(max_length=35) description = models.TextField(max_length=300) class MovieRating(models.Model): movie = models.ForeignKey(Movie, on_delete= models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) class Meta: unique_together = (('user', 'movie')) index_together = (('user', 'movie') ) So the error occurs when I try to run the the function that I have created so this function was to create a new rating for a movie if the rating did not exist and if the rating had existed then the program should update the rating of the user that's being made Here is my model view set that has the code: class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer def rate_movie(self, request, pk=None): if 'stars' in request.data: stars = request.data['stars'] user = User.objects.get(id=1) movie = Movie.objects.get(id=pk) try: rating = MovieRating.objects.get(user=user.id, movie=movie.id) rating.stars = stars rating.save() serializer = MovieRatingSerializer(rating, many=False) response = {'message':'Rating has been updated', 'results': serializer.data} return Response(response, status=status.HTTP_200_OK) except: rating = MovieRating.create(user=user , movie=movie) serializer = MovieRating(rating, many=False) response = {'message': 'Rating for movie has been created', 'results': serializer.data} return Response(response, status=HTTP_200_OK) I shall add the picture for visual representation …