Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Client-Side Encryption using boto3
So i'm using "S3Boto3Storage" as my django "file storage" and i have done "server side encryption" for file upload but i want to do "client side encryption" before file uploads to aws. I have read few articles about client side encryption but those solutions are helpful when file is already uploaded to aws. Pls help -
How to pass Django choice key to template using Elasticsearch
I'm trying to implement faceted search using django-elasticsearch-dsl and python-elasticsearch-dsl, but I am having problems mapping keys to values, when displaying them in templates. Let's say I have a model like this. class Record(models.Model): # Other fields.. status = models.CharField(max_length=255, choices=( (0, 'New'), (1, 'Pending'), (2, 'Completed') )) @property def status_to_string(self): return self.get_status_display() Then I defined my Document @registry.register_document class RecordDocument(Document): status = fields.KeywordField(attr='status_to_string') class Index: name = 'records' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Record fields = ['status'] When the data get's indexed, the value of the status field is a string (New, Pending,..), but the value in the database is still an integer. I then continue adding FacetedSearch like this. class RecordSearch(FacetedSearch): index = 'records' doc_types = [RecordDocument, ] fields = ['status'] facets = { 'status': TermsFacet(field='status') } And run the actual search rs = RecordSearch() response = rs.execute() So far so good, now when I access the results in the template, I can see statuses with respective document count. My question and concern is; the search keyword in this case is a string New or Pending and not 0 or 1. As far as I can see, my search is working, but it … -
'MoneyField' object has no attribute 'serialize'
I have model Product with field MoneyField im /products/models.py class Product(SeoModel, ModelWithMetadata, PublishableModel): name = models.CharField(max_length=128) currency = models.CharField( max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH, default=settings.DEFAULT_CURRENCY, ) price_amount = models.DecimalField( max_digits=settings.DEFAULT_MAX_DIGITS, decimal_places=settings.DEFAULT_DECIMAL_PLACES, ) price = MoneyField(amount_field="price_amount", currency_field="currency") Also, i have model MoneyField(NonDatabaseFieldBase) in django_prices/models.py. My views.py is: from .models import Product from .serializers import ProductListSerializer from rest_framework import generics class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductListSerializer class ProductDetail(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductListSerializer and serializers.py: from rest_framework import serializers from .models import Product class ProductListSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['name', 'id'] and when i go to url i have error: AttributeError at /ru/products/api/ 'MoneyField' object has no attribute 'serialize' Request Method: GET Request URL: http://127.0.0.1:8000/ru/products/api/ Django Version: 2.2.6 Exception Type: AttributeError Exception Value: 'MoneyField' object has no attribute 'serialize' Can you help me? Thank you! -
Why 'select_realted()' doesn't work in django models?
I'm trying to make 'inner join' from superclass and subclass. The codes of superclass and subclass are as below: SUPERCLASS: class Group(models.Model): # [column name] = model.[column type].(conditions of column) address = models.CharField(max_length=255, blank=True, null=True) area = models.FloatField(blank=True, null=True) num_person = models.CharField(max_length=255, blank=True, null=True) severity_average = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'group' def create_group(self, address, area, num_person, severity_average): self.address = address self.area = area self.num_person = num_person self.severity_average = severity_average try: self.save() # execute query return True except: return False def retrieve_group(self, address=None, area=None, num_person=None, severity_average=None): queryset = Group.objects try: if address is not None: queryset = queryset.filter(address=address) if area is not None: queryset = queryset.filter(area=area) if num_person is not None: queryset = queryset.filter(num_person=num_person) if severity_average is not None: queryset = queryset.filter(severity_average=severity_average) return tuple(queryset.values()) except: return () def update_group(self, address=None, area=None, num_person=None, severity_average=None): if address is not None: self.address = address if area is not None: self.area = area if num_person is not None: self.num_person = num_person if severity_average is not None: self.severity_average = severity_average try: self.save() # execute query return True except: return False def delete_group(self): try: self.delete() return True except: return False SUBCLASS: class Facility(models.Model): # [column name] = model.[column type].(conditions of column) facility_type … -
Fetch ID of a model and save to other model's foreign key field in django
I have a User model using AbstractBaseUser. I have a model Employee using Model class. I want that when a user is created through sign up, the user inherits all the fields of Employee model. I have made a OnetoOne relation between User model and Employee. But after creating an user when I query employee model, I can not find any data related to the created User. User manager: class UserManager(BaseUserManager): """ Creates and saves a User with the given email and password. """ def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email,username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user User: class User(AbstractBaseUser): """ Creates a customized database table for user """ email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] objects = UserManager() def get_full_name(self): # The user is identified by their email address … -
Counting page views for a User uploaded PDF in Django
I have a webapp where a user can upload a pdf. I want to be able to see how many times the PDF is viewed by other user, all of which would be anonymous users. At the moment I didn't have to write a view to view the PDF, in the 'view PDF' button i Just link the uploaded PDF's URL, which directs to the PDF document. Button to view PDF <a href="{{ doc.File.url }}" class="btn btn-outline-secondary" style="margin: 2px;">View PDF</a> The issue arises, in that when a user uploads a PDF doc, i create a qr code which contains the URL of that doc. So i only want to count the views that are from the qr scan in, and not redirected from the button. How can i do this seeing as i don't actually have a view to render the PDF? One way i was thinking of is writing a return redirect view, with an incrementer for the views instance in the model? or to use the Django F() statement to pull in the views instance and then increment it. Any ideas? -
Render Folder Structure on webpage with Django
I have a root folder, containing other folders and XML-files. I would like to show the folder contents just like in windows-explorer on my webpage. For example: folder_1 txt_file_1 txt_file_2 folder_2 folder_3 txt_file_3 How can I render the directory in this way? -
trying to save django form data after submit to a thankyou page with details
If I add redirect url in form submit page, the page is redirecting but the form data is not being saved to db. If I remove the redirect url, form data is getting saved but my redirect doesn't work. I need to redirect to a page with the details of the event along with a thank you message. Please let me know where I am going wrong.. #forms.py class UserForm(forms.ModelForm): class Meta: model = webinar_user fields = ['first_name', 'last_name', 'email_id', 'contact_no', 'city', 'state','postal_code','country','company'] #views.py def post_detail(request, slug): template_name = "site/new_form.html" event = get_object_or_404(webinar_event, slug=slug) # event = get_object_or_404(webinar_event, pk=post_id) # success_url = "events:thankyou" user_data= None if request.method == "POST": user_form = UserForm(data=request.POST) print("form") if user_form.is_valid(): print("form valid") user_data= user_form.save(commit=False) user_data.event= event req= user_data.save() subject = 'Thank You for registering for the webinar' context={'first_name':user_data.first_name, 'title':event.title, 'description':event.about_event, 'event_date':event.event_date, 'event_time':event.event_time, 'event_duration':event.event_duration} message = get_template('site/emails/thank_you.html').render(context) email_from = settings.EMAIL_HOST_USER email_id = user_form.cleaned_data['email_id'] recipient_list = [email_id, ] email = EmailMessage(subject, message, email_from, recipient_list) email.content_subtype = 'html' email.send() return HttpResponseRedirect('events:thank_you', kwargs={'id':req.id}) ) else: user_form = UserForm() return render( request, template_name, { "event": event, "user_data":user_data, "user_form": user_form }, ) def thank_you(request, id): event = webinar_event.objects.get(pk=id) return render(request, 'site/thankyou.html', {'event' : event}) html code <div class="testbox"> {% if event.event_image … -
Nested serializers getting only one instance of a model
I'm working on my first project. I'm working with a headless wagtail cms. The api should print out the link i put in in the wagtail admin page. I added multiple links to every team but only the last made team prints out a link and its only the first link i made for that team. I presume i'm using the wrong foreign keys but i just can't figure it out. serializers.py class LinkChannelSerializer(serializers.ModelSerializer): class Meta: model = LinkChannel fields = ['name', 'icon'] class TeamLinkSerializer(serializers.ModelSerializer): channel = serializers.SerializerMethodField() class Meta: model = TeamLink fields = ['team', 'channel', 'url', 'title'] def get_channel(self, obj): channel = LinkChannel.objects.filter(team_links=obj) print(channel) return LinkChannelSerializer(channel, many=True).data class TeamsSerializer(serializers.ModelSerializer): value_tag_motivations = ValueTagMotivationsSerializer(many=True) hero = ImageSerializer() logo = ImageSerializer() links = serializers.SerializerMethodField() class Meta: model = TeamPage fields = [ 'id', 'title', 'tagline', 'value_tags', 'logo', 'hero', 'value_tag_motivations', 'vacation_policy', 'tech_stack', 'team_members', 'locations', 'interview_process', 'mission_statement', 'links' ] def get_links(self, obj): links = TeamLink.objects.filter(team=obj) print(links) return TeamLinkSerializer(links, many=True).data models.py class TeamPage(Page): """A team profile""" parent_page_types = [JobboardHomePage] subpage_types = ["OpenPositionPage", "OpenPositionLink"] logo = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", help_text="Company logo, square", ) tagline = models.CharField(max_length=255) hero = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", help_text="Hero banner for the top of the page, … -
Unable to save empty list to Django ArrayField
I have a Django model from django.db import models from django.contrib.postgres.fields import ArrayField class Website(models.Model): id = models.BigAutoField(primary_key=True, verbose_name='ID') status = models.BooleanField(default=True) meta = ArrayField(base_field=models.CharField(max_length=200, null=True), default=list) I'm using following serializer to save data to the DB: class WebsiteConfigSerializer(serializers.ModelSerializer): class Meta: model = Website fields = ('status', 'meta') When I'm trying to save the following data, I'm getting error: { "status": true, "meta": [] } #ERROR: # "meta : This list may not be empty." Is it not possible to save an empty list to an ArrayField ? When I'm not passing the field at all, the value getting stored is {NULL}. Also during initial migrations, since I had added a default value as list, all my existing entries had "meta" value as {} If the empty list value is not allowed at all, how come this got saved during initial migration ? -
Django Admin loading without css
I had created a new Django app, and I noticed it's admin page was loading without css. I set the STATIC_URL and the STATIC_ROOT in settings.py according to this solution, but it still does not work. After some digging, I found this error when I open Chrome Dev Tools on Admin Page [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/base.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/responsive.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/login.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/responsive.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page]/:1 Refused to apply style from 'http://[my_web_page]/static/admin/css/login.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page]/:1 Refused to apply style from 'http://[my_web_page]/static/admin/css/base.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking … -
Is there a way to filter in Django using the equal magic method?
Some background just in case there is a better way to do this other than the way I am trying: I am requesting data of a rest API. When the data is received I want to check if a model containing this data already exists. The rest API does not give an ID for data entry so I cannot use this to see if a model instance already exists. I have created an equal magic method for the model that checks several of the fields to see if they are equal and returning the appropriate boolean. This works fine when checking for example if instance == other_instance. The issue arises when I try to filter or get to check the DB. breach = Breach.objects.get(self=breach1) I could check by specifying the fields each time but this would lead to some duplicated code over time and make the code base maintainable. I am still newish to using Django so apologies if Django has a simple way of doing this. -
Django formset with queryset doesn't fill out all the fields of formset with initial values
I have the following code to get a formset: patient = Patient.objects.get(id=pk) prescription = Prescription.objects.get(patient=patient) formset = PrescriptionLineFormSet(queryset=prescription.line_prescription.all()) The form is very simple too: PrescriptionLineFormSet = modelformset_factory(PrescriptionLine, fields='__all__', extra=1, ) in the template I display the formset in a table: {{ formset.management_form }} <table class="table table-bordered"> {{formset.as_table}} </table> The problem is that not all attributes of the PrescriptionLine model are set with the initial values. Not even the default values are given. But one field is always set no matter what solution out of the internet I try (and I tried so many). Why is that happening? Why is it only working for the first field? -
Query on User related Object in Django
In my Application I am trying to query a field which in depth requires a reverse lookup. Let me explain by Models Models.py class User(AbstractUser): is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_name = models.CharField(max_length=500, default=0) class MaterialRequest(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) flows = models.ManyToManyField(MaterialRequestFlow) is_allocated = models.BooleanField(default=False) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) send_from_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE) Now I want to query Allotment which are created by a particular Client. In the frontend I have a dropdown of Clients which sends the id of the Client Here's my function for this: Views.py class AllotmentReport(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): cname = self.kwargs['cname'] if self.kwargs['cname']: items = Allotment.objects.filter(sales_order__owner??? = cname).order_by('-id') #Need Help Here else: items = Allotment.objects.all().order_by('-id') serializer = AReportSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) Also I'd like to know If there is a better alternative to do that -
How can I sort a list of models considering one element of a many-to-many relation?
We're building an API using Django Rest Framework where I have the following schema: class Main(models.Model): name = models.CharField(default=None, max_length=200, blank=True, null=True) # [...] class Attribute(models.Model): main = models.ForeignKey('Main', on_delete=models.CASCADE, related_name='attrs') code = models.CharField(max_length=50, null=True) value = models.CharField(max_length=50, null=True) I want to build a queryset (paginated) for a list of Main objects and I would like to sort them using the "value" of certain Attribute "code". For example, if we suppose three attributes are: "age" (8-18), "grade" ("A", "B", "C", etc.), "stars" (0-5) and Main were "students" I would like to be able to build a queryset for the list of students ordered by "age" and "grade" values. I've tried something like: queryset = Main.objects.filter(id__in=ids).filter(attrs__code='age').order_by(attrs_value) Extra: Woud I be able to reach a multiple attr order? -
How to filter certain fields in Django Rest Framework
I have two models, one is Product and second is paymentInvoice that are connected by a foreign key. I want to get all the invoice details where the product field has the qty_amount='20L'. Product Model class Product(models.Model): Qty_Choices = ( ('250ml', '250ml'), ('500ml', '500ml'), ('1L', '1L'), ('5L', '5L'), ('20L', '20L') ) slug = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200) available = models.BooleanField(default=True) description = models.TextField(blank=True) image = models.ImageField(default='default_product.jpg', upload_to='product_photos') category = models.CharField(max_length=200) qty_amount = models.CharField( max_length=20, choices=Qty_Choices, default='250ml') price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name paymentInvoice Model class paymentInvoice(models.Model): class paymentStatus(models.TextChoices): PENDING = 'Pending' PAID = 'Paid' DELIVERED = 'Delivered' class paymentMode(models.TextChoices): MPESA = 'Mpesa' BANK = 'Bank' CHEQUE = 'Cheque' CASH = 'Cash' shipping_address_owner = models.ForeignKey( ShippingAddress, on_delete=models.CASCADE, related_name="customer_invoice") product = models.ManyToManyField( Product, related_name='product_invoice') mode = models.CharField(max_length=20, choices=paymentMode.choices, default=paymentMode.MPESA) date = models.DateField(default=datetime.now) invoice_id = models.CharField(max_length=50, unique=True) quantity = models.PositiveSmallIntegerField() status = models.CharField( max_length=20, choices=paymentStatus.choices, default=paymentStatus.PENDING) total_payment = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.shipping_address_owner.customer.name My views.py file for my invoice is displayed below. class paymentInvoiceListCreateView(ListCreateAPIView): """ ListCreateAPIView executes both 'GET' and 'POST' requests. i.e listing a queryset or creating a model instance. """ serializer_class = paymentInvoiceSerializer queryset = paymentInvoice.objects.order_by( '-date').filter(product.qty_amount="20L") The filter method i used above does not work. Kindly … -
Django Channel - Redis integration error : aioredis.errors.ReplyError: ERR unknown command 'EVAL'
I am new to Django channels and following the tutorial ( https://channels.readthedocs.io/en/latest/tutorial/part_2.html) As Redis does not support Windows 7 I downloaded Redis version 2.4 from (https://github.com/dmajkic/redis/downloads) When I try to access the Redis from Django shell I got error as mentioned in the subject. $ python3 manage.py shell >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) >>> async_to_sync(channel_layer.receive)('test_channel') # ERROR OCCURED AFTER THIS STEP As you can see below, the Redis folder , it start dev server at port 6379. -
Field 'id' expected a number but got '_delacruzjuan'
I am trying to put a decimal field form in my accounts.html but whenever I visit the page I created, I always get this traceback error Here is my code in my views.py class UserAccountsView(UpdateView): """ Shows user total income and withdraw money. """ model = User fields = ['money_withdraw'] # Keep listing whatever fields template_name = 'users/accounts.html' def form_valid(self, form): """ Checks valid form and add/save many to many tags field in user object. """ user = form.save(commit=False) user.save() form.save_m2m() return redirect('users:user_account', self.object.username) def get_success_url(self): """ Prepares success url for successful form submission. """ return reverse('users:user_account', kwargs={'username': self.object.username}) Here is the portion of my accounts.html containing the money_withdraw I am trying to put. <form method="post" novalidate enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.money_withdraw | as_crispy_field}} </div> </div> <br> <div class="col text-center"> <button type="submit" style="color:#FFFFFF; background-color:#213b52; border: 3pt lightgrey" class="btn btn-success">Request Money</button> </div> </form> I already tried putting the money_withdraw to other .html and it is working fine. I even tried putting it on admin.py and I can access and edit it on the admin page. -
Reducing queries on serialization with SerializerMethodField
I currently have a serializer which uses two SerializerMethodField that access the same nested object, resulting in two db calls: # models.py class Onboarding(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_retailer_created = models.BooleanField(default=False) is_complete = models.BooleanField(default=False) # views.py class StateView(RetrieveAPIView): serializer_class = serializers.UserSerialiser def get_object(self): return self.request.user # serializers.py class UserSerialiser(serializers.ModelSerializer): is_onboarded = serializers.SerializerMethodField() is_loyalty_onboarded = serializers.SerializerMethodField() class Meta: model = models.User fields = ('is_onboarded', 'is_loyalty_onboarded') def get_is_onboarded(self, obj): onboarding = obj.onboarding_set.first() if onboarding: return onboarding.is_retailer_created return False def get_is_loyalty_onboarded(self, obj): onboarding = obj.onboarding_set.first() if onboarding: return onboarding.is_complete return False I'd like to roll this into one call if possible. Normally it would be possible to just use prefetch_related, but since the get_object is returning the specific user (and not a queryset) I don't think that solution works here. Is there a way to prefetch the Onboarding model with the user? Or failing that have a single call to Onboarding instead of two? -
Creating a website like Amazon where user can create an account for selling their products with Django
I am basically working on creating a website like Amazon where user can create an account for selling their products with Django, how do I achieve that, should I create a Django group name shopkeepers, kindly please tell me what is the best way to do that -
Django Pagination not working as expected
I am new to Django, and trying to paginate a dictionary objects,However I am unable to so and not getting what's wrong with my code. Above I have posted my View along with template code. class Search(ListView): paginate_by = 5 def get(self, request): if 'search' in request.GET: search = request.GET['search'] url = 'https://api.stackexchange.com/2.2/search/advanced?&site=stackoverflow' params = dict(item.split("=") for item in search.split(",")) req = PreparedRequest() req.prepare_url(url, params) stackoverflow_url = req.url response = requests.get(stackoverflow_url) data = response.json() #Data will be like this # data={{'tag':'python','question':'some question'},{'tag':'java','question':'some question'}} # n here is 2 paginator = Paginator(list(data), 5) page_number = request.GET.get('search') page_obj = paginator.get_page(page_number) return render(request, 'stackoverflow.html', { 'data': data, 'page_obj': page_obj }) Above is my template {%if data %} <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for key,value in data.items %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ value.title }}</h2> <p class="card-text text-muted h6">{{ value.creation_date }} </p> <p class="card-text text-muted h6"> Asked By</p> <a href="{{value.owner_link}}">{{value.display_name }} </a> <p class="card-text"></p> <a href="{{value.link}}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> </div> </div> <div class="pagination"> <span class="page-links"> {% if value.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of … -
why my file input multiply and send the same image twice?
so i have this ajax script to shown the image that the admin send to client but i have problem is that everytime the admin upload new image the script keep doubleing and send image twice for example if the admin upload first image it shown one image and the admin add a new image <-- and here the problem start it double the image that being upload (now it sending the same image twice and so on) how can i fix this? i don't know if my backend is the problem or my ajax script, here is my code and thank you. my ajax script $("#btn-file-input").on("click",function(){ $("#file-input").trigger("click"); $('#file-input').change(function () { var value = $(this).val(); var form = new FormData(); var dat = $('#file-input').prop('files')[0]; console.log(dat) form.append("image-user",dat); form.append("id_user",id_user); for(var q of form.entries()){ console.log(q[0]+ ', ' + q[1]); } $.ajax({ processData: false, contentType: false, async: false, cache: false, type: "POST", url: "updateimage", data: form, success: function(result) { var result_json = JSON.parse(result) console.log(result_json) } }); }); }); my backend @csrf_exempt def admin_send_image(request): data_ajax_r = request.FILES.get('image-user') id_user = request.POST.get('id_user') user = UserMessage.objects.get(line_id=id_user) admin_now = Account.objects.get(id=request.user.id) file_storage = FileSystemStorage() file_storage.save(data_ajax_r.name,data_ajax_r) url_object = file_storage.url(data_ajax_r.name) url_to_line ='https://c93c90ff8ee8.ap.ngrok.io'+url_object line_bot_api.push_message(user.line_id,[ImageSendMessage(url_to_line,url_to_line)]) ctx = {"admin_name":admin_now.username,"file_name":url_object,"admin_image":"/media/"+str(admin_now.gambar)} return HttpResponse(json.dumps(ctx)) here is screen shot … -
django check if a field has changed
This is my update function, where I can update my order details. In this form, I have three fields dispenser, cargo box, and packs. Every time I change other fields and update the form. The values in those three fields get subtracted again. I want to make sure only if I make changes to those three fields then it should be subtracted. def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): packs = form.cleaned_data.get('packs') dispenser = form.cleaned_data.get('dispenser') cargo_box = form.cleaned_data.get('cargo_box') Material.objects.filter(material_name='Packs').update(quantity=F('quantity')-packs) Material.objects.filter(material_name='Dispenser').update(quantity=F('quantity')-dispenser) Material.objects.filter(material_name='Cargo Box').update(quantity=F('quantity')-cargo_box) order = form.save(commit=False) order.updated_by = request.user order.date_updated = timezone.now() if order.scheduled_date is not None and order.status == 'In Progress': order.status = 'Scheduled' order.save() form.save() return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) -
How to fetch data from an api in React Native from Django rest framework using axios
This is the context Provider That has my state that is fetched from the rest framework api. import axios from 'axios'; export const PostContext = createContext(); const PostContextProvider = (props) => { const [ posts, setPosts ] = useState([]); useEffect(() => { axios.get('http://127.0.0.1:8000/api/products/') .then(res => { setPosts(res.data) }) .catch(err => { console.log(err); }) }, []); return( <PostContext.Provider value={{ posts }}> {props.children} </PostContext.Provider> ) } export default PostContextProvider** When I try to console log it I get an this error in my emulator console.log Unrecognized event: {"type":"client_log","level":"log","data":["[]"]} Array [] When I check my browser, I got this error. DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/rest_framework/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE I tried to configure my backend using cors headers and the code looks like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'django_filters', # 'rest_framework_filters', 'shop.apps.ShopConfig', 'cart.apps.CartConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True # CORS_ORIGIN_WHITELIST = ( # 'http://localhost:19002/' # ) -
Issue with Pipfile.Lock while installing pillow with pipenv
Trying to use pillow for images in Django.Using Pipenv to generate the virtual environment.Pillow is getting installed but Pipfile is not able to lock properly.Below is the Pipfile. name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "==3.0.1" psycopg2-binary = "==2.8.4" django-crispy-forms = "==1.8.1" django-allauth = "==0.41.0" [requires] python_version = "3.7"