Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit users for change their own files in django REST
how are you? I am totally new in Django and rest. I am interested in writing a project which limits users just change their own tasks(my project is task management). I know that I should use the DjangoModelPermissions but unfortunately, it does not work on my project... it does not return any error but does not work either. Thank you for helping My app urls: path("api/",views.ListTaskAPIView.as_view(),name="all_task"), path('api/<int:pk>/', views.TaskDetailView.as_view(), name='detail_task'), path("api/create/", views.CreateTaskAPIView.as_view(), name="create_task"), path("api/update/<int:pk>/", views.UpdateTaskAPIView.as_view(), name="update_task"), path("api/delete/<int:pk>/", views.DeleteTaskAPIView.as_view(), name="delete_task"), Models : class Task(models.Model): title=models.CharField(max_length=250) text=models.TextField() user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) status=models.ForeignKey('Status',on_delete=models.SET_NULL,null=True) startDate=models.DateTimeField(auto_now_add=True) endDate=models.DateField(null=True) def __str__(self): return self.title class Status(models.Model): name=models.CharField(max_length=250) def __str__(self): return self.name serializer: from rest_framework import serializers from .models import Task,Status class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['title', 'text', 'status', 'endDate'] class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__' Views: class ListTaskAPIView(generics.ListAPIView): serializer_class = TaskSerializer model= Task template="task_list.html" def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ query = self.request.GET.get('search') if query: object_list = self.model.objects.filter(Q(title__icontains=query) | Q(text__icontains=query)) else: object_list = self.model.objects.all() return object_list class CreateTaskAPIView(CreateAPIView): """This endpoint allows for creation of a todo""" queryset = Task.objects.all() serializer_class = TaskSerializer permission_classes = [IsAuthenticatedOrReadOnly] … -
How to find average difference between datetime field in a related table?
I have to apps buyer and seller. seller app has model Gigs and buyer app has model Orders. I want when I retrieve a gig to my rest app it should compute average completion time of order of that specific gig. But I am getting error 'decimal.Decimal' object has no attribute 'tzinfo' Models.py(seller app) from django.db.models import Avg from django.db.models import F class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) Models.py (buyer app) class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=None) orderCompletedTime = models.DateTimeField(default=None) created_at = models.DateTimeField(auto_now_add=True) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.all().annotate( _average_completionTime=Avg( F('gig__orderCompletedTime') - F('gig__orderStartTime') ) ) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, obj): return obj.average_completionTime class Meta: model = Gigs fields = ['id','title','category','price','details','seller','images','average_completionTime'] But I am getting error 'decimal.Decimal' … -
how to use base64 with django ,and input html tag
I'm trying to save captured image from webcam to my django website 3.2 version this is what i'm tried class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py #my views function ... if request.is_ajax() and request.method == 'POST': images = request.FILES.get('canvas') print("images" , images) format, imgstr = images.split(';base64,') ext = format.split('/')[-1] dataimage = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) if dataimage: photo = Document.objects.create( booking=obj, docs = dataimage ) photo.save() but print images value is none , here is my JS + html const player = document.getElementById('player'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const captureButton = document.getElementById('capture'); console.log(context) const imgFormat = canvas.toDataURL(); console.log(imgFormat) console.log(canvas) const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <input type="file" name="documents" id="document"> <video id="player" controls autoplay></video> <button id="capture">Capture</button> <canvas id="canvas" name="canvas" width=320 height=240></canvas> is there something i have to change ? i think i have to access to canvas js variable from my views.py but i dont know how to achieve it -
Django access self in PrimaryKeyRelatedField
I have Order model with columns: id, restaurant_id, user_id, comment and OrderHasItem with columns: quantity, order_id, item_id I would like to be able to allow item from the same restaurant only for OrderHasItem. class OrderHasItemCreateSerializer(serializers.ModelSerializer): item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), many=False) class Meta: model = OrderHasItem fields = ['id', 'quantity', 'item'] class OrderCreateSerializer(serializers.ModelSerializer): items = OrderHasItemCreateSerializer(many=True) restaurant = serializers.PrimaryKeyRelatedField(queryset=Restaurant.objects.all(), many=False) comment = serializers.CharField(required=False) Is there a way to access self.restaurant in PrimaryKeyRelatedField? Thanks -
Django URLField Not Validating URLs
The URLField takes literally any text I pass to it. Doesn't the models.URLField have a validation on it? Model: class TesterManager(models.Manager): pass class Tester(models.Model): objects = TesterManager() url = models.URLField(unique=True) View @action(detail=False, methods=['POST']) def create_url(self, request): test = Tester.objects.create(url=request.data['url']) # Why does this not catch non-URLs??? # response -
what should i do toprogram in my domain that i purchased?
Today I bought a domain name in GoDaddy. I changed the nameservers to Cloudflare and got a free SSL certificate from there. How do I connect the domain that I purchased to python [i use flask/Django to program the website] -
Why is logging to a Django model a Blasphemy?
In all Django projects I write, I have a common application, and in that application I put things that are useful to the project as a whole. One such thing is an Activity or Event model like this: class Activity(models.Model): SUMMARY_LENGTH = 72 def __str__(self): return '%d:- %s' % (self.id, self.summary) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT) created = models.DateTimeField(db_index=True, auto_now_add=True, editable=False) activity_type = models.PositiveIntegerField(choices=ActivityTypeEnum.choices, default=ActivityTypeEnum.LOG) summary = models.CharField(max_length=SUMMARY_LENGTH, help_text='Text Shown in Staff Activity Log') show = models.BooleanField(default=False, help_text='Show in Staff Activity Log') page_url = models.URLField(max_length=128, blank=True) ip_address = models.GenericIPAddressField(blank=True, null=True) extra_detail = models.TextField(blank=True) class Meta: ordering = [ '-created' ] def save(self, *args, **kwargs): if len(self.summary) > self.SUMMARY_LENGTH: self.summary = self.summary[:self.SUMMARY_LENGTH] return super(Activity, self).save(*args, **kwargs) Then I have a helper function one liner that I can put anywhere in my code where I can log something, with different log types for different kind of events. def record_activity(activity_type=ActivityTypeEnum.LOG, summary='', extra_detail='', show=True, makeme_string=None, job=None, request=None): """ Record System Wide Activity Stuff. Not a member function, becuase importing the model class everywhere is to be avoided """ if makeme_string: try: string_bit = json.dumps(makeme_string, sort_keys=True, indent=4, separators=(',', ': '), default=str) except: string_bit = 'Could not dump the makeme_string' extra_detail += '\n=======================\n%s' % string_bit … -
Django CKEditor Background Color
I'm using django ckeditor, and when i click any button (for example: iframe button), the background color is black so its hard to see and edit Here is my code for django ckeditor config CKEDITOR_CONFIGS = { 'default': { 'toolbar': [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Subscript", "Superscript", "Iframe"], ['Undo', 'Redo'], ["Maximize"]], }, } Is there a way to change a color background? Is the problem in django ckeditor? django? or my browser? any idea? Thankyou. -
Google App Engine GitHub Action: Error: Unexpected token � in JSON at position 0
I'm trying to deploy my Django API on to Google App Engine using GitHub CI/CD, but I'm getting a strange error that doesn't provide any stack trace in my deploy job. My build job with unit tests and code coverage passes. main.yaml: name: Python application on: push: branches: [ main ] pull_request: branches: [ main ] defaults: run: working-directory: src jobs: build: runs-on: ubuntu-latest services: postgres: image: postgres:10.8 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github_actions ports: - 5433:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Test with Unittest env: SECRET_KEY: ${{ secrets.SECRET_KEY }} DB_NAME: ${{ secrets.DB_NAME }} DB_USER: ${{ secrets.DB_USER }} DB_PASSWORD: ${{ secrets.DB_PASSWORD }} DB_HOST: ${{ secrets.DB_HOST }} DB_PORT: ${{ secrets.DB_PORT }} DB_ENGINE: ${{ secrets.DB_ENGINE }} run: | coverage run manage.py test && coverage report --fail-under=75 && coverage xml mv coverage.xml ../ - name: Report coverage to Codecov env: SECRET_KEY: ${{ secrets.SECRET_KEY }} DB_NAME: ${{ secrets.DB_NAME }} DB_USER: ${{ secrets.DB_USER }} DB_PASSWORD: ${{ secrets.DB_PASSWORD }} DB_HOST: ${{ secrets.DB_HOST }} DB_PORT: ${{ secrets.DB_PORT }} DB_ENGINE: … -
Building my first Django app - need guidance [closed]
I'm getting down to building my first Django App for my portfolio, and would like some guidance. Brief - the app will be a booking system that allows logged in users (customers) to book delivery slots on a selected date & a specific time. Think of it as a B2B portal for customers who are delivering their shipments to a distribution center (DC) and need to select a Delivery Date & Delivery Time for their shipment to be received at the DC's docks. e.g. Delivery Date = 29-Sep, Delivery Time = 09:00 Rules of booking: Delivery Time slots will be fixed for each day (7:00, 09:00, 11:00, 13:00) There is no limit to the number of bookings a customer can make If customer A has already booked a specific date & time e.g. 29-Sep, 09:00 and customer B also tries to book the same slot, the portal should feedback "The requested slot is already occupied, please choose another delivery time" If all the time slots on a specific date are already occupied, the portal should feedback "All the slots on this date are occupied, please choose another delivery date" The customer will be allowed to change or delete their booking … -
balance not getting correctly in the accounts ledger app
I'm trying to make a ledger app. the 2nd and 3rd row is of the same bill with 2 transactions.The bill value is the total amount of the bill and I use mathfilters in template to calculate the balance. In this case thats not possible since there are 2 transactions. Template <h1>Ledger</h1> <table id="table"> <thead> <td class="no-sort">Sl No</td> <td class="no-sort">BILL DATE</td> <td class="no-sort">ORDER NO</td> <td>BILL VALUE (Rs)</td> <td>PAYMENT (Rs)</td> <td>BALANCE (Rs)</td> </thead> {% for data in order_list_data %} <tr> <td>{{forloop.counter}}</td> <td>{{data.invoice__bill_date}}</td> <td>{{data.invoice__bill_no}}</td> <td>{{data.customer_gross_sum}}</td> <td>{{data.invoice__transaction_invoice__transaction_amount}}</td> <td></td> </tr> {% endfor %} </table> Views class LedgerView(TemplateView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): order_list = Order.objects.filter( is_deleted=0, order_status__in=[4], order_type=0) order_list_data = order_list.values('user_id', 'invoice__bill_no', 'invoice__bill_date', 'invoice__transaction_invoice__transaction_amount', 'invoice_id').annotate( customer_gross_sum=Sum('invoice__original_amount')-Sum('invoice__discount_amount')+Sum('invoice__tax_amount'), dcount=Count('user_id'), customer_paid_sum=Coalesce(Sum('invoice__transaction_invoice__transaction_amount'), Value(0))) transaction_list = Transactions.objects.filter( is_active=1,transaction_status= True).order_by('-invoice_id') transaction_amount = transaction_list.values( 'invoice__transaction_invoice__transaction_amount') context = { "order_list_data": order_list_data } template = loader.get_template('custom_admin/ledger/ledger.html') return HttpResponse(template.render(context, request)) -
how to generate a excel report of the customers?
class customer(models.Model): name = models.CharField(max_length=50) class info(models.Model): email = models.EmailField(max_length=250) phone_number = models.CharField(max_length=10, blank=False, null=False, unique=True) name = models.ForeignKey(customer,on_delete=models.CASCADE) class detail(models.Model): proof = models.ForeignKey(customer,on_delete=models.CASCADE) aadhar = models.ImageField(upload_to='images/', height_field=None, width_field=None, max_length=100,default=True) -
Django decorator, redirect user to 404 if they access unauthorized page?
I have created a decorator using users_passes_test and it works perfectly, but my requirement is as follows, If user is not authenticated: Then user needs to be redirected to login page Else, if user is authenticated but doesnt have access to the page: Then they need to be redirected to 404page How to modify my decorator according to the above need ? from django.contrib.auth.decorators import user_passes_test from django.contrib.auth import REDIRECT_FIELD_NAME def is_student(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: (u.is_authenticated and u.role == 'student'), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator This is my decorator, please help ! -
Show logs and progress of a cmd command live on a web Page python
When the user clicks a button in django web page, it should run a cmd command with which it should also show the progress and logs of the command live on the page. I am able to run the command through a python function but not able to display logs and progress simultaneously. Pls help. Thanks in advance. -
One To Many Broadcast webrtc with django server any tutorial or guidance?
My requirement is that -- Suppose there are person A and person B who wants to talk to each other in live stream, But they also wants to show(broadcasting) it to millions of people in there website. Is there any framework or something in django that i can do. I am using django as backend server. I saw something called webrtc, which is used for real time live streaming. But there are some blogs who suggests that webrtc p2p connection is not beneficial for this. I also saw mcu and sfu connection but didn't find any source code or tutorials in django server to implement it. Everyone is doing it in nodejs. I saw some tutorials in Youtube but they are just showing p2p and one-to-many-broadcasting(with nodejs server) Your Guidance will help a lot. -
Django+DRF FileUpload: How to get upload progress when uploading large files
I am trying to upload large files in Django (max size 2GB files) currently I am trying file = request.data['file1'] file_name = file.name outFile = open(file_name, "wb+") # check if the file size is less than 2.5mb else write in chunks if not file.multiple_chunks(): outFile.write(file.read()) else: for chunk in file.chunks(chunk_size=1000000): outFile.write(chunk) outFile.close() Now is there any way I can send the status of upload to the frontend. I am ok to use another api call from server to check this. -
How to handle django.db.utils.IntegrityError for asynchronous POSTs? (Can you except an IntegrityError?)
I have a model with a @BEFORE_CREATE signal hook like thus: from django.lifecycle.hooks import BEFORE_CREATE class Item(models.Model): title = models.CharField() slug = models.JSONField(unique=True) @hook(BEFORE_CREATE) def populate_slug(self): # Create a slug from the title # If the slug already exists, append "-{n}" # to make sure it is unique slug[0] = slugify(self.title) n = 2 while List.objects.filter(slug=slug).exists(): slug[0] = f"{slug[0]-{n}" n += 1 self.slug = slug This works fine in my tests when the Items are created synchronously one-after-another: i1 = Item.objects.create(title="Hello") i2 = Item.objects.create(title="Hello") self.assertEqual(i1.slug, ["hello"]) self.assertEqual(i2.slug, ["hello-2"]) However, on my actual frontend, I'm creating these objects asynchronously and at the same time: const item1 = axios.post(POST_ITEMS_URL, {title: "Hello"}) const item2 = axios.post(POST_ITEMS_URL, {title: "Hello"}) Promise.all([item1, item2]); Which gives me this error: web_1 | django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_item_slug_key" web_1 | DETAIL: Key (slug)=(["hello"]) already exists. An easy fix (I think) would be to change my @hook to be AFTER_CREATE but I would like to avoid the additional write on all objects if possible. Is it possible to put an except IntegrityError somewhere? If so, where? Or how else can I overcome this problem? I'm using PostGRE if that matters. -
Explain relay and find_global_id in django graphql
i was reading django project in schema they define interface as a relay and also explain use of find_global_id class Meta: model = Books interfaces = (relay.Node, ) class Arguments: ad_id = graphene.ID() in mutate function ad_id = from_global_id(ad_id)[1] what will store ad_id ? -
Django rest framework and frontend
I want to use Django Rest Framework to create RESTAPI to integrate with the payment gateway API like stripe. For the frontend part I can only see project using React for the frontend. Cant i use Django as a frontend? Looking for suggestions if i really just need to use React or Vue. Or is it possible to use django as frontend as well. Looking for your suggestions. Thank you. -
How to get relate model without nested in Django rest framework?
How to get a json with relate model but without nested in Django rest framework? Code : Models, Session and Athlete, Athlete models has foreign key relationship with Session class Session(models.Model): Id = models.AutoField(primary_key=True) SessionNo = models.SmallIntegerField() WinTeam = models.SmallIntegerField(null=True) class Athlete(models.Model): Id = models.AutoField(primary_key=True) Name = models.CharField(max_length=6) Age = models.SmallIntegerField() Session = models.ForeignKey(Session, on_delete=models.CASCADE, related_name='athletes') Status = models.SmallIntegerField() Serializers class SessionSerializer(serializers.ModelSerializer): class Meta: model = Session fields = '__all__' class AthleteSerializer(serializers.ModelSerializer): Session = SessionSerializer(read_only=True) class Meta: model = Athlete fields = ('Age', 'Status', 'Session') And views: def all_athletes(request): """ Get all athletes list """ queryset = Athlete.objects.all().select_related() serializer = AthleteSerializer(instance=queryset, many=True) return Response(serializer.data) And the API result is : [ { "Age": 38, "Status": 1, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null } }, { "Age": 26, "Status": 1, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null } }, { "Age": 35, "Status": 2, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null } } ] It works to get relate model, but I want relate models show without nested, how to do to fit my expectation ? I expect the API result: [ { "Age": 38, "Status": 1, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null }, { … -
Django ownership assignment to modify or delete entries
First post here. I followed the project code in the Python Crash Course book, so if the code looks similiar that is why. In my django project, I want all the users to be able to view everything on the website. However, I want to have only the users who entered information in the entries to be able to edit and delete said entries. I know I need to assign ownership, but I'm having difficulty assigning it. currently I have a default setting enabled. For some reason if I take out the default it messes everything up. urls.py """Defines URL patterns for research_topic_database.""" # research_topic_database from django.urls import path from . import views app_name = 'research_topic_database' urlpatterns = [ # Home page path('', views.index, name='index'), # Page that shows all the research category topics. path('topics/', views.topics, name='topics'), # Detail page for a single research entry submission. path('topics/<int:topic_id>/', views.topic, name='topic'), # Page for adding a new research entry submission. path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), # Page for editing an entry. path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'), ] models.py class Topic(models.Model): """A research category for topic submissions to fall under.""" category = models.CharField(max_length=19, choices=CATEGORY_CHOICES, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" … -
Can't make live updated django site?
I have been updating code on my django site, but for some reason I cannot make it alive again. Now I get Internal Server Error... Apache/2.4.41 (Ubuntu) Server at something. When I put back old code, it works perfectly. At this update is not that big update, few small stuff. Any idea what I might messed up? -
How to process multiple variables of url parameter at once in django
Currently, the function is applied by passing only one argument to the url parameter, but considering the case of selecting multiple checkboxes, I am curious how to handle it when multiple arguments are received at once. Please help. urls.py path('student/add_teacher/<int:id>/', views.add_teacher) views.py def add_teacher(request, id): student = Student.objects.get(pk=id) student.teacher = request.user.name student.save() return HttpResponseRedirect(f'/student/') student_list.html <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Register date</th> <th>Select</th> </tr> </thead> <tbody> {% for student in student %} <tr class="text-black tr-hover table-link text-center student" student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> student_detail.js $(function () { $('button.addteacher').click(function (e) { var elem = $(".maintable input:checked").parents("tr"); var studentID = elem.attr('student-id'); var updateTeacher = confirm("업데이트하시겠습니까?"); if (updateTeacher) { window.location.href = 'student/add_teacher/' + studentID + '/'; } }); }); -
constraint validation invalid django
I try validate form but it go to the database and return the constraint validation error. form.py from django import forms from . models import Semana class FormularioSemana(forms.ModelForm): class Meta: model = Semana exclude = ['username'] #fields = '__all__' widgets = {'lunes_inicio': forms.TimeInput(attrs={'type': 'time'}), 'lunes_fin': forms.TimeInput(attrs={'type': 'time'}), 'martes_inicio': forms.TimeInput(attrs={'type': 'time'}), 'martes_fin': forms.TimeInput(attrs={'type': 'time'}), 'miercoles_inicio': forms.TimeInput(attrs={'type': 'time'}), 'miercoles_fin': forms.TimeInput(attrs={'type': 'time'}), 'jueves_inicio': forms.TimeInput(attrs={'type': 'time'}), 'jueves_fin': forms.TimeInput(attrs={'type': 'time'}), 'viernes_inicio': forms.TimeInput(attrs={'type': 'time'}), 'viernes_fin': forms.TimeInput(attrs={'type': 'time'}), 'sabado_inicio': forms.TimeInput(attrs={'type': 'time'}), 'sabado_fin': forms.TimeInput(attrs={'type': 'time'}), 'domingo_inicio': forms.TimeInput(attrs={'type': 'time'}), 'domingo_fin': forms.TimeInput(attrs={'type': 'time'}), } def __init__(self, username, *args, **kwargs): super(FormularioSemana, self).__init__(*args, **kwargs) # Set the instance's solicitante to the passed user. With this, you no longer have to do it in your views.py as well self.instance.username = username if not username.is_staff: # note that I moved the queryset filtering inside the if statement to avoid logical errors when user.is_staff is True self.fields['nombre'].queryset = nombre.stem.filter(username = request.user) def clean(self, *args, **kwargs): super().clean(*args, **kwargs) # Get the values nombre = self.cleaned_data['nombre'] username = self.instance.username # Find the duplicates duplicates = Semana.stem.filter( nombre=nombre, username=username ) if self.instance.pk: duplicates = duplicates.exclude(pk=self.instance.pk) if duplicates.exists(): raise forms.ValidationError('El nombre de la semana existe!') I think the problem is here but i dont see them views.py def index(request): … -
How to stop the Post request, if there is already the same data is in the Model
I am trying to stop the instance if the data matches in the DB. But i tried and failed again and again. My Code: models.py class Doctor(models.Model): """ Manages data of consulting doctors working in the Hospital """ user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=40) contact = models.IntegerField() department = models.CharField(max_length=50) active = models.BooleanField(default=False) def __str__(self): return f"{self.user} ({self.department})" class Patient(models.Model): """ Manages data of patient """ user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=40) contact = models.IntegerField() symptoms = models.CharField(max_length=50) active = models.BooleanField(default=False) def __str__(self): return f"{self.user} ({self.symptoms})" class Appointment(models.Model): """ Manages the appointment details """ patient_name = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='doctor') doctor_name = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name='patient') appointment_date = models.DateTimeField() active = models.BooleanField(default=False) def __str__(self): return str(self.patient_name) + " has appointment with " + str(self.doctor_name) serializers.py from rest_framework import serializers from api.models import Patient, Doctor, Appointment class AppointmentSerializer(serializers.ModelSerializer): """ Appointment serializer class """ class Meta: model = Appointment fields = "__all__" class DoctorSerializer(serializers.ModelSerializer): """ Doctor serializer class """ user = serializers.StringRelatedField(read_only=True) patient = AppointmentSerializer(many=True, read_only=True) class Meta: model = Doctor fields = "__all__" class PatientSerializer(serializers.ModelSerializer): """ Patient serializer class """ user = serializers.StringRelatedField(read_only=True) doctor = AppointmentSerializer(many=True, read_only=True) class Meta: model = Patient fields = "__all__" views.py from django.shortcuts import render from …