Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cannot upload images to DRF using React Native
I am trying to upload image from react native to django server I cannot upload it. i can get uri of image properly at the server end following error is occur _mysql.connection.query(self, query) django.db.utils.DataError: (1406, "Data too long for column 'Services_image' at row 1") my server end code class ServicesList(APIView): permission_classes = [IsAuthenticated] parser_classes = (MultiPartParser, FormParser,JSONParser,FileUploadParser) def post(self, request,): data=request.data print(data) Services.objects.create(s_name=data.get('title'),description=data.get('description'), provider_user_id=self.request.user.id, services_rate_per_hour=70,Services_image=data.get('image')) return Response(status=status.HTTP_201_CREATED) models.py Services_image=models.ImageField(upload_to='Services', blank=True,null=True) my uri of image 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540m.arshad5857%252FManagPatients/ImagePicker/214b8e7e-8027-4778-95d5-281c4a8bf356.jpg' I have no idea how to resolve this error plz answer me. How to upload image in django with proper way using react native -
Django database update
I wrote a parser that takes the name and price of the product from the url. Each product has its own url. Information about the price of goods must be constantly updated and displayed on the site. Do not tell me if it is possible every 30-60 seconds to parse all products (which are stored in the database) by url and have their data displayed on the site. (I don't know how to make the data automatically update and save to the database). -
Problem with placeholder on a django template input form field
I am creating a user login using the default django authentication system. Using a bootstrap template, I am creating a form with custom fields, and they are working correctly. The problem is that when displaying this form, it renders showing the value attribute instead of the placeholder that I have passed to it. This is who it looks: login page login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <img class="mb-4" src="{% static 'images/logo.jpg' %}" alt="" width="100" height="100"> <h1 class="h3 mb-3 fw-normal">Please sign in</h1> <div class="form-floating"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com" value="{{form.username}}"> <label for="floatingInput">Username</label> </div> <div class="form-floating"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" value="{{form.password}}"> <label for="floatingPassword">Password</label> </div> <div class="checkbox mb-3"> <label> <input type="checkbox" value="remember-me"> Remember me &emsp; <a href="{% url 'password_reset' %}"> Lost password?</a> </label> </div> <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button> <p class="mt-5 mb-3 text-muted">&copy; 2022 all rights deserved</p> </form> -
Django saving multiple forms - what's a compact way of doing this?
Is there a more compact way of writing this in Python / Django? I haven' finished this yet, but I can see it growing big quickly, as I need to include further branches for 3 other values of form7.cleaned_data.get('working_type_selection') == '3 other Options', apart from 'Employee'. If it's Employee form8 gets saved, otherwise it could be form 9, or form 10. The saving of the forms has to be the final step of each branch right? if form1.is_valid() and form2.is_valid(): if form2.cleaned_data.get('right_to_work_selection') == 'Passport' and form3.is_valid(): if form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form3.save() form7.save() form8.save() return redirect('profile_employment') if form2.cleaned_data.get('right_to_work_selection') == 'Birth Certificate & N.I. Number' and form4.is_valid() and form6.is_valid(): if form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form4.save() form6.save() form7.save() form8.save() return redirect('profile_employment') if form2.cleaned_data.get('right_to_work_selection') == 'Certificate of Registration & N.I. Number' and form5.is_valid() and form6.is_valid(): if form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form5.save() form6.save() form7.save() form8.save() return redirect('profile_employment') -
Filter model by m.Choices
On Django3, I have a model each line has tuple. class CallType(m.Choices): PUSH = (1,"Pushing",True) PULL = (2,"Pulling",False) PUNCH = (3,"Punching",False) And in form.py action_type = forms.ChoiceField( required=False, choices=sm.CallType.choices) Now I want to filter the Item like this below. action_type = forms.ChoiceField( required=False, choices=sm.CallType.filter(third_item=True) This code is of course doesn't work. However is it possible? -
How to integrate bKash payment method in Django?
i just trying to integrate payment method on my course selling app. https://github.com/RakibulIslamDigonto -
'ModelChoiceField' object is not iterable - calling objects from existing Model
Losing the will to live here lol. Can't work out what's going wrong here, I'm calling objects from a model that has values in Django Admin but every time I try to fix one thing, it breaks another. I want to be able to create a new entry from frontend, but I get this error when trying to migrate: Stack error File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py", line 784, in __init__ self.choices = choices File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py", line 801, in _set_choices value = list(value) TypeError: 'ModelChoiceField' object is not iterable Please see my model below: models.py # Model engineer_shifts = [ (0,'Shift 1), (1,'Shift 2'), (2,'Shift 3') ] class Engineer(models.Model): engineer = models.CharField(max_length=200,default="John Smith",verbose_name="Engineer") engineer_shift = models.IntegerField(choices=engineer_shifts,verbose_name="Shift") def __str__(self): return f"{self.engineer}" class Meta: verbose_name_plural = 'Engineers' class CreateHandoff(models.Model): handoff_pk = models.AutoField(primary_key=True) handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date") shift1_lead = models.IntegerField(choices=engineer_picker,verbose_name="Shift 1 Lead") shift1_sec = models.IntegerField(choices=engineer_picker,verbose_name="Shift 1 Secondary") def __str__(self): return f"{self.handoff_date}" class Meta: verbose_name_plural = 'Handoffs' # Form engineer_picker = forms.ModelChoiceField( queryset=Engineer.objects.all() ) class CreateHandoffForm(forms.ModelForm): shift1_lead = forms.ChoiceField( label = "Select Shift 1 Lead", choices = engineer_picker, required = True ) shift1_sec = forms.ChoiceField( label = "Select Shift 1 Secondary", choices = engineer_picker, required = True ) class Meta: model = CreateHandoff fields = ["shift1_lead","shift1_sec"] -
PK incrementing when adding new TestCase
I realized when I'm adding new TestCase PK in old TestCase is incrementing. For example, I'm testing .get_absolute_url method: def get_absolute_url(self): return reverse('linkdetail', kwargs={'pk': self.pk}) with this test def test_get_absolute_url(self): obj = Link.objects.get(title="test_tile") self.assertEqual(obj.get_absolute_url(), "/link/1/") and to this point everything is okay and test is passing, but when I add another TestCase class LinkCommentTestCase(TestCase): def setUp(self): user = User.objects.create(username="test", password="asd") link = Link.objects.create(title="test_tile2", link="http://google.com", author=user) comment = LinkComment.objects.create(author=user, link=link, content="asd") def test_get_comments_count(self): obj = LinkComment.objects.get(content="asd") im getting this error ====================================================================== FAIL: test_get_absolute_url (links.tests.test_models.LinkTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/x/Desktop/x/links/tests/test_models.py", line 72, in test_get_absolute_url self.assertEqual(obj.get_absolute_url(), "/link/1/") AssertionError: '/link/2/' != '/link/1/' - /link/2/ ? ^ + /link/1/ ? Why is this happening and how can I prevent this? -
Unique field case insensitive constraint
I am trying to ensure that all tags are unique when converted to lowercase. However, when I run the migrate on the following model I receive the following error: api.Tag: (models.E012) 'constraints' refers to the nonexistent field 'Lower(F(name))'. class Tag(models.Model): name = models.CharField(max_length=30) class Meta: constraints = [ models.UniqueConstraint( fields=[Lower('name')], name='unique_name' ), ] -
how to call back calculation function after fadeout a row
I'm trying to recalculation after removing a row from a form using fadeout to disappear the removing form, i depend on checkbox to removing the rows, if checked then it will be disappear here is my code : function counting(result) { document.getElementById("total_price").value= parseFloat(result).toFixed(2); } function countingReceive(result) { document.getElementById("total_receive").value= parseFloat(result).toFixed(2); } function countingQarz(result) { document.getElementById("total_loan").value= parseFloat(result).toFixed(2); } function countingDiscount(result) { document.getElementById("total_discount").value= parseFloat(result).toFixed(2); } counting(0); countingLoan(0); countingDiscount(0); countingReceive(0); function totalSumField () { let inp = document.querySelectorAll("#form-imeilists > .child_imeiforms_row"); let result=0; for(let i=0;i<inp.length;i++){ let nrx=inp[i].getElementsByClassName("nrx")[0].value; let kash=inp[i].getElementsByClassName("cash")[0].value; let dashkandn=inp[i].getElementsByClassName("dis")[0].value; inp[i].getElementsByClassName("loan")[0].value=((nrx - dashkandn)-kash).toFixed(2); } } function totalSum () { let inp = document.querySelectorAll("#form-imeilists > .child_imeiforms_row"); let result=0; let qarz=0; let discount = 0; let receive = 0; for(let i=0;i<inp.length;i++){ let nrx=inp[i].getElementsByClassName("nrx")[0].value; let kash=inp[i].getElementsByClassName("cash")[0].value; let dashkandn=inp[i].getElementsByClassName("dis")[0].value; result+=nrx-dashkandn; loan+=(nrx-dashkandn)-kash; discount+= parseFloat(dashkandn); receive+=parseFloat(kash) } countingLoan(loan); counting(result); countingDiscount(discount); countingReceive(receive); totalSumField() } $("#create-customer-invoice").on("click","input:checkbox",function(){ mythis = this $(mythis).closest('.child_imeiforms_row').fadeOut(); totalSum() // this doesnt work }); <form action="" method="POST" id="create-customer-invoice">{% csrf_token %} {{imei_forms.management_form}} <div id="form-imeilists"> {% for imei in imei_forms %} {{imei.id}} <div class="child_imeiforms_row"> <div class="row no-gutters table-bordered"> <div class="col-md-3"> <div class="form-group"> {{imei.item | add_class:'form-control imei_choose' |append_attr:"onChange:check_imie_collection(this);this.oldvalue = this.value;"}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-2"> <div class="form-group"> {{imei.price | add_class:'nrx'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-1"> <div class="form-group"> … -
Can't fetch particular data from database using session Obj. How can I do that in Django?
def register(request): userID = random.randint(1000, 9999) if request.method == 'POST': # got error in this ("MultiValueDictKeyError generated in Django after POST request on login page") # register_id = request.POST[userID] -| # can use both methods request.POST[] & request.POST.get() # user_name = request.POST.get('username') user_name = request.POST['username'] # user_email = request.POST.get('useremail') user_email = request.POST['useremail'] # password1 = request.POST.get('pass') password1 = request.POST['pass'] # password2 = request.POST.get('repass') password2 = request.POST['repass'] # request.session['regid'] = userID # request.session['usnm'] = user_name if user_name and user_email and password2 and password2: if password2 == password1: recsave = user_registration() recsave.regid = userID recsave.username = user_name recsave.useremail = user_email recsave.userpassword = password2 recsave.save() return redirect('/login') else: notmatch = {'passnotmatch': 'Passwords are not match'} return render(request, 'testpage1.html', notmatch) else: return render(request, 'testpage1.html') This is login where we have a session Where I used req.session['userid'] but I didn't get the other data of particular user from the database. def login(req): if req.method == 'POST': oth = user_registration.objects.get(useremail=req.POST.get('useremail'), userpassword=req.POST.get('pass')) if oth: print('You are logged in', oth) req.session['userid'] = oth.regid req.session['username'] = oth.username return render(req, 'userdash.html') else: return render(req, 'login.html', {'oth': "Credentials are not perfect"}) else: return render(req, 'login.html') def userdash(req): if req.session.has_key('userid'): usnm = req.session.get('userid') uname = req.session.get('username') allfields = user_registration.objects.contains(uname) return render(req, 'userdash.html', … -
Django ChoiceField is not rendering /n as a new line?
I want to Display Strings with New Lines in ChoiceField form but it is rendered in just one line... s = "name: x \n email: x@gmail.com" But after it's rendered it's showing like this: name: x email: x@gmail.com And not like this: name: x email: x@gmail.com Please suggest me some workaround in the backend and not in the frontend part. -
Customize default message djangorestframework-simplejwt retrieved when the user is not active?
I'm using Django==4.0.3 ,djangorestframework==3.13.1 and djangorestframework-simplejwt==5.1.0 and djoser==2.1.0 I have used djoser to authenticate, and all works fine. When the user is not active yet, the response is same as when user enter wrong password {"detail":"No active account found with the given credentials"} I need to customize this response. I have checked this message inside a dictionary in the class TokenObtainSerializer default_error_messages = { 'no_active_account': _('No active account found with the given credentials') } have tried to override this class with no success. Any ideas? Thanks -
Why django not storing files in media folder?
My settings.py MEDIA_ROOT='/static/' MEDIA_URL='media' My urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns=[ #all routes ] if settings.DEBUG: urlpatterns+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This code works fine many time but this is not working, I don't know why? -
AWS Elastic BeanStalk - Django Deployment failed (Error: chown /var/app/staging/env/bin/python: no such file or directory)
I am trying to deploy my django application to AWS beanstalk and i get the following error 2022/03/05 08:06:43.401505 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_sourc e_bundle -d /var/app/staging/ 2022/03/05 08:06:45.020761 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging / successfully 2022/03/05 08:06:45.024804 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop run ning the command. Error: chown /var/app/staging/env/bin/python: no such file or directory 2022/03/05 08:06:45.024814 [INFO] Executing cleanup logic 2022/03/05 08:06:45.024928 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAI LURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed. For de tails, see 'eb-engine.log'.","timestamp":1646467605,"severity":"ERROR"}]}]} My configuration file is as follows option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "src.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "src.wsgi:application" Can someone please tell me what i could be doing wrong? Do note that i am not currently using any environment variables in an external files throught my django settings -
Error while inserting data in database using Ajax in Django after validating the ModelForm
I am creating a Django ModelForm It is partially working as if I do not validate the form i.e. if I remove if form.is_valid(): statement from the code then values got inserted in the database but if I use it, then it shows error in the console as print("Errors ", form_to_insert_data.errors) as: <ul class="errorlist"><li>name<ul class="errorlist"><li>write name</li></ul></li><li>ini_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>dev_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>mid_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>end_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>ini_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>dev_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>mid_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>end_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>root_len<ul class="errorlist"><li>This field is required.</li></ul></li></ul> However, I am inserting all the values properly in the form i.e. noting is left blank. and if I don't pass print("Errors ", form_to_insert_data.errors), then the error appears as Internal Server Error: /url_for_crop_data_to_insert Traceback (most recent call last): File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 188, in _get_response self.check_response(response, callback) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 309, in check_response raise ValueError( ValueError: The view waterbalance.views.save_inserted_cropdata didn't return an HttpResponse object. It returned None instead. The code is as below Model from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class CropDetail(models.Model): name = models.CharField(max_length=100) ini_stg = models.PositiveIntegerField(validators=[MinValueValidator(0.0), MaxValueValidator(100.0)]) dev_stg = models.PositiveIntegerField(validators=[MinValueValidator(0.0), MaxValueValidator(100.0)]) mid_stg = models.PositiveIntegerField(validators=[MinValueValidator(0.0), MaxValueValidator(100.0)]) … -
Django : What does "%" mean in self.success_messages % fiche.__dict__
Since I've been leaning Python, I have often seen and used : class FicheDeleteView(LoginRequiredMixin, DeleteView): model = Fiche success_url = reverse_lazy('fiche-list') success_messages = "La Fiche %(ref_id)s a bien été supprimée" def delete(self, request, *args, **kwargs): fiche = self.get_object() messages.success(self.request, self.success_messages % fiche.__dict__) return super(FicheDeleteView, self).delete(request, *args, **kwargs) Even if I see this mechanic's effects, I'm not really sure to understand. Does it mean : I send to the "reverse-lazy" all the FICHE dict and in my message.success I retrieve the fiche.ref_id with %(ref_id)s ? -
How to get all id from model in django
views.py e = FRUser.objects.get(id) print(e) models.py from django.db import models from django.contrib.auth.models import User from app_user_mngmt.models.image import Image from django.contrib.postgres.fields import ArrayField from .frtemplate import FRTemplate ## Table for saving FRUser details. class FRUser(models.Model): image = models.ForeignKey(to=Image, on_delete=models.CASCADE, null=True) frtemplate = models.ForeignKey(to=FRTemplate, on_delete=models.CASCADE, null=True) name = models.TextField(null=True) user_type = models.TextField(null=True) uid = models.TextField(null=True) company_name = models.TextField(blank=True, null=True) visit_purpose = models.TextField(blank=True, null=True) employee_number = models.TextField(blank=True, null=True) designation = models.TextField(blank=True, null=True) valid_from_date = models.DateField(null=True) valid_till_date = models.DateField(null=True) valid_from_time = models.TimeField(null=True) valid_till_time = models.TimeField(null=True) is_blacklisted = models.BooleanField(default=False, null=True) is_other_visit_purpose = models.BooleanField(default=False, null=True) How to get all uid from FRUser model in views How to do code for to get all uid from FRUser model database Thanks in advance -
django can't edit js file
I'm trying to edit config file config.js of ckeditor in http://127.0.0.1/static/ckeditor/ckeditor/config.js for django after I add this two line config.allowedContent = true; config.ignoreEmptyParagraph = false; if I refresh the url I get a file without the lines I added CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; }; if I do python manage.py collectstatic --noinput --clear the file return back as it was without the 2 lines I added -
How to specify field choices in django inlineformset
I wish to only display a subset of the choices for a model form field. E.g Depending on the url the user is at I might want only 'weight gain' and 'parkinsonism' displayed as options for the 'se_name' field. I can work out how to get the url as a parameters in the view (p = self.request.GET.get("p", None)) But I cant work out how to use this parameter to limit the choices available. This is the formset SideeffectFormSet = inlineformset_factory( Case, SideEffect, fields=("se_name",), widgets={'concern': RangeInput()}, extra=0, min_num=1, validate_min=True, ) Which is based on the model: class SideEffect(TimeStampedModel): SE_CHOICES = [ ("weight_gain", "Weight Gain"), ("parkinsonism", "Parkinsonism"), ("dystonia", "Dystonia"), ("none", "None"), ] se_name = models.CharField("",max_length=200, choices=SE_CHOICES, default="none") case = models.ForeignKey(Case, on_delete=models.CASCADE) And the form is rendered by this view: class CaseView(LoginRequiredMixin, TemplateView): model = Case template_name = "se_balance/se_balance.html" def get(self, *args, **kwargs): p = self.request.GET.get("p", None) sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none(),) return self.render_to_response( { "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) -
Altering a Django model values based on a few conditionals? What is the best practice way to do this?
I have the model SyncCollector that has the field status. status is one of statusIntervalEnum. I want to change the existing ones that are statusIntervalEnum.DYNAMIC to 'statusIntervalEnum.STATIC. Now I know that I can do a SyncCollector.objects.filter(status=statusIntervalEnum.DYNAMIC) and loop through all of them and save them and perhaps trigger it through a custom endpoint that I later take away, but what is the best way to do this for a production instance? Making a fake endpoint that I just call in prod to run this seems very hacky. -
having this particular problem... in installing react
p reactapp_clones Creating a new React app in C:\Users\Eduur\reactapp_clones. You are using npm 3.5.3 so the project will be bootstrapped with an old unsupported version of tools. Please update to npm 6 or higher for a better, fully supported experience. Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts... npm ERR! Windows_NT 10.0.19042 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Users\Eduur\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "install" "--no-audit" "--save" "--save-exact" "--loglevel" "error" "react" "react-dom" "react-scripts@0.9.x" npm ERR! node v16.14.0 npm ERR! npm v3.5.3 npm ERR! primordials is not defined npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! https://github.com/npm/npm/issues npm ERR! Please include the following file with any support request: npm ERR! C:\Users\Eduur\reactapp_clones\npm-debug.log Aborting installation. npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts@0.9.x has failed. Deleting generated file... package.json Done. C:\Users\Eduur> -
Filtering ArrayField by entire and exact array only?
I have a slug ArrayField on a model. How can I filter or get by the entire exact array only? I'm currently doing something like this: search = f'["a", "b", "c"]' list = search[2:-2].split("', '") dict = {} for n, item in enumerate(list): dict[f"slug__{n}"] = item obj = queryset.filter(**dict) However, this returns any object where the slug begins with "a", "b", and "c". E.g. ["a", "b", "c"] ["a", "b", "c", "d"] ["a", "b", "c", "d", "e"] ["a", "b", "c", "123"] How do I do a filter or get so that only the entire and exact slug match returns? I.e. obj only returns objects with a slug of ["a", "b", "c"] -
Need to restrict access to view only their inputted data or assigned data in the django admin
User model class User(models.Model): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.OneToOneField(Default_User,on_delete=CASCADE) dob=models.DateField(max_length=8) email=models.EmailField(max_length=25,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneNumberField() emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) class Meta: db_table ='User' def __str__(self): return str(self.id) Job model class Job(models.Model): job_name=models.CharField(max_length=50) client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client',default=None) #project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project',default=None) project = ChainedForeignKey(Project,chained_field="client", chained_model_field="client",show_all=False, auto_choose=True, sort=True) user=models.ForeignKey(User,on_delete=CASCADE,related_name='user',default=None) hours=models.TimeField(null=True) start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) class Meta: db_table ='Job' def __str__(self): return '{} {}'.format(str(self.id), self.job_name) admin.py class StaffAdmin(admin.ModelAdmin): '''def get_queryset(self, request): qs = super().get_queryset(request) print(f"\nrequest.user : {request.user}\n") if request.user.is_superuser: return qs return qs.filter(user__id=request.user.id)''' def get_queryset(self, request): qs = super().get_queryset(request) user = request.user if user.is_superuser: return qs return qs.filter(user_id=request.user.id) custom user model class Default_User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) email = models.EmailField(max_length=250, unique=True) first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', ] I have given a privilege for the staff users to view, edit and delete the Job API, but I need to restrict to view only their job assigned to that users and edit and delete the jobs which the user have added. But in the … -
Django restfamework put method not working
I am creating a rest api using DRF the get and post method work perfectly but the put method doesnt update the request this is my views.py from django.shortcuts import render from rest_framework import viewsets # Create your views here. from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from BarakaSalesSystemApp.models import Farmer from BarakaSalesSystemApp.serializers import FarmerSerializer def list(self, request): farmer = Farmer.objects.all() serializer = FarmerSerializer(farmer, many=True, context={"request": request}) response_dict = {"error": False, "message": "All Farmers List Data", "data": serializer.data} return Response(response_dict) def create(self, request): try: serializer = FarmerSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) serializer.save() dict_response = {"error": False, "message": "Farmers Data Saved Successfully"} except: dict_response = {"error": True, "message": "Error During Saving Farmers Data"} return Response(dict_response) def update(self, request, pk=None): try: queryset = Farmer.objects.all() farmer = get_object_or_404(queryset, pk=pk) serializer = FarmerSerializer(farmer, data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) serializer.save() dict_response = {"error": False, "message": "Successfully Updated Farmer Data"} except: dict_response = {"error": True, "message": "Error During Updating Farmer Data"} return Response(dict_response) farmer_list = FarmerViewSet.as_view({"get": "list"}) farmer_create = FarmerViewSet.as_view({"post": "create"}) farmer_update = FarmerViewSet.as_view({"put": "update"}) and this is my serializer.py from rest_framework import serializers from BarakaSalesSystemApp.models import Farmer, Customer, Order, Bill, Employee, Delivery class FarmerSerializer(serializers.ModelSerializer): class Meta: model = Farmer fields = ["name", "address", "contact", "in_stock"] When …