Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter objects by Many-To-Many field intersection
Hello, Can some good person give me advice on how to get a queryset of ordered objects by intersecting a many-to-many field with a given one object's many-to-many field? For example I have: class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True) ... class Tag(models.Model): name = models.CharField(max_length=64) ... I select one Video object and would like to have first ten objects that have most similar tags set to show like related videos. Thanks in advance! -
Is there a equivalent implemented example for google OAuth 2.0 for Web Server Applications on django rest framework as shown for flask?
Is there a equivalent implemented example for google OAuth 2.0 for Web Server Applications on django rest framework as shown for flask ? https://developers.google.com/identity/protocols/oauth2/web-server#example -
Razorpay issue payment is being processed
my view is Django views file my view my html template where use java script to send request to Razor pay my template page where java script is my java script inside template this is the page that am getting every single time try to pay it show your payment is being procced then nothing happens pls help main issue -
502 Bad Gateway Response on AWS
I have setup a django app and connected it to AWS via elasticbeanstalk. I followed a configuration tutorial, and I assume I am doing everything correctly. However, when trying to connect to the elasticbeanstalk app on AWS, I receive the error below: 502 Bad Gateway (nginx/1.20.0) I'm unsure why I am getting this error and am wondering if it potentially has something to do with the structure of my application. My django app is within a bigger folder (the main repository), and is also being stored alongside the front end of the app directory which are both in the same directory. Might this be the problem? Does Elastic Beanstalk not know which subfolder is the app? I declared eb init on the main folder and not the folder containing the Django app. -
Django save duplicate image to folder
Does anyone know why I get a second image in my User folder when I refresh the page? I can get rid of the problem with fs.delete(name), but I don't think this is an appropriate solution because the image is still going to be saved in the folder, is just going to be deleted right away by the delete function. If I remove the delete function, the image gets duplicated with a different name. @login_required(login_url='login_user') def profiles(request): user = request.user user_id = request.user.id user_profile_id = request.user.profile.id user_name = request.user.username form = ProfileForm(instance=user) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): avatar = form.cleaned_data.get('avatar') name_extension = avatar.name name, extension = name_extension.split(".") path_profile_pic = user_name + '/' + "ProfileImg" + '/' + user_name + '.' + extension file_name = user_name + '.' + extension fs = FileSystemStorage(location='profiles/media/') if fs.exists(file_name): pass #fs.delete(file_name) else: fs.save(path_profile_pic, avatar) title = form.cleaned_data.get('title') Profile.objects.filter(id=user_profile_id).update(avatar=path_profile_pic, title=title) data = Profile.objects.filter(id=user_id).values_list('avatar') else: messages.success(request, "Invalid File.") context = {'form': form} return render(request, "profiles/profiles.html", context) -
Django appending /None to url
i am creating a logic for users to save posts as favourite, i finished creating but when i header over to the url http://127.0.0.1:8000/design/ui-ux/learn-ui-the-easy-way/save/ it automatically refreshes it self and now appends None to the url like this http://127.0.0.1:8000/design/ui-ux/learn-ui-the-easy-way/save/None and that is not what i am expecting. views.py @login_required def designtut_favourite(request, designcat_slug, design_slug): user = request.user designtut = DesignTutorial.objects.get(slug=design_slug) profile = Profile.objects.get(user=user) if profile.favourite_design.filter(slug=design_slug).exists(): profile.favourite_design.remove(designtut) else: profile.favourite_design.add(designtut) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favourite_design = models.ManyToManyField(DesignTutorial) -
Django-allauth - calling callback directly (from third-party app) returns error
Some third-party applications like Hubspot or Pipedrive have their own marketplace. They list my app there and there is a button "install" which generates a code parameter and redirects to https://mywebsite.com/accounts/<provider>/login/callback/?code=<SOME_CODE_THAT_THEY_GENERATED> The problem is that allauth shows errors in such cases instead of signing up or logging in users automatically. Social Network Login Failure When I try to sign up the common way, eg. by going to: /accounts/<provider>/login/ - everything is working correctly and the user is signed up or logged in. Do you know if that should work and where is the problem? -
Does this use of the require_GET decorated add value?
I was reading this page on how to add a favicon to a Django website. In this article, the following code is presented to serve a favicon from the project root: @require_GET @cache_control(max_age=60 * 60 * 24, immutable=True, public=True) # one day def favicon(request: HttpRequest) -> HttpResponse: if settings.DEBUG: name = "favicon-debug.png" else: name = "favicon.png" file = (settings.BASE_DIR / "static" / name).open("rb") return FileResponse(file) I understand the @require_GET decorator will ensure this "page" (or this case just an image, really) can only be opened using a GET request. But I wonder, given that all we output here is just a static image, is there any value in doing so? Why would this decorator be there? -
I am working on django e-commerece project my teacher give me task
When user click on pay button then generate a bill receipt and send on user email ...Kindly Tell me gyzz how I perform this task -
Is there a way to get when an SSL certificate expires using Pyton?
I'm building a site that monitors the status of other websites using Django and want to keep track of when the SSL certificate of the other websites expire. Does anyone know any way to do this? -
HTMX, Django - update part of page
I've started with HTMX and I want to use it to refresh part o page after pressing button on pop-up page. The button is adding clicking user as participant in an event. I going true tutorials and example which mostly present cases with forms and I don't know how to approach this update with it. I'm pretty sure I should use hx-ws, but it is just completely unclear for me how. chall-interface.html (here is a part which I want to update) {% load static %} {% load tagz %} <div id='chall-interface' class="card-bottom mb-2"> <button onclick="call('challFollows',{'id':'{{chall.id}}'}, this)" class='icon icon-s rounded-sm float-end background-transparent mb-2 me-1 color-white'><i class="font-12 fa fa-heart {% followedChall user chall %}"></i></button> <button href="#" data-menu="comment-section" class="icon icon-s rounded-sm float-end background-transparent mx-1 mb-2"> <i class="font-12 fa fa-comments color-white"></i> </button> {% if chall.dealine_is_over %} <button href="#" data-menu="rules" class="icon icon-s rounded-sm float-end background-transparent mx-1 mb-2"> <i class="font-12 fa color-white {% changeJoinButton user chall %}""></i> </button> <!-- Here is a code I'm asking about --> {% if user == userParticipationStatus.user %} <a href="/addResponse/{{chall.id}}" class="icon icon-s rounded-sm float-end background-transparent mx-1 mb-2"> <i class="font-12 fa fa-plus-square color-white"></i> </a> {% else %} {% endif %} <!-- Here is a code I'm asking about --> {% if chall.user … -
What's the correct way to get a pdf attachment from a GET request in django
I have this simple view: class Reports(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): report_id = request.GET.get("report_id") response = get_report(report_id) return Response(response, status=status.HTTP_200_OK) The get_report method simply strips the payload and returns just an id that needs to be sent to GET the pdf. Error that is returned: ERROR 2022-04-20 19:02:58,537 log 148558 140052495332928 Internal Server Error: /api/v2/app/reports Traceback (most recent call last): File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/rest_framework/renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/rest_framework/utils/json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/local/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 50, in default return obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 in position 10: invalid start byte The server response headers: access-control-allow-origin: * access-control-expose-headers: content-disposition content-disposition: attachment; filename="assessment_hbx0MkrjYad2I2suaKcrIdzOcaMlIBSGDw4I8TBprWC28GbDFkF0KxuBpNMB1qYc.pdf" content-length: 48818 content-type: application/octet-stream date: Wed,20 Apr 2022 19:16:34 GMT server: istio-envoy … -
How to save form data to two separate database tables in Django
How would I save data from a form in Django to two separate database tables. The data would be saved to one table and also used to update the balance in another table. -
Django complete form as signed up user
After you sign up, you are prompted to a page that contains a form used for gathering additional information about the new user and after that it redirects you to the login page. The problem is that the form doesn't submit if i don't specify the {{form.user}} instance in the html file. Probably because the user_id is not recognized by default. When i specify it, the form let me chooses from already existing users, and i would like it to go with the logged in user by default. views.py class CreateInfoView(CreateView): model = AdditionalInfoModel form_class = AdditionallnfoModelForm template_name = "user_ski_experience/additional_info.html" def get_form_kwargs(self): variable_to_send = super(CreateInfoView, self).get_form_kwargs() variable_to_send.update({'pk': None}) variable_to_send.update({'pk_user': self.request.user.pk}) return variable_to_send def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('login') forms.py class AdditionallnfoModelForm(forms.ModelForm): class Meta: model = AdditionalInfoModel fields = '__all__' def __init__(self, pk, *args, **kwargs): pk_user = kwargs.pop('pk_user') super(AdditionallnfoModelForm, self).__init__(*args, **kwargs) self.pk = pk self.fields['user'].disabled = True self.fields['user'].initial = pk_user for el in self.fields: self.fields[el].label = False def clean(self): return self.cleaned_data How can i solve this ? -
Requests synchronization on multiple servers
We have an API for a game on Django Rest Framework. There are tournaments and tournament participants in the game. Tournament model has the max_players field and the API should not allow register more participants when max_players number is reached. This is simplified models: class Tournament(models.Model): max_players = models.PositiveIntegerField() class TourneyPlayer(models.Model): tourney = models.ForeignKey(Tourney, on_delete=models.CASCADE, related_name='players') user = models.ForeignKey(User, on_delete=models.CASCADE) There is serializer in the registration endpoint and within its validate method it checks the number of already registered players returns an error if the tourney is full: def validate(self, attrs): if tourney.players.count() >= tourney.max_players: raise serializers.ValidationError() return attrs And if validation passes we create a new TourneyPlayer object. But when we create a new tournament all users receive notification and many of them immediately click on the register button. It causes a lot of requests at the same time and sometimes player is being registered even when max_player count reached. It happens because there is some delay between validation and creation, so the classic concurrency issue arises: Request A validated Request B validated Request A created player Request B created player Locally I solved this issue by adding the threading.Lock object, but how to do it if we have … -
Autorun Server Django on Rasberry Pi 4
I have django server, which working corectly when I run rasberry then I open terminal in corrct folder then write : source env/bin/activate python manage.py runserver 'my_ip:port But I want to do this line automaticly when I turn on Rasberry So I have solution from youtube which work but not enough. I have directory /home/pi/.config/autostart in this directory i have file 'name_file.desktop' in 'name_file.desktop' : [Desktop Entry] Exec = bash /home/pi/Desktop/start.sh Also I have file on my desktop 'start.sh' in 'start.sh' : cd /path/to/file source env/bin/activate cd /path/to/file python manage.py runserver 'my_ip:port' And that work corectly. I turn on rasberry after about 20 seconds I see my desktop and I can connect to server Django with wi-fi with my mobile phone. But in this solution I must also connect monitor to Rasberry. When I have Rasberry without any output devices (like monitor). I only switch on rasberry and wait more time than 20 seconds and then i try and I can not connect to server Django with wi-fi with my mobile phone and I dont know why conecting monitor is nesscecery in this solution. Has anybody have answer or other solution to autorun server Django when I only turn on … -
Django Serializer Validator not working with allow_blank and read_only arguments
i have a serializer which has some_field = CharField(allow_null=False, allow_blank=False, read_only=True) The problem is that i do not get any errors if i try to serialize Serializer(data={'some_field': '').is_valid(raise_exception=True) or Null. What am i doing wrong? -
can i have two exact same models poiting to the same table on django?
trying to split a piece (called A) of a django monolith (called B) apart, i decided to add a new module to my monolith and move there all code related to A. In the future, this module would be extracted to a whole new system. both A and B uses class City(models.Model), so while i deal moving services and helpers, i wanted to have, inside A, a read-only city model to isolate A from anything related to B's city. while having B/some_path/city.py, i created a new model as A/another_path/city.py with this addition: class Meta: managed = False db_table = 'city' trying to check if everything was working, i noticed ./manage.py migrate would give me several errors like ?: (models.E030) index name 'city_column_name_index' is not unique among models: A.City, B.city. where city_column_name_index was declared inside a migration: migrations.AddIndex( model_name='city', index=models.Index(fields=['column_name'], name='city_column_name_index'), ), how should i have a copy of city model to use inside A without messing with B? -
Django GrahpQL ACL?
Is there a Django GraphQL ACL? Like you can't access the Query/Mutation if the user has no permission. For Example, the login user has a only permission on products Query/Mutation but no permission on human resources Query/Mutation. How can I return a error message like "Permission Denied!"? -
Create view to save data in django m2m parent and intermediate (through) table using a form and formset
I want to replicate the admin functionality shown in the screenshot below on the client side. This is app is meant to cost a recipe based on the ingredients and quantity. Find below some snippets of my code admin.py class RecipeIngredientInline(admin.TabularInline): model = RecipeIngredient extra=0 class RecipeAdmin(admin.ModelAdmin): inlines = [RecipeIngredientInline] admin.site.register(Recipe, RecipeAdmin) models.py class Ingredient(models.Model): ingredient_name = models.CharField(max_length=255) unit_of_measure = models.CharField(max_length=255) price = models.DecimalField(max_digits=20, decimal_places=2) units_size_in_package = models.DecimalField(max_digits=20, decimal_places=2) cost_per_unit = models.DecimalField(max_digits=20, decimal_places=2) supplier = models.CharField(max_length=255, null=True, blank=True) create_date = models.DateTimeField(auto_now_add=True, blank=True) edit_date = models.DateTimeField(auto_now=True, blank=True) class Recipe(models.Model): recipe_name = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True) product_category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, blank=True, null=True) ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient') is_vatable = models.BooleanField(default=False) VAT_percentage = models.PositiveIntegerField(blank=True, null=True) VAT = models.FloatField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True, blank=True) edit_date = models.DateTimeField(auto_now=True, blank=True) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, blank=True, null=True, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, blank=True, null=True, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=20, decimal_places=2) cost = models.FloatField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True, blank=True) edit_date = models.DateTimeField(auto_now=True, blank=True) forms.py class RecipeForm(forms.ModelForm): product_category = forms.ModelChoiceField(queryset=ProductCategory.objects.all()) class Meta: model = Recipe fields = ['recipe_name', 'description', 'photo', 'product_category', 'ingredients', 'is_vatable', 'VAT_percentage' ] widgets = { 'description': forms.Textarea( attrs={ 'rows': 4, } ), 'VAT_percentage': forms.NumberInput( attrs={ 'class': 'form-control', } ), } ) class … -
Internal server error 500 while sending data from react to Django rest framework
I am making a crop prediction system where user will send some data to backend and crop_prediction function will predict a crop and send it to frontend to display it. I checked my views.py function it is working properly on Django rest framework. But when sending data it is giving internal server error. Please suggest any modification in my code. My frontend code to send data async function userDataHandler(userData) { const response = await fetch("http://localhost:8000/Efarma/", { method: "POST", body: JSON.stringify(userData), headers: { "Content-Type": "application/json", }, }); const data = await response.json(); } Django views code:- from django.shortcuts import render from firebase import firebase import numpy as np # from rest_framework.parsers import JSONParses from django.views.decorators.csrf import csrf_exempt import pickle from efarma import config from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer from rest_framework import permissions from rest_framework.decorators import api_view, permission_classes def weather_fetch(city_name): """ Fetch and returns the temperature and humidity of a city :params: city_name :return: temperature, humidity """ api_key = config.weather_api_key base_url = "http://api.openweathermap.org/data/2.5/weather?" complete_url = base_url + "appid=" + api_key + "&q=" + city_name response = requests.get(complete_url) x = response.json() if x["cod"] != "404": y = x["main"] temperature = … -
Pytest coverage with django generates wrong result when run in parallel
When I run my testsuite with parallel executions I receive different results compared to run only one test runner. I tried two approaches and both did not provide proper results. These commands did either only produce one partial result or less than we had runners. I've tried with coverage and pytest combined: COVERAGE_PROCESS_START=./my_app coverage --parallel-mode --concurrency=multiprocessing run -m pytest -m "not e2e" -n 4 Also with pytest and pytest-cov: pytest -m "not e2e" -n 4 --cov=my_app The second one also had the issue that some templatetags were not seen as registered even though others in the same directory were registered. After running these I executed coverage combine and coverage report. When run in parallel the results are always incomplete compared to running it with only one test runner, which works perfectly fine: coverage run -m pytest -m "not e2e" This is my coveragerc: [run] include = my_app/* omit = *migrations*, *tests* plugins = django_coverage_plugin [report] show_missing = true Does some know how to get proper coverage results when running pytest in parallel? -
how to add an image through {{i.image}} to template in django?
In this template i want to put something like {{i.image}} instead of "{% static '3307209.jpg'%}" {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> </head> <body> {% for i in pr%} <div class='card'> <div class="number">{{i.number}}</div> <img src="{% static '3307209.jpg'%}"> <span class="prname">{{i.name}}</span> <p id="id">{{i.description}}</p> <button><span class="price"> ${{i.price}}</span> <img id='add'src="{% static 'add.png'%}"> Add to cart</button> </div> {%endfor%} </body> </html> So i have an image field in my models and my views are ready. to change an image inside my template from admin page i tried this but did not work: <img src={{i.image}}> How can i add an image to template from database? -
Custom function in Django's model
I have model and i want to add my custom function, and when i create object this function call automatically. this is my model and test function. it's only for testing i want when i create Like object after call test function class LikeManager(models.Manager): def create(self, *args, **kwargs): decrease = kwargs.pop("decrease") new_like = self.model(**kwargs) new_like.save(decrease=decrease) return new_like class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user")) question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question")) objects = LikeManager() #this function @property def test(self): print("Testing") return 1 def save(self, decrease, *args, **kwargs): if not self.pk: if decrease: self.question.save() else: self.question.point += 1 self.question.save() return super(Like, self).save(*args, **kwargs) -
How to save multiple objects at once to Django database
I'm trying to get form data using a POST request and save the form data to my database which was created using a django model named InfoModel. I'm getting the data from the POST request, but I don't know how to save all of it at once so that it all saves to the same row in the db. The way I'm doing it now, each object from the form saves to a different row of the database which is obviously not useful at all. I expect the answer is simple, but I haven't seen this in the docs. views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import InfoForm from .models import InfoModel # Create your views here. def home(request): if request.method == 'POST': #if POST request, validate the data form = InfoForm(request.POST) if form.is_valid(): #if the form is valid, collect the data, submit to db, and thank the user valid = True form_data = request.POST f = InfoModel(fname = form_data['fname']) f.save() l = InfoModel(lname = form_data['lname']) l.save() e = InfoModel(email = form_data['email']) e.save() p = InfoModel(phone = form_data['phone']) p.save() return render(request, 'form_db/home.html', {'form':form, 'valid':valid}) else: #if the form is invalid, populate the form with the entered …