Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assign each value using different loops in python
Hi I got a loop where I get different parameters (age, date, role, etc.), and I got an array where I get these values. How can I assign each value to eache parameter. I'll add some code below I tried this but obviosly didn't work parameters = Parametros.objects.filter(job_id=job.id) if request.method == 'POST': for parameter in parameters: #Update parameters params = request.POST.getlist('parameter') for i in range(len(params)): cursor.execute("UPDATE Jobs_parametros SET parameter_value='" + params[i] + "' WHERE parameter_name='" + parameter.parameter_name + "' AND job_id=" + str(job.id)) Here we can see parameters where I'm assigning parameter.parameter.name for the differente names. After that we can see the array where I get the values called "params". I want to assign each value I get form params to the name of the parameter to execute the code showed in the last line The result that I got with the code showed is each parameter name with the last value I added. The values are updated but only take the last value in my form and didn't assigned my values like the date and age for eache parameter name -
django foreign key filtering in admin panel
class City(models.Model): name = models.CharField(max_length=200, null=True, blank=False) class District(models.Model): city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=False) class ShippingAddress(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, null=False) district = models.ForeignKey(District, on_delete=models.CASCADE, null=False) I would like to filter the admin panel by city (selected city). in order to filter too much similar districts names. If someone has another way to do it no problem, that was a junior try, waiting for your advice. -
How can I run Django on a subpath on Google Cloud Run with load balancer?
I'll preface by noting that I have a system set up using Google Cloud Run + Load Balancer + IAP to run a number of apps on https://example.com/app1, https://example.com/app2, etc, and up to now I've only deployed Streamlit apps this way. The load balancer is directing traffic to each app in Cloud Run according to subpath (/app1, ...), and I used the --server.baseUrlPath=app2 option of streamlit run with no problems. Now I'm trying to get a 'hello, world' Django 4.1.5 app running on https://example.com/directory, and I can't seem to get the routes right trying differing suggestions here, here, and here. The Dockerfile ends with CMD exec poetry run gunicorn --bind 0.0.0.0:${PORT} --workers 1 --threads 8 --timeout 0 example_dir.wsgi:application First, the canonical solution. I added FORCE_SCRIPT_NAME = "/directory" in settings.py. Here's example_dir/urls.py: urlpatterns = urlpatterns = [ path("admin/", admin.site.urls), path("", include("directory.urls")), ] and here's directory/urls.py: urlpatterns = [ path("", views.hello, name="hello"), ] Visiting https://example.com/directory returns Page not found (404) Request Method: GET Request URL: http://example.com/directory/directory Using the URLconf defined in example_dir.urls, Django tried these URL patterns, in this order: 1. admin/ 2. [name='hello'] That Request URL is surprising and weird. Adding either USE_X_FORWARDED_HOST = True or SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') or … -
Overlapping two ImageField in a Django form
I’m trying to edit a user’s profile in django but when editing the banner image and the profile pictura overlap. I mean, I put a different image on each one, but when I save the form, I get the same image. When a profile is created both are set by default as it comes in models.py. views.py @login_required def EditProfile(request): user = request.user.id profile = Profile.objects.get(user__id=user) user_basic_info = User.objects.get(id=user) if request.method == 'POST': form = EditProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): user_basic_info.first_name = form.cleaned_data.get('first_name') user_basic_info.last_name = form.cleaned_data.get('last_name') profile.picture = form.cleaned_data.get('picture') profile.banner = form.cleaned_data.get('banner') profile.location = form.cleaned_data.get('location') profile.url = form.cleaned_data.get('url') profile.birthday = form.cleaned_data.get('birthday') profile.bio = form.cleaned_data.get('bio') profile.save() user_basic_info.save() return redirect('users:profile', username=request.user.username) else: form = EditProfileForm(instance=profile) context = { 'form':form, } return render(request, 'users/edit.html', context) forms.py class EditProfileForm(forms.ModelForm): first_name=forms.CharField( widget=forms.TextInput(attrs={ 'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md', }) ) last_name=forms.CharField( widget=forms.TextInput(attrs={ 'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md', }) ) picture = forms.ImageField(label='Profile Picture', required=False, widget=forms.FileInput) banner = forms.ImageField(label='Banner Picture', required=False, widget=forms.FileInput) location = forms.CharField(widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=25, required=False) url = forms.URLField(label='Website URL', widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs … -
why section of my django project views getting queryset error?
Hello I have a django project for calorie tracker and when I go to fooditem_create url I get this error : FoodItemCreateView is missing a QuerySet. Define FoodItemCreateView.model, FoodItemCreateView.queryset, or override FoodItemCreateView.get_queryset(). this is my views: from .forms import * from django.urls import reverse_lazy from .models import * from accounts.models import CustomUser from django.views import generic from django.views.generic import ListView from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin class FoodItemCreateView(LoginRequiredMixin, generic.CreateView): mode = Fooditem template_name = 'fooditem_create.html' fields = "__all__" success_url = reverse_lazy('fooditem_list.html') class FoodItemListView(LoginRequiredMixin,ListView): model = Fooditem template_name = 'fooditem_list.html' fields = "__all__" class FoodItemDeleteView(LoginRequiredMixin,generic.DeleteView): model = Fooditem template_name = 'fooditem_delete.html' success_url = reverse_lazy('fooditem_list.html') @login_required(login_url='login') def SelectFoodCreateView(request): usernow = CustomUser.objects.get(id=request.user.id) form = selectfoodForm(request.user, instance=usernow) if request.method == "POST": form = selectfoodForm(request.user, request.POST, instance=usernow) if form.is_valid(): name = form.cleaned_data.get('name') category = form.cleaned_data.get('category') quantity = form.cleaned_data.get('quantity') person = form.cleaned_data.get('person') selectedfood = Selectfooditem.objects.create( name=name, quantity=quantity, category=category, person=person) selectedfood.save() return redirect('/manage/profile') else: form = selectfoodForm(request.user) context = {'form': form} return render(request, 'addfood_create.html', context) @login_required(login_url='login') def ProfileView(request): usernow = CustomUser.objects.get(id=request.user.id) calorielimit = usernow.calorielimit selectedfood = Selectfooditem.objects.filter(person=request.user) calorieconsumed = 0 calorieleft = calorielimit for food in selectedfood : calorieconsumed+= (food.name.calorie * food.quantity) calorieleft = calorielimit - calorieconsumed context = { … -
404 error when requesting a file that exists
I'm trying to deploy a Django project using a VPS - it uses Apache and mod_wsgi. (It works fine locally). My homepage is displayed, but no static file is found, leading to a goofy display. I have configured my static files this way : settings.py : STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' call in template : ` ` After that I ran collectstatic, which created a "static" folder on root, as expected. I have checked via SSH and FTP, it is there (see screenshot 1 : ), with the correct permissions. The URL to access it should then be : /static. But I get this 404 error, even though my explorer seems to look for the correct adress (see screenshot 2 : ) I have only basic academic knowledge on this topic, but I simply don't understand how can I get a 404 when requesting a file that seems to exist. I will take any suggestion, since I've tried everything I could think of. Thank you very much ! Also, I added this in urls.py : urlpatterns = [ path('', home, name='home'), path('output/<str:region>/<str:summoner_name>', output, name='output') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I didn't think this was necessary, but tried anyway. It … -
how to make django admin theme dark?
can I somehow set a dark theme in django admin and make it look like in the screenshot below -
Assign each value in a loop in python
Hi I got a loop where I get differente parameters (age, date, role, etc.), and I got an array where I get these values. How can I assign each value to eache parameter. I'll add some code below I tried this but obviosly didn't work parameters = Parametros.objects.filter(job_id=job.id) if request.method == 'POST': for parameter in parameters: #Update parameters params = request.POST.getlist('parameter') for i in range(len(params)): cursor.execute("UPDATE Jobs_parametros SET parameter_value='" + params[i] + "' WHERE parameter_name='" + parameter.parameter_name + "' AND job_id=" + str(job.id)) -
Gunicorn Config File I've Created Doesn't Exist
I am using Django and Gunicorn to create a blog and am wanting to run my config file that I have created. This is the path to my config file (the conf folder is at the same level as manage.py): /var/www/website.co.uk/blog/DjangoBlog/Articles/conf/gunicorn_config.py I am in this path: /var/www/website.co.uk/blog/DjangoBlog/Articles and run this command: gunicorn -c gunicorn_config.py Articles.wsgi However, it returns the error: Error: 'gunicorn_config.py' doesn't exist Is Gunicorn looking in the wrong place for my config file? Any help would be massively appreciated. I have not been able to solve this for a while. Kind regards -
Vue.js are not displaying images from Django media folder
So, i have up and running Django server on localhost. There's is a Vue page, whick is authorized and able to fetch models data. If i inspect page, i see that img element have correctly resolved URL, and image exsists and can be loaded. But I got this: As you can see, other model parameters (such as name and price) can be loaded. Here's how I loading img. <figure class="image mb-4"> <img v-bind:src="product.get_thumbnail" /> </figure> I've checked media folder paths, and believe they are correct MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' Also, if I am able to load image by the link gotten via page inspection, why can't it be loaded on page itself? -
How to run long running task behind the scence in django class based view?
I want to run long running task in Django class based Redirectview. Before this running task to complete I want to return template. Here is my code. I try with this code. class Redirect_to_page(RedirectView): async def sleep_long(self): for i in range(1,10): print(f'Run {i}') await asyncio.sleep(1) pass query_string = True pattern_name = 'pages:redirect_page' def get_redirect_url(self, *args, **kwargs): asyncio.run(self.sleep_long()) print('This run before complete!') return super().get_redirect_url(*args, **kwargs) and this is result. Run 1 Run 2 Run 3 Run 4 Run 5 Run 6 Run 7 Run 8 Run 9 This run before complete! But I want result like_ Run 1 This run before complete! Run 2 Run 3 Run 4 Run 5 Run 6 Run 7 Run 8 Run 9 -
Django channels daphne: missing 1 required positional argument: 'send'
Hi I am having issues getting django channels working in production. I am running gunicorn --bind 0.0.0.0:8000 project_name.asgi to test that my ASGI setup is working correctly (This all works on my local machine which is super odd. Maybe I am missing something): This is the error I keep getting :( I have tried everything online but nothing is working: Traceback (most recent call last): File "/home/quilt/quilt_env/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 136, in handle self.handle_request(listener, req, client, addr) File "/home/quilt/quilt_env/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 179, in handle_request respiter = self.wsgi(environ, resp.start_response) TypeError: ProtocolTypeRouter.__call__() missing 1 required positional argument: 'send' my requirement file has the following: channels==4.0.0 channels-redis==4.0.0 daphne==4.0.0 Django==4.1.5 billiard==4.1.0 asgiref==3.6.0 This is my settings file: ASGI_APPLICATION = 'project_name.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ["127.0.0.1", "6379")], }, }, } This is my asgi.py setup: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') django.setup() from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack import notifications.routing application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter( notifications.routing.websocket_urlpatterns ), ) ) }) This is my routing in notification app: from django.urls import path from notifications import consumers websocket_urlpatterns = [ path("ws/", consumers.NotificationConsumer.as_asgi()), ] And then this is my consumer.py file: import json from asgiref.sync import sync_to_async from … -
Django filtering with ipaddress lib
For example, I got a table with address field which can store both ip and subnet addresses. Called IPTable. And a got entire ip address like '127.0.0.1' How can i write a query to get data that into subnet? IPTable.objects.create(address='127.0.0.0/32') IPtable.objects.filter('127.0.0.1' in '127.0.0.0/32')?? Tried to use ipaddress lib to get all ips from this subnet -
Create and update 3 tables OneToMany relationship with nested serializers in Django Rest Framework
I have 3 tables in my database : Quiz - question - answer, with this models class Quiz(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class Question(models.Model): id = models.AutoField(primary_key=True) question = models.CharField(max_length=255) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions") class Answer(models.Model): id = models.AutoField(primary_key=True) answer = models.CharField(max_length=255) is_correct = models.BooleanField() question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="answers" ) i need to override create and update method for create or put/patch a quiz with questions and answers in one time with the default route. i try différent things to do this. My create methode is is operational thise is the serializers of quizz questio nand answers : class AnswerSerializer(ModelSerializer): class Meta: model = Answer fields = ( "id", "answer", "is_correct", ) class QuestionSerializer(ModelSerializer): answers = AnswerSerializer(many=True, required=True) class Meta: model = Question fields = ("id", "question", "answers") class QuizSerializer(ModelSerializer): questions = QuestionSerializer(many=True, required=True) class Meta: model = Quiz fields = ("id", "name", "questions") # create function for create a quiz with questions and answers def create(self, validated_data: Dict[str, Any]) -> Quiz: questions = validated_data.pop("questions") quiz = Quiz.objects.create(**validated_data) for question in questions: answers = question.pop("answers") question = Question.objects.create( quiz=quiz, question=question.get("question") ) for answer in answers: Answer.objects.create( question=question, answer=answer.get("answer"), is_correct=answer.get("is_correct"), ) return quiz my views : … -
Data does not get saved in database ; unexpected keyword arguments
I have gone through many solutions posted on SO and other places but have been running into the same issue. Pretty new to django and trying to understand where I am going wrong I am getting the following error TypeError: Basetable() got unexpected keyword arguments: 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents' I have the following JSON Data jsonToUse = { "CompanyId": "320193", "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": "-6", "unitRef": "usd", "value": "39789000000" }, { "decimals": "-6", "unitRef": "usd", "value": "50224000000" }, { "decimals": "-6", "unitRef": "usd", "value": "25913000000" }, { "decimals": "-6", "unitRef": "usd", "value": "35929000000" } ] } Model: class Basetable(models.Model): basetable_id = models.AutoField(primary_key=True) CompanyId = models.IntegerField() class Cashcashequivalentsrestrictedcashandrestrictedcashequivalents(models.Model): cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id = models.AutoField( primary_key=True) unitRef = models.CharField(max_length=100) value = models.CharField(max_length=100) decimals = models.IntegerField() basetable_id = models.ForeignKey(Basetable, on_delete=models.CASCADE) Serializer: class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer(serializers.ModelSerializer): class Meta: model = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents fields = ['decimals', 'unitRef', 'value'] class CashFlowSerializer(serializers.ModelSerializer): CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer( many=True) class Meta: model = Basetable fields = "__all__" View: .....#TRIMMED GET SYNTAX..... check = CashFlowSerializer(data=jsonToUse) if (check.is_valid(raise_exception=True)): print("ready to send to db") check.save() return JsonResponse(jsonToUse, safe=False) I want to save the data in the database for the provided JSON -
¿How can i to read request headers using django test?
I'm using ApiClient class but I don't know how to send a headers, I'm trying to do it like this, but the answer is that I'm not authorized. I have been trying to solve it for several hours but I have not been able to, your contribution would be of great help. self.client = APIClient() self.jwt = response.json()["access"] self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.jwt) self.client.headers.update({'Origin': 'https://travelingapps.com.co'}) this is te response: ('status_code', 401), ('content_type', 'application/json'), ('content', 'UNAUTHORIZED')]) -
Graphene Enums not working when using without creating a new class
From the documentation, it's evident that we are not bound to create new classes for using Enums. I have the following code snippet: from graphene import Enum, InputObjectType GRAPH_TYPES = [ ('step', 'Step graph'), ('bar', 'Bar graph'), ('line', 'Line graph'), ('dot', 'Dot graph'), ] class DataType(Enum): VELOCITY = 'velocity' ACCELERATION = 'accelration' class SomeInput(InputObjectType): data_type = DataType('DataTypeEnum') graph_type = Enum('GraphTypeEnum', GRAPH_TYPES) When I head over to GraphiQL, I am able to see SomeInput but graph_type is missing inside. Package versions: graphene-django==2.12.1 graphene==2.1.8 -
Is it acceptable to put a break points in the Django admin site file (admin.py) of my app to debug?
Simply, I need to debug the admin.py file, but it doesn't give me the chance for this, so the error pops up directly without stopping at the break point or going line by line after it. So here I have a problem at line 14 related to the tuples because I have nested tuples without adding a comma after the nested tuple. enter image description here I tried to render the page of the admin site to implement the method line by line, but the error happens directly Sorry for this long question . -
Google Sheets Python Client gives indeterministic behavior
I have created a Django project with uses Google Sheets to store some data. When I make a request to an endpoint (/ca/register), sometimes the request passes successfully with a new ca object being created in the database, and its details being added to the corresponding Google Sheet too. Other times, with the same data, the new CA's data is added to the Django database, but the script responsible for adding the data to the Google Sheets fails, leading the request to fail as a whole. I get a weird error in the deployment logs. PS. CA stands for Campus Ambassador. Attaching the relevant pieces of codes and logs: Error Log Internal Server Error: /ca/register/ Traceback (most recent call last): File "/opt/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/opt/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/app/ca/views.py", line 19, in post … -
How to combine multiple custom management commands in Django?
I wrote a set of commands for my Django project in the usual way. Is it possible to combine multiple commands into one command? class Command(BaseCommand): """ import all files in media in dir and add to db after call process to generate thumbnails """ def handle(self, *args, **options): ... To make easy steps I have commands like: import files, read metadata from files, create thumbnails etc. The goal now is to create a "do all" command that somehow imports these commands and executes them one after another. How to do that? -
I am adding a new row instead of make changes in a existing row in my DB
I am trying to save my form in my data base. But my code adds a new row instead of save changes to the existing one. where is my mistake? view.py def settings(request): error = '' if request.method == 'POST': new_form = TrafficSourcesForm(request.POST) if new_form.is_valid(): new_form.save() else: error = 'Something went wrong!' new_form = TrafficSourcesForm() forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()] return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error}) template <div class="table table-striped table-hover"> <div class="table-row"> <th style="width: 42%">Name</th> <th style="width: 43%">Token</th> <th style="width: 15%">Action</th> </div> {% for form in forms %} <div class="table-row"> <form method="POST"> {% csrf_token %} <div class="table-cell">{{ form.name }}</div> <div class="table-cell">{{ form.token }}</div> <div class="table-cell"><button class="btn btn-lg btn-success w-100"">Save</button></div> </form> </div> </div> If its not clear: I am showing all the table from my databese on the page. I want to edit them and save again to the database. -
Is it possible to map a field to a custom template radio button group?
Question in the title. I have a form like so class SelectTypeForm(forms.Form): the_type = forms.CharField(max_length=100) I have a custom template with a radio button group. How can make the field get the selected value? -
How to merge two model sinto one mode with django?
I have to identical models: class AnimalGroup(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000, blank=True) images = models.ImageField(upload_to="photos/groups") class AnimalSubGroup(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000, blank=True) images = models.ImageField(upload_to="photos/groups") and they have a on-to-many relationship. So AnimalGroup can have multiple AnimalSubGroups But as you see they have identical fields. Question: how to make one model of this? -
How to solve libmagic.dylib - incompatible architecture error?
I'm trying to install my Django project to my M1 Mac laptop but it is giving errors. ..OSError: dlopen(/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib, 0x0006): tried: '/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')), '/System/Volumes/Preboot/Cryptexes/OS/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib' (no such file), '/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')) I do not know why is this happening? I'm using python 3.8 and last version of pip. How can I fix that? -
why there is a yellow line underneath the import modules?
I see this is a problem but the program still runs. Can you point out where is the problem? I'm newbie to programming. Especially to python language.enter image description here I can't solve this on my own even if I search it online. I need a finger to point out where can I solve this problem in models.py.