Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in Downloading Files from Django app in Production with Gunicorn & Nginx
I have deployed my Django app on AWS EC2 Instance using this guide. Everything is working fine but the error arises when I download an excel file. (Excel is created using opnenpyxl library). While downloading an xlsx file the application is returning download.htm file. Everything work great on a development server. I tried Adding and removing the download tag. <a href="{% url 'download_estimate_excel_file' project.id project.name %}" class="dropdown-item" download> Download Excel </a>. [Didn't Work] Adding [service] Environment="LANG=ru_RU.UTF-8" to gunicorn.service file (found this on StackOverflow also). [Didn't Work] Thanks in advance. -
Django annotate conditional value
Lets say i have a model like this : class modelA(models.model): name = models.Charfield() class modelB(models.model): model_A = models.ForeignKey('modelA', on_delete=models.CASCADE) value = models.IntegerField() class modelC(models.model): model_A = models.ForeignKey('modelA', on_delete=models.CASCADE) value = models.IntegerField() How can i annotate the query so i can achieve something like this : q = modelA.objects.all().annotate(value= # IF THERE IS modelC exist with related modelA THEN modelC.value ELSE modelB.value #) -
My user contact details from front-end not saved in django admin
I am trying to get the Contact information from my "Contact Us" page to my Django admin but its not displaying, I don't find what could be wrong... my models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=100) public_date = models.DateField() public_time = models.TimeField() image = models.ImageField(upload_to='images/',null=True) body = models.TextField() class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['public_date'] def summary(self): return self.body[:100] def pub_date(self): return self.public_date.strftime('%b %e,%y') # to give layout for time and date def __str__(self): return self.title class Contact(models.Model): msg_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) email = models.EmailField(max_length=70, default="") phone = models.CharField(max_length=70, default="") desc = models.TextField(max_length=500, default="") timeStamp = models.DateTimeField() def __str__(self): return self.name + '---' + self.email # if we write only upto self.name, only name is visible in contact. forms.py from django.forms import ModelForm from .models import Contact class ContactForm(ModelForm): class Meta: model = Contact fields = '__all__' views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from blog.models import Post from .forms import ContactForm from django.shortcuts import get_object_or_404 def allpost(request): post = Post.objects.all() #post = [post[i:i + 3] for i in range(0, len(post), 3)] return render(request,'posts.html',{'posts':post}) def detail(request,blog_id): detail = get_object_or_404(Post, pk = blog_id) #return render(request,'/home/deatils',{'post':detail}) return render(request,'details.html',{'post':detail}) def … -
Set xaxis range plotly dash
How can I set a maximum view of data so that the line graph will not be crowded. My graph looks like this image as you can see the lines are crowded. I want it too looks like this image. Only the recent 9 data will be viewed app.layout = html.Div([ html.Div(style={'display': 'flex'}, children=[ dcc.Graph( id='graph-ph', config={ 'displayModeBar': False, 'displaylogo': False, 'modeBarButtonsToRemove': ['zoom2d', 'hoverCompareCartesian', 'hoverClosestCartesian', 'toggleSpikelines'] }, figure={ 'data': [ {'x': [], 'y': [0, random.random()], 'mode':'lines+markers', }], 'layout': { 'title': 'pH (pH)', 'xaxis': { 'rangeslider': {'visible': True}, }, }, }, ), ]) @app.callback(Output('graph-ph', 'extendData'), [Input('interval-graph-update', 'n_intervals')], [State('graph-ph', 'figure'), ]) def update_extend_traces_traceselect(existing, n_intervals): trace_selection = 0 x_new = datetime.datetime.now() y_new = random.random() return dict(x=[[x_new]], y=[[y_new]]), [trace_selection] -
FileView.get() missing 1 required positional argument: 'request' - class FileView
so i want to called func to html. but when i click the button, it have error message. what i want is, i can save bytes to string and save it to file text. f contains with b'5&\xd7\x8c', it's the result from encryption FileView.get() missing 1 required positional argument: 'request' i don't know what's wrong, can someone check it please? def create_file(f): with open("file.txt", 'w') as file: return file.write(str(f)) class FileView(View): def get(f, self, request, *args, **kwargs): return HttpResponse(f, content_type='text/plain', headers={'Content-Disposition': 'attachment; filename=file.txt'}) def homepage(request): form = AudioForm() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() last_audio = Audio_store.objects.all().last() plaintext = Audio_store.objects.all().values_list('password').last() key = Audio_store.objects.all().values_list('key').last() pt = plaintext[0] ky = key[0] print(pt) print(ky) context={'form':form, 'last_audio':last_audio} enc = encrypt(ky, pt) print(enc) download = create_file(enc) print(download) return render(request, "homepage.html", context) context={'form':form} return render(request, "homepage.html", context=context) in urls: path("", views.homepage, name="homepage"), # to call homepage path("", views.encrypt, name="homepage"), path("create_file", views.FileView.as_view(), name="create_file"), in html to called: <a href="{% url 'create_file' %}"> Download </a> -
Django nested serializer giving me None for all fields
So I'm working with Django and djangorestframework (versions 3.2.12 and 3.12.4, respectively) and I'm running into an issue with nested serializers. I've got FantasyLeague and FantasyLeagueSettings models. FantasyLeagueSettings has a FK to FantasyLeague models.py class FantasyLeague(models.Model): name = models.CharField(max_length=100) managers = models.ManyToManyField(User) yahoo_league_id = models.CharField(max_length=20, blank=True, null=True) class FantasyLeagueSettings(models.Model): league = models.ForeignKey(FantasyLeague, on_delete=models.CASCADE, related_name='settings') max_teams = models.IntegerField(blank=True, null=True) num_playoff_teams = models.IntegerField(blank=True, null=True) playoff_start_week = models.IntegerField(blank=True, null=True) I'm serializing them like so: serializers.py class FantasyLeagueSettingsSerializer(serializers.ModelSerializer): class Meta: model = FantasyLeagueSettings fields = ['max_teams', 'num_playoff_teams', 'playoff_start_week'] class FantasyLeagueSerializer(serializers.ModelSerializer): managers = UserSerializer(read_only=True, many=True) settings = FantasyLeagueSettingsSerializer(many=False, read_only=True) class Meta: model = FantasyLeague fields = ['id', 'name', 'managers', 'settings', 'yahoo_league_id' ] But for some reason FantasyLeagueSerializer(league).data gives me a value of None for all of the settings fields (even though the settings data exists) Testing code: league = FantasyLeague.objects.get(pk=1) print('🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥') print(FantasyLeagueSerializer(league).data) # FantasyLeagueSerializer(league).data: {'id': 1, 'name': 'PLAYING FOR KEEPS', 'managers': [OrderedDict([('id', 1), ('username', 'Smurflo'), ('settings', OrderedDict([('selected_theme', 'kanagawa')])), ('is_staff', True)])], 'settings': OrderedDict([('max_teams', None), ('num_playoff_teams', None), ('playoff_start_week', None)]), 'yahoo_league_id': '461051' } # Note how all of the settings fields are None # Even though league.settings clearly has data and FantasyLeagueSettingsSerializer works print('🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆🎆') print(FantasyLeagueSettingsSerializer(league.settings.all()[0]).data) # {'max_teams': 12, 'num_playoff_teams': 6, 'playoff_start_week': 15} Anyone know what's going on here? … -
how to get django-taggit custom tags in view
I am trying to get two categories of tags to work using django-taggit on one model. Everything seems to be working right in the admin but I can't figure out how to write a view that will let me use two categories of tags. class Photo(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='photos/') submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) year = models.ManyToManyField(Year, blank=True) people = TaggableManager(through=TaggedPeople, verbose_name='People') tags = TaggableManager(through=TaggedGeneric, verbose_name='Tags') def __str__(self): return self.title Then in my view I have class PhotoListView(ListView): model = Photo template_name = 'photoapp/list.html' context_object_name = 'photos' class PhotoTagListView(PhotoListView): template_name = 'photoapp/taglist.html' def get_tag(self): return self.kwargs.get('tag') def get_queryset(self): return self.model.objects.filter(tags__slug=self.get_tag()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tag"] = self.get_tag() context["tags"] = GenericTag.objects.all().order_by('name') context["people"] = PeopleTag.objects.all().order_by('name') return context The "tag" tag is working correctly. How do I get the "people tag" to work with a template to display all the photos with a certain person? -
How to integrate django rest framework with clamav
How can I integrate clamav with django rest framework? I am trying to scan uploaded files via drf with clamav? I installed clamav from https://www.clamav.net/ here is my code ... file = self.request.FILES.get('file') # check a file for viruses if file: print("checking file for viruses") from tempfile import mkstemp from py_clamav import ClamAvScanner import os tmpfile = mkstemp()[1] f = open(tmpfile, 'wb') f.write(file.read()) f.close() with ClamAvScanner() as scanner: # scan file by path infected, virname = scanner.scan_file(tmpfile) os.unlink(tmpfile) if infected: return Response({'message':"virus was detected in your file"},status=status.HTTP_400_BAD_REQUEST) ... I am getting the error: raise FileNotFoundError('Not found libclamav') FileNotFoundError: Not found libclamav Why are my getting this error? Is there a better library I can do this with? -
How I can get data to pop up in django
please how can I get attribut id_benevole Class Participer(Models) i need to show it in the pop up i use this method but nothing is displayed Thanks in advance This is -------->Models.py class Participer(models.Model): id_benevole = models.CharField(max_length=150,null=False,blank=False) id_mission = models.CharField(max_length=150,null=False,blank=False) # def __str__(self): def __str__(self): return self.id_mission This is ------->Views.py def getLB(request): participer=Participer.objects.all() context={ 'participer':participer } print(participerss) return render(request, 'home/Association.html',context) This is ----------> Association.html {% for miss in missions %} <th scope="row">{{miss.id}}</th> <td>{{miss.nom}}</td> <td>{{miss.domaine}}</td> <td>{{miss.lieu}}</td> <td style="white-space: nowrap;width: 1%;" >{{miss.date_publier}}</td> <td style="text-align: center;">{{miss.nombre_participant}}</td> <td>{{miss.association.association.nom_association}}</td> <td><a type="button" class="btn btn-danger mt-5" data-bs-toggle="modal" data-bs-target="#myModal" class="col-11 text-center mt-3">Voir liste des bénévoles</a></td> <div class="modal mt-5" id="myModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="d-flex justify-content-center text-danger"> <h4>Liste des bénévoles participants</h4> </div> {% for par in participer %} <div class="modal-header"> {{par.id_mission}} {{par.id_benevole}} </div> {% endfor %} <div class="modal-footer"> <div class="col-11 text-center mt-3"> <input class="btn gradient-bg" type="submit" value="Confirmer"/> <input type="button" class="btn gradient-bg" data-bs-dismiss="modal" value="Annuler"/> </div> <div> </div> </div> </div> {% endfor %} -
Get count of Options in Django ChoiceField
I have a choiceField in a model and I want to get the count of each choice in my homepage. I alos want the counts to be clickable so that when it is clicked, it redirects me to a page containing all buildings related to it. This is my models.py class Property(models.Model): landlord = models.ForeignKey(User, related_name="lanlord", on_delete=models.CASCADE) title = models.CharField( max_length= 500 ) description = models.CharField( max_length= 50000 ) BUILDING_CHOICES = [ ("Flat" , "Flat" ), ("Duplex" , "Duplex" ), ("Bungalow" , "Bungalow" ), ("Apartment" , "Apartment" ), ("Shop" , "Shop" ), ("Warehouse" , "Warehouse" ), ("Storey Building" , "Storey Building" ), ] buildingtype = models.CharField( max_length=20, choices=BUILDING_CHOICES, default='Bungalow' ) This is my home page <ul class="home4_iconbox mb0"> <li class="list-inline-item"><div class="icon"><span class="flaticon-house"></span><a> Storey Building</a></div></li> <li class="list-inline-item"><div class="icon"><span class="flaticon-house-1"></span><a>Shop</a></div></li> <li class="list-inline-item"><div class="icon"><span class="flaticon-house-2"></span><a>Duplex</a></div></li> <li class="list-inline-item"><div class="icon"><span class="flaticon-building"></span><a>Apartment</a></div></li> </ul> This is my views.py def home(request,): q = request.GET.get('q') if request.GET.get('q') != None else '' props = Property.objects.filter( Q(title__icontains = q) | Q(address__icontains = q) | Q(buildingtype__icontains = q) ) property = Property.objects.all() properties = Property.objects.filter(is_approved = True)[:5] context = {"props":props, "property": property, "properties": properties} return render(request, "base/index.html", context) -
Chart.js not displaying in django site
I am trying to display Charts with chart.js, but it's not displaying... below is my code In Views.py i prepared the queryset to display how many people have Gluten Allergy, Peanut allergy and so on... def patientsView(request): gluten_allergy = MedicalRecord.objects.filter(gluten_allergy = True).count() # gluten_allergy = int(gluten_allergy) print('Number of Gluten Allergy patients Are',gluten_allergy) peanut_allergy = MedicalRecord.objects.filter(peanut_allergy = True).count() # peanut_allergy = int(peanut_allergy) print('Number of Peanut Allergy patients Are',peanut_allergy) covid_history = MedicalRecord.objects.filter(covid_history=True).count() # covid_history = int(covid_history) print('Number of Covid History patients Are',covid_history) ebola_history = MedicalRecord.objects.filter(ebola_history=True).count() # ebola_history = int(ebola_history) print('Number of Ebola History patients Are',ebola_history) GROUP_A = MedicalRecord.objects.filter(blood_type='A').count() # GERT = MedicalRecord.objects.filter(blood_type='A') # GROUP_A = int(GROUP_A) print('Number of Male Are',GROUP_A) GROUP_B = MedicalRecord.objects.filter(blood_type='B').count() # GROUP_B = int(GROUP_B) print('Number of patients with Group B Are ' ,GROUP_B) GROUP_AB = MedicalRecord.objects.filter(blood_type='AB').count() # GROUP_AB = int(GROUP_AB) print('Number of patients with Group AB Are', GROUP_AB) GROUP_O = MedicalRecord.objects.filter(blood_type='O').count() # GROUP_O = int(GROUP_O) print('Number of patients with Group O Are', GROUP_O) blood_type = ['GROUP_A', 'GROUP_B', 'GROUP_AB', 'GROUP_O'] blood_type_count = [GROUP_A, GROUP_B, GROUP_AB, GROUP_O] condition_list = ['Gluten Allergy', 'Peanut Allergy', 'Covid History', 'Ebola History'] condition_list_count = [gluten_allergy, peanut_allergy, covid_history, ebola_history] context = {'condition_list':condition_list, 'condition_list_count':condition_list_count, 'blood_type':blood_type, 'blood_type_count':blood_type_count} return render(request, 'patients/homechart1F.html', context) In my Base.html loaded the javascipt libraby for … -
Docker compose not installing django or not finding Django after installation
Docker-Compose.yml version: '3.9' services: nginx: restart: unless-stopped build: context: . dockerfile: ./docker/nginx/Dockerfile ports: - 80:80 - 443:443 volumes: - dev-static_volume:/vol/static - dev-media_volume:/vol/media - ./docker/nginx:/etc/nginx/conf.d depends_on: - app command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\"'" app: restart: unless-stopped build: context: . dockerfile: ./docker/server/Dockerfile entrypoint: /app/docker/server/entrypoint.sh volumes: - dev-static_volume:/vol/static - dev-media_volume:/vol/media expose: - 8000 environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme - DEBUG=1 depends_on: - db db: image: postgres:13-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-static_volume: dev-media_volume: dev-db-data: Dockerfile: FROM python:3.10-alpine MAINTAINER = 'Me' ENV PYTHONUNBUFFERED 1 COPY ./fp-backend/requirements.txt /tmp/requirements.txt COPY ./fp-backend/requirements.dev.txt /tmp/requirements.dev.txt COPY ./fp-backend/app /app COPY ./docker /app/docker WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache nodejs npm && \ apk add --update --no-cache postgresql-client jpeg-dev && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \ /py/bin/pip install -r /tmp/requirements.txt && \ /py/bin/pip install Django && \ if [ $DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ … -
Change Elastic Bean Stalk Platform
I have been having troubles deploying my application with Elastic Beanstalk. I need to change the platform I am using to a current one that is accepted. I am using python 3.10.6 in my project so I am completely unsure of where the version 2.6 came from. enter image description here -
How do I pass serializer data in Django httpresponseredirect?
Here is my initial login view: class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) This gives the below results after login: But then to prevent form resubmission, I changed from Response to HttpResponseRedirect: class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return HttpResponseRedirect(reverse('login',serializer.data, status=status.HTTP_200_OK)) # new But it gives me the error: TypeError: unhashable type: 'ReturnDict' Is there a workaround for this? -
Django translations does not work for html templates
The project running Django 4.1 with the settings below: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'uk' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, '/locale'), os.path.join(BASE_DIR, 'apps/hub/locale'), ) LANGUAGES = ( ('uk', _('Українська')), ('en', _('English')), ) I run makemessages and compilemessages and get dajngo.po file with the following content: Two items below are from html and are not changing upon language has changed. #: .\templates\_footer.html:14 .\templates\_header.html:12 msgid "Головна" msgstr "Home" #: .\templates\_footer.html:15 .\templates\_header.html:13 msgid "Про нас" msgstr "About" But this item below does work: #: .\apps\hub\views.py:19 msgid "Выход" msgstr "Exit" All html files except base.html start with {% load i18n %}, have tags {% translate "Головна" %} Do I miss something? -
Django - UpdateView: After update by not superuser person who create get change on none
my problem is when i update my model by class MovieUpdateView(UpdateView) and i am not superuser, person who create get change on None when i want him stay old. Ik that issue is that i only change this field in tempalte only for superuser but don't know how to change it. views: class MovieUpdateView(UpdateView): model = Movie template_name = 'movies_collection/form_movie_update.html' fields = ['title', 'gender', 'youtube_trailer_url', 'user', 'director'] success_url = reverse_lazy('movie-list') template: <form method="post" novalidate> {% csrf_token %} <div class=""> <p> Title: <b>{{ form.title }}</b> </p> <p> Gender: <b>{{ form.gender }}</b> </p> <p> YouTube trailer url: <b>{{ form.youtube_trailer_url }}</b> </p> <p> Director: <b>{{ form.director }}</b> </p> {% if user.is_superuser %} <p> User: <b>{{ form.user }}</b> </p> {% endif %} <button type="submit" class="btn btn-primary btn-block">Submit</button> </form> -
Django Rest Framework - Create object with foregin key relation
I created simple REST API which i want to create product objects. My problem is that API view is not showing me multiple choice field to choose from existing categories. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Meta: ordering = ('name',) class Product(models.Model): name = models.CharField(max_length=200, unique=True) price = models.PositiveSmallIntegerField(default="") category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, default=None) def __str__(self): return self.name class Meta: ordering = ('name',) serializers.py from rest_framework import serializers from .models import Product, Category class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' views.py from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from .models import Product, Category from .serilaizers import ProductSerializer, CategorySerializer from rest_framework.response import Response from rest_framework.views import APIView class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class CategoryView(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer That is what i get after running server, only two positions -
Django MultiValueField and MultiWidget AttributeError: 'CharField' object has no attribute 'is_hidden'
I am trying to make a field that can select a day of the week and a time of that day. I read the document and this is what I managed to do. class ClassTimeWidgit(forms.MultiWidget): def __init__(self, attrs=None) -> None: widgets = [forms.CharField(), forms.TimeField()] super(ClassTimeWidgit, self).__init__(widgets, attrs) class ClassTimeField(forms.MultiValueField): widget = ClassTimeWidgit def __init__(self, **kwargs) -> None: f = ( forms.CharField(widget=forms.Select(choices=[ ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday'), ]) ), forms.TimeField(input_formats='%H:%M') ) super().__init__(fields=f, require_all_fields=True, **kwargs) class RequestCourseForm(forms.ModelForm): teacher = forms.ModelChoiceField(queryset=User.objects.filter(profile__teacher_status=True)) class_count = forms.IntegerField(widget=forms.Select(choices=[(10,10), (20,20)])) class_time = ClassTimeField() class Meta: model = Request fields = ['teacher', 'class_count', 'class_time'] Before I had the MultiValueField on its own and it displayed a one-line textbox, so I added the MultiWidget class and it is giving me this error AttributeError: 'CharField' object has no attribute 'is_hidden' I am new to Django, please point out any obvious mistakes that you see, and please let me know if there is a better way to do what I am trying to do. -
Save ImageField to different folders
I have two models that inherit from a Base model as following ''' games = [ ('DND5E', 'Dungeons and Dragons'), ('TOR20', 'Tormenta20'), ] class BaseSheet(models.Model): ... game: str = models.CharField(default='', max_length=5, choices=games) ... class DnDMonster(BaseSheet): ... image = models.ImageField(upload_to='images/monsters/DnD5e') ... class Tor20Monster(BaseSheet): ... image = models.ImageField(upload_to='images/monsters/Tor20') ... ''' The way i'm thinking it, it's more organized that way, so I can place images from different games in different folders, not one giant folder with everything in it I am having some problems when I want my client to see everything that inherits from BaseSheet and the their images, so I want to put this ImageField in the BaseSheet. When I try to do that, it seems I can't put the images in different folder depending on the game the Monster has. Is there a way to do so? Is there a better way to do it? -
Dynamic URL routing from html form within action in Django
I have a simple form which shall take a user input and directly send the user to a dynamic url using the input. Inputing "111" into the form shall send the user to /number_input=111 Somehow i can not get it done, since i do not know how to get direct variable value from the form to the view immediately. I can build it with 2 views but that looks somehow ugly and inconvenient. Here is what i have so far: The Form: (within index.html) <form action={% url 'my_view'%} method="POST"> {% csrf_token %} <p><input type="text" name="inp_number" placeholder="Insert Number"/></p> <p><input type="submit" value="Submit"/></p> </form> views.py: def number_view(request): if request.method == 'POST': context = {'number': request.POST['inp_number']} return render(request, 'number.html', context) urls.py from . import views urlpatterns = [ path('number_input=<int:number>/', views.number_view, name='number_view') ] The dynamic part here (int:number) will make the code fail, since iam not sending a value from the form, right? But i only know how to send static values (i.e. action={% url 'my_view' 111 %}. How can i send direct dynamic values from the form itself (the value that the user inputs in the submit button)? number.html <h2>This page is for number {{ number }}</h2> -
About customizng drop down menu information in django import export module
Please consider this a book library website, I have three models here: models.py class books(models.Model): book_name = models.CharField(verbose_name='book name',max_length=24) book_desc = models.CharField(verbose_name='book description',max_length=240) class classes(models.Model): class_name = models.CharField(verbose_name='class name',max_length=24) class map_book_class(models.Model): book_id = models.ForeignKey(books, on_delete=models.CASCADE, verbose_name='book ID') class_id = models.ForeignKey(classes, on_delete=models.CASCADE, verbose_name='class UID') Here are some simple explains for the model: The first model is for adding new books, including it's name and book description, the model id will be generated automaticly by django. The second model is for adding new categories for the book, for example: recipes, toolbooks... etc. The model id will be generated automaticly by django too. The third model is for a mapping table, which connects the book data added by the first model, and the category data added by the second model together by using ids from above two models as foreign keys. After this, the data should be mapped together like this: John's Story(book name), Adventures(category). My question is, after I successfully built up those three models, and I added following data by using the django admin page. books id book_name book_desc 1 John's Story a story for kids. 2 Best recipes good foods. classes id class_name 1 Adventures 2 Toolbooks By using the … -
Cant connect to mysql [Access denied for user 'root'@'localhost' (using password: YES)] when using pytest to test django project running on wsl2
I'm using wsl2 to run my django project and I'm using dotenv to hide the project credentials like MYSQL database password cause I don't want these data on github enter image description here and this is my settings file enter image description here It was working and I could run my migrations, but the weirdest error I have run into when I tried to use pytest enter image description here when i tried to run tests gives me access denied enter image description here but when I tried to add the password in the database settings enter image description here It connected to my database and my tests passed enter image description here I tried every thing but it was useless, if anyone could help I would be gratefull. -
Why My Django Code Is Not Going To Else Part?
Here Is My views.py Where I written User Login Code And The Promblem I'm Facing Is That The Code Is Working Properly For Authenticating User But When User Enter Wrong Credential then I Want User To Take Him/Her To Register Page But I'm Unable To Take It To Register Page Please Help Me Thorugh This And Let Me Know Where I'm Doing Mistake def user_login(request): if request.method == "POST": fm = AuthenticationForm(request=request,data=request.POST) if fm.is_valid(): uname = fm.cleaned_data['username'] pword = fm.cleaned_data['password'] user = authenticate(username=uname,password=pword) if user is not None: login(request,user) return HttpResponseRedirect('/profile/') else: return HttpResponseRedirect('/register/') else: fm = AuthenticationForm(request) return render(request,'login.html',{'form':fm}) Here Are My urls.py from . import views urlpatterns = [ path('',views.index), path('register/',views.user_register,name='user_register'), path('login/',views.user_login,name='user_login'), path('profile/',views.user_profile,name='user_profile'), ] -
django custom forms with models, also with 'choices' as values, how should I approach this problem?
django forms is giving me a pretty bad headache... I've been struggling with this for 2 hours now. I wanted to make a custom form for a model to be able to add objects to it and also be able to move the fields as I want to (instead of using form.as_p (or form|crispy), I wanted to put the entire form in a grid-like table using a custom pattern, not only putting one under another) but whenever I put a choicefield (which is either a choicefield or a foreignkey) their values are empty and also, 3 out of 4 formfields are actually shown, one remains the default. It contains fields='__all__' with 3 choicefields and 1 floatfield each with a label, nothing more. To show the forms in html I used {% for field in form.visible_fields %} {{ field.label_tag }} {{ field.errors }} {{ field }} {{ field.help_text }} {% endfor %} which works well. Am I trying to solve the problem in a wrong way? I'll come back to this topic tomorrow, I'll need some rest now but I don't understand why passing a choices=TheModel # or # choices=TheModel.ojbects.all() breaks the entire thing. Is there a website or a youtube … -
How do I collect all my Django data from the database before invoking my serializer?
I'm using Python 3.9 and Django 3.2. I have a Django model with a couple of many-to-many relationsips class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address, through='CoopAddressTags') enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() description = models.TextField(null=True) approved = models.BooleanField(default=False, null=True) proposed_changes = models.JSONField("Proposed Changes", null=True) reject_reason = models.TextField(null=True) I can search for my model using a manager class that builds a query like so ... def find( self, partial_name, types_arr=None, enabled=None, city=None, zip=None, street=None, state_abbrev=None ): """ Lookup coops by varying criteria. """ q = Q() if partial_name: q &= Q(name__icontains=partial_name) if enabled != None: q &= Q(enabled=enabled) if types_arr != None: filter = Q( *[('types__name', type) for type in types_arr], _connector=Q.OR ) q &= filter if street != None: q &= Q(addresses__raw__icontains=street) if city != None: q &= Q(addresses__locality__name__iexact=city) if zip != None: q &= Q(addresses__locality__postal_code=zip) if state_abbrev != None: q &= Q(addresses__locality__state__code=state_abbrev) q &= Q(addresses__locality__state__country__code="US") queryset = Coop.objects.filter(q) print(queryset.query) return queryset In my view, I invoke and return the data using coops = Coop.objects.find(...) serializer = CoopSearchSerializer(coops, many=True) in which the serializer looks like class CoopSearchSerializer(serializers.ModelSerializer): ... …