Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am working on project using Django and React using Rest Framework. I have set CORS_ALLOW_ALL_ORIGINS=True in settings.py still i am getting error Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/encrypt/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using axios to post and get request. Suprisingly even after error post request is made but get request fails. This is react file using axios sendImage =()=> { this.activateSpinner() let formData = new FormData() formData.append('to_be_hidden', this.state.files[0], this.state.files[0].name) formData.append('used_to_hide', this.state.files[1], this.state.files[1].name) axios.post('http://127.0.0.1:8000/api/encrypt/', formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' } }) .then(resp=>{ this.getImageClass(resp) console.log(resp.data.id) }) .catch(err=>{ console.log("Code broke at send image") console.log(err) }) } getImageClass =(obj)=> { axios.get(`http://127.0.0.1:8000/api/encrypt/${obj.data.id}/`, { headers: { 'accept': 'application/json', } }) .then(resp=>{ this.setState({recentImage:resp}) console.log(resp) }) .catch(err=>{ console.log("Code broke at get image") console.log(err) }) this.deactivateSpinner() } -
Decoding problem with files and serializers
In my API using Django Rest Framework I have a function based view for part of a sign up process for using Stripe. The view succefully sends everything to stripe and updates my sites database with the proper information, but when trying to return the serializer data I get this error: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Assuming it has to do with the files needed for personal identification Here is the view: @api_view(['POST']) def StripePersonalOnboard(request): serializer = StripePersonalSerializer(data=request.data) profile = get_object_or_404(Profile, user=request.user) if serializer.is_valid(): phone_number = serializer.validated_data.get('phone_number') ss_number = serializer.validated_data.get('ss_number') id_front = serializer.validated_data.get('id_front') id_back = serializer.validated_data.get('id_back') try: stripe.api_key = settings.STRIPE_TEST_SEC_KEY id_front_file = stripe.File.create( purpose='identity_document', file=id_front ) id_back_file = stripe.File.create( purpose='identity_document', file=id_back ) stripe.Account.modify( profile.stripe_acc_id, individual= { 'phone': phone_number, 'id_number': ss_number, 'verification': { 'document': { 'back': id_back_file, 'front': id_front_file } } } ) profile.stripe_id_front_tkn = id_front_file.id profile.stripe_id_back_tkn = id_back_file.id profile.save(update_fields=['stripe_id_front_tkn', 'stripe_id_back_tkn']) return Response(serializer.validated_data) except stripe.error.InvalidRequestError as e: #invalid parameters were provided return Response(e.error.message) else: return Response(serializer.errors) -
'NoneType' object is not subscriptable I've have been studying this one all morning
Trying to get a list of products from my database def bad_view(request, *args, **kwargs): print(dict(request.GET)) my_request_data = dict(request.GET) new_products = my_request_data.get("new_products") print(my_request_data, new_products) if new_products[0].lower() == "true": print("new product") Products.objects.create(title=my_request_data.get('title')[0], content=my_request_data.get('content')[0]) return HttpResponse("Dont do this") I keep getting : if new_products[0].lower() == "true": TypeError: 'NoneType' object is not subscriptable [08/Nov/2020 17:25:38] "GET /bad-view-dont-use/ HTTP/1.1" 500 67144 -
select data returned from a for loop in django template
I was able to get data from our flights API which get flights data from Amadeus . i was able to display this data on django template using a for loop: <form action="#" method="post" > {% if ctx.flight_details_error %} {{ctx.flight_details_error}} {% else %} {% for obj in ctx.flight_details %} <div class="w-layout-grid add-flight-result" style="width: 70em;margin-left: 10px;"> <!-- --> <div class="airline-logo-wrapper"> <!-- <p>{% if obj.atob_flight.indirect_flights %} {{obj.atob_flight.indirect_flights.0.airline_code}} {{obj.atob_flight.indirect_flights.0.flight_number}} {% else %}{{obj.atob_flight.airline_code}} {{obj.atob_flight.flight_number}}{% endif %}</p> --> {% if obj.atob_flight.indirect_flights %}<img src="/static/images/airline/{{obj.atob_flight.indirect_flights.0.marketing_code}}.png" alt="" class="airline-logo">{% else %}<img src="/static/images/airline/{{obj.atob_flight.marketing_code}}.png" alt="" class="airline-logo">{% endif %} </div> <div class="depart-date-time-wrapper"> <div class="depart-time">{% if obj.atob_flight.indirect_flights %} {{obj.atob_flight.indirect_flights.0.time_of_departure}}{{forloop.counter}}{% else %}{{obj.atob_flight.time_of_departure}} {% endif %}</div> <div class="depart-date">{% if obj.atob_flight.indirect_flights %}{{obj.atob_flight.indirect_flights.0.date_of_departure}}{% else %}{{obj.atob_flight.date_of_departure}}{% endif %}</div> <div class="airport">{% if obj.atob_flight.indirect_flights %}{{obj.atob_flight.indirect_flights.0.source_airport.city}} ({{obj.atob_flight.indirect_flights.0.source_airport.airportName}}){% else %}{{obj.atob_flight.source_airport.city}} ({{obj.atob_flight.source_airport.airportName}}) {% endif %}</div> </div> <div class="stops-fliter-wrapper"> <div class="flight-duration">{{obj.atob_flight.elapsed_flying_time}}</div> <img src="/static/images/direct-arrow.png" alt=""> {% if obj.atob_flight.indirect_flights %} <div class="stop-fliter-flight">({{ obj.atob_flight.indirect_flights|length }}-Stop)</div> {% else %} <div class="stop-fliter-flight">(Non-Stop)</div> {% endif %} </div> <div id="w-node-5fcf7c85721e-18943613" class="arrival-date-time-wrapper"> <div class="arrival-time">{% if obj.atob_flight.indirect_flights %}{% if obj.atob_flight.indirect_flights|length == 4 %}{{obj.atob_flight.indirect_flights.3.time_of_arrival}}{% elif obj.atob_flight.indirect_flights|length == 3 %}{{obj.atob_flight.indirect_flights.2.time_of_arrival}}{% else %}{{obj.atob_flight.indirect_flights.1.time_of_arrival}}{% endif %}{% else %}{{obj.atob_flight.time_of_arrival}}{% endif %}</div> <div class="arrival-date">{% if obj.atob_flight.indirect_flights %}{% if obj.atob_flight.indirect_flights|length == 4 %}{{obj.atob_flight.indirect_flights.3.date_of_arrival}}{% elif obj.atob_flight.indirect_flights|length == 3 %}{{obj.atob_flight.indirect_flights.2.date_of_arrival}}{% else %}{{obj.atob_flight.indirect_flights.1.date_of_arrival}}{% endif %}{% else %}{{obj.atob_flight.date_of_arrival}}{% endif %}</div> <div class="airport">{% if obj.atob_flight.indirect_flights … -
django get previous url
i am using request.META.get('HTTP_REFERER') to get the previous url , it works fine when the url is inside my website but when the url is outside my website (facebook) it returns none and the template tag for HTTP_REFERER return the current url with a facebook parameter : http://127.0.0.1:8000/order_analytics/?fbclid=IwAR2nLUSZAAmJOdjS7UPw_jol14ZpOEW7QjxrUqrisFk1msWa_L9nZPWqyDg what i want to get is https://www.facebook.com/ -
Django show multiple pictures of an item in HTML
I can add pictures to my admin page but I want to figure out how to display them all on my main html page. Below code shows only the first image that I uploaded to the admin page and ignores the rest. models.py class Product(models.Model): PN = models.CharField(max_length=100, image = models.FileField(blank=True) def __str__(self): return self.name class PostImage(models.Model): post = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'products/') def __str__(self): return self.post.name views.py from .models import Product, PostImage def product_detail(request, PN): product = get_object_or_404(Product, PN=PN, available=True) photos = PostImage.objects.filter(product=product) return render(request, 'product/product_detail.html', {'product':product, 'photos':photos}) product_detail.html {% block content %} {% for obj in object %} <div id="item"> {% for image in obj.postimage_set.all %} <img src="{{ MEDIA_URL }} {{ obj.image.url }}" /> {% endfor %} </div> {% endfor %} {% endblock %} -
Make AM/PM Lowercase System-wide in Django Settings
I've seen this post, but it's not quite what I'm after. What I'm looking to do instead is change the way AM and PM are displayed system-wide, by configuring this in Django settings. Something like this (which doesn't work): USE_L10N = False DATETIME_FORMAT = 'Y-m-d, f {0}'.format('A'.lower()) I'd like the Django admin timestamps to look like this, for example: 2020-10-20, 9:15 pm I see that by default these are formatted how I want if the locale was de_DE. Can I set this for only the date time, without affecting other language settings? I also noticed that if it weren't for adhering to AP style, using 'a' would get me what I want. I also tried an answer give here (@mrts), but this yields the same as what I already have. This is somewhat academic, as I would be satisfied with 2020-10-20, 9:15 PM (achieved by setting USE_L10N=False and DATETIME_FORMAT = 'Y-m-d, f A'), but I'm still curious what is the best way to do this. -
How to create a relation from one table entry to other table entries?
I am creating a small Django app which has a model of exercise like in sports/fitness. class Exercise(models.Model): name = models.CharField(max_length=200, null=True) description = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) muscles = models.ManyToManyField(Muscle, blank=True) equipment = models.ManyToManyField(Equipment, blank=True) There are different entries in the exercise table. Something like a Push-Up, Knee-Push Up, Wall Push-Up, Diamant Pust-Up and others. I want to somehow have a relation between some exercises. For example, when you can not perform a single Push Up what exercise could be an easier progression (Knee Push-Up). If you can not do Knee Push-Ups, then check out the next easier one. But also the reverse is possible. Your think regular Push-Ups are easy, checkout the harder ones. Would using a column like "easier_progression" and saving the easier exercise or exercises with the foreign key a good choice? What about the reverse case: A progression which is harder. Should I implement this as well or just use "is easier" and abstract that in code when adding a harder progression since it is just the reverse case but from the other entry? -
Django Filter using multiple Foreign Keys
I am trying to make a django filter to filter values based on multiple models connected using foreign keys. My models looks like: model test1(models.Model): name=models.CharField() ..........some more fields models test2(models.Model): name = models.CharField() code = models.CharField() models test3(models.Model): name = models.CharField() code = models.CharField() model test4(models.Model): first = models.ForeignKey(test1, on_delete=models.CASCADE) second = models.ForeignKey(test2, on_delete=models.CASCADE, blank=True, null=True) third = models.ForeignKey(test3, on_delete=models.CASCADE, blank=True, null=True) I want to make a filter from test1 to filter test2 and test3 values. Also, one and only one of the second or third field in model test4 will be null each time. Currently I was trying to use django_filters but not able to lookup these fields. How can I approach -
Django Models - Filter third model, based on two connected models?
How Can StoreDefaultAudience be improved? John's Store - Audiences: Audience A, Audience B, Audience C Nicole's Store - Audiences: Audience D, Audience E for StoreDefaultAudience John's Store should only be able to choose Audience A, Audience B, Audience C as a default audience for StoreDefaultAudience Nicole's Store should only be able to choose Audience D, Audience E as a default audience class Store(models.Model): store_name = models.CharField(max_length=50) class Audience(models.Model): audience_name = models.CharField(max_length=50) store = models.ForeignKey(Store, on_delete=models.CASCADE) # only one StoreDefaultAudience should be allowed per Store # the default audiences should only be that stores audiences class StoreDefaultAudience(models.Model) default_audience = models.ForeignKey(Audience, on_delete=models.CASCADE, unique=True) store = models.ForeignKey(Store, on_delete=models.CASCADE, unique=True) -
Can i merge photos in python with pillow?
I want to create a website like redbubble Can i use python to programming it? I want to use pilow, django. Is it possible with this tools? I searched for it and didnt find any answer. I tried a little but I am not sure that it can be possible or not Best regards -
Django blog - printing only last few posts and load more on clicking a button
I have a really simple Django blog application. https://example.com/ returns a template (index.html) which looks something like this: {% extends "base.html" %} {% block content %} <style> ... </style> ... <div class="container"> {% for post in post_list %} <div class="..."> <h2>{{ post.title }}</h2> <p>{{ post.content | slice:"300" }}</p> </div> {% endfor %} </div> ... <button onlick="morePosts()"></button> ... {% endblock %} and https://example.com/post_slug returns the full post What I need to do now, is to limit the for loop to print only first 5 posts in the post_list and to print more when function morePosts() is called. In my views.py there's a simple class PostList class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' -
Define an abstract model with generic signals in a Django project
I am creating an abstract model that allows me to inherit signals that execute basic methods. Abstract model class SignalModel(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) models.signals.post_save.connect(self.post_save_signal, sender=self.__class__, dispatch_uid='post_save_{}_signal'.format(self.__class__.__name__.lower())) # @classmethod # def __init_subclass__(cls, **kwargs): # super().__init_subclass__(**kwargs) # models.signals.post_save.connect(self.post_save_signal, # weak=False, # sender=cls, # dispatch_uid='post_save_{}_signal'.format(cls.__name__.lower())) class Meta: abstract = True def post_save_signal(self, sender, update_fields, created, instance, **kwargs): print('_post_save_signal') if <condition1>: self.condition1() ... def condition1(self): ... User model class User(SignalModel): email = .... ... When I do user = User.objects.first() user.save() I hope to see the result # _post_save_field_signal but nothing happends. I have tried to override __init__ or __init_subclass__. but nothing works. I think that the signal does not connect with the model. I do not know to do it. Thanks! :D -
Hi, I have builted a blog with django. How can I obtain all posts published in the last hour with a queryset?
That's my idea but obviously doesn't work.... Thanks def PostUltimaOra(request): PostsLastHour = Post.objects.filter(pub_date__time__range=(datetime.time.now, datetime.time(now- 1h))) return render(request, 'blog/numeroposts.html', {'PostsLastHour': PostsLastHour}) -
Create a field with conditions
I'm a beginner in django rest framework. I am wondring if there is a way to create a field from a GET. For example if "count" == 0, create a field named "available" : "out_of_stock" else "available [ { "id": 1, "count": 10, }, { "id": 2, "count": 0, } ] -
Can I use django templating language with inside .vue file?
I would like to use Vue CLI for my existing Django project. The setup works, as in I can, in the future - if I want to, separate backend (API Django) and frontend (Vue CLI). One problem is, since it's an existing project, many templates/htmls are using Django templating language, such as: {% load static %} {% load fruit_tags %} {% load i18n %} {% load l10n %} .... {% if not request.user.is_authenticated %} {% endif %} .... etc ... My questions: Is there a way to use Django templating language inside .vue files? What would be the best practice for this scenario? I am currently using npm installation approach and it's working (using html with Django template; not .vue). Shall I just keep on doing it like this, and use the CLI (new frontend folder) for upcoming features? Thank you in advance! -
how to calculate number of clicks on embeded video
I am embedding some videos on my Django site and I want to calculate how many users viewed that video. I think of one solution which is "how many times the user clicks on (generated automatically) viewers will be updated" with the help of jQuery, but it doesn't work as expected. This is my template: {% load static %} {% load embed_video_tags %} <!DOCTYPE html> <html lang="en"> <head> </head> <body> <h4>User: {{user}}</h4> <div class="row"> <div class="container"> {% for v in videos %} <div class="col s12 l6"> {% video v.video 'tiny' %} <div class="info"> <h5 id="view"><span><i class="material-icons">visibility</i></span> 0</h5> </div> </div> {% endfor %} </div> </div> </body> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="{% static 'js/main.js' %}"></script> </html> Views.py: ... @login_required(login_url='login') def index(request): videos = item.objects.all() user = request.user.username return render(request, 'video/index.html', context={'videos': videos, 'user': user}) If you have any better solution please suggest to me that also. -
setting cookie in the middleware
please I need to set cookies country for the user, if it is his first time visit the site, check the following code, I depend on the code on call function class CountrySelectionMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # to check if the browser supports cookies or not # if request.session.test_cookie_worked(): # request.session.delete_test_cookie() country = request.COOKIES.get('country', None) expiry_date = request.session.get_expiry_date() if request.user.is_authenticated and request.user.username: account = Account.objects.filter(username=request.user.username) if account.exists() and country and account.country != country: account.first().update(country=country) elif not request.user.is_authenticated: if country is None or expiry_date < timezone.now(): if request.path != reverse('membership:choose_country'): return HttpResponseRedirect(reverse('membership:choose_country')) # response.set_cookie('country', country, max_age=settings.SESSION_COOKIE_AGE) response = self.get_response(request) country = request.POST.get('country', None) #if country: #response.set_cookie('country', country, max_age=settings.SESSION_COOKIE_AGE) return response the request.POST always return None -
Does elastic beanstack support latest python version?
In EB document it says Django 2.2 is incompatible with the Elastic Beanstalk Python 3.6 platform. The latest compatible version is Django 2.1.https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html But another document says EB support latest python versions, don't they contradict each other ? I wish to try Django 2.2 stable version hosting. https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python -
django rest framework many to many field not working
I need your help regarding something weird. I have the following models: class Profile(models.Model): first_name = models.CharField(max_length=20, default="") last_name = models.CharField(max_length=20, default="") email = models.EmailField(max_length=50, unique=True, default="") image = models.ImageField(null=True, blank=True, upload_to=profile_image_upload_path) class Skill(models.Model): profiles = models.ManyToManyField(Profile, blank=True) name = models.CharField(max_length=30) image = models.ImageField(upload_to=skill_image_upload_path) is_tech_skill = models.BooleanField(default=True) and the following serializer: class SkillSerializer(serializers.ModelSerializer): profiles = serializers.PrimaryKeyRelatedField(queryset=Profile.objects.all(), many=True) class Meta: model=Skill fields=['name', 'image', 'is_tech_skill', 'expertise'] class ProfileSerializer(serializers.ModelSerializer): skill_list = SkillSerializer(read_only=True, many=True,) class Meta: model = Profile fields = ('first_name', 'last_name', 'email', 'image', 'skill_list') depth = 2 when I do GET request for the profile I do not see any skills: enter image description here I added two skills to this profile from django admin panel. Thanks a lot in advance! -
Unable to create related model within forloop
I'm attempting to create a related model within a forloop, but I'm getting the following error: Cannot assign "False": "GoogleProfile.userprofile" must be a "UserProfile" instance. Any thoughts as to how to get this working? my code is below for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = UserProfile.objects.update_or_create( busname=column[0], ) google_profile = GoogleProfile.objects.create( userprofile=created, longitude=column[1], latitude=column[2], ) Thanks for your help! -
How To Pass a Dictionary Of Labels and Values into jQuery Autocomplete
I am trying to pass in a dictionary of Labels and Values into my template so that I can use the autocomplete on one of my fields with jQuery. The problem is that my dictionary is not being passed in correctly. I have a Django model Question that has a question and a slug. I want to pass both of these into my template so that when someone clicks on the question text, I can redirect them to the url/slug of that question. Question.html <input id="search-bar" name="question" type="text" class="form-control" placeholder="Find your next question..." aria-label="Find your next question..."> <div class="input-group-append"> <button id="search-question-button" class="btn" type="submit">Search</button> </div> <script> $(function () { $("[name='question']").autocomplete({ source: "{% url 'questions' slug=question.slug %}", select: function (event, ui) { window.location.href = ui.item.value; console.log(ui.item); } }); }); </script> Views.py if 'term' in request.GET: qs = current_questions.filter(question__istartswith=request.GET.get('term')) qs_dict = dict() for question in qs: qs_dict['label'] = question.question qs_dict['value'] = question.slug print(qs_dict) return JsonResponse(qs_dict, safe=False) In my django project console I am printing this dictionary and it seems to be printing correctly {'label': "Blah blah blah", 'value': 'blah-blah-blah'} However, when I inspect my site using chrome I see that the label and value are the same and my dictionary did not get … -
django-rest-framework datatables columns break table
Part 1 I had my datatable working with obj iteration but I am moving to DRF-datatables.. and although I got the example site running no problem the actual implementation on my end is kicking my butt. Basically, I got my whole weekend to show a table that seems to be loading data (as pagination is showing the proper info) but my rows are all blank: https://i.imgur.com/ImA23Zo.png Then I tried to add the "columns" section in the scripts and that breaks the whole table: https://i.imgur.com/ykwf58P.png Where am I going wrong? I'm also not getting any error messages so it's hard to debug datatables. Maybe Part 2.. Do I even need to go for DRF-datatables? My end goal is to be able to select multiple rows and then edit the trade for all those entries. Example of the end goal Select 3 trade Click dropdown somewhere at the top of the table Select Trade PK from that dropdown Click Save Table shows the latest data entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2> <a role="button" class="btn btn-success" … -
two variables in front of update_or_create
I've come across the following line of code _, created = UserProfile.objects.update_or_create( What is the point of the "_"? Thanks! -
Django | getting circluar import error on ModelForm
I am using Form and FormModel in Django for one of my application. I created one Model as below models.py from django.db import models class ImageProcessor(models.Model): id_image = models.ImageField(upload_to="image_dir") I am using the form as below (forms.py) from django import forms from .models import ImageProcessor class ImageProcessorForm(forms.ModelForm): class Meta: model = ImageProcessor In terminal window I am getting below message, and I am pretty sure that it is because of from .models import ImageProcessor this import. ERROR message: django.core.exceptions.ImproperlyConfigured: The included URLconf 'img_site.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular i mport.