Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decrypt function not working in python, below is the code
import hashlib from binascii import hexlify from binascii import unhexlify from Crypto.Cipher import AES class AppCrypto: __KEY: str = None __iv = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" def __init__(self, key: str = None) -> None: """ Initialize the class. :param key: The key for the Encryption and Decryption. """ self.__KEY = key def pad(self, data: str): """ Pad the data to be encrypted. :param data: The str data to be encrypted. """ length = 16 - (len(data) % 16) data += chr(length) * length return data def unpad(data): return data[0:-ord(data[-1])] def __get_cipher(self) -> AES: """ Get the cipher object. :param key: The key to be used for encryption. """ bytearrayKey = bytearray() bytearrayKey.extend(map(ord, self.__KEY)) return AES.new( hashlib.md5(bytearrayKey).digest(), AES.MODE_CBC, self.__iv.encode("utf-8"), ) def encrypt(self, plainText: str) -> bytearray: """ :param data: The data to be encrypted. :return: The encrypted data. """ plainText = self.pad(plainText) enc_cipher = self.__get_cipher() return hexlify(enc_cipher.encrypt(plainText.encode("utf-8"))).decode("utf-8") def decrypt(self, encryptedText: str) -> str: """ :param data: The data to be decrypted. :return: The decrypted data. """ dec_cipher = self.__get_cipher() data = unhexlify(dec_cipher.decrypt(encryptedText).decode('utf-8')).encode("utf-8") return self.unpad(data) from AppCrypto import AppCrypto appCrypto = AppCrypto("729C6F92987DCEF8D955D23ED2269354") enc_data = appCrypto.encrypt("Hello, Ninranjan") Output: 0f657d48535896ab573a4cb7e9a967e8d409b7f4f537c3157949abd91e221bf2 plain_tx = appCrypto.decrypt("0f657d48535896ab573a4cb7e9a967e8d409b7f4f537c3157949abd91e221bf2") gives error like TypeError at /propertytax/receipt_entry/ Object type <class 'str'> cannot be passed to … -
how set model for comments-django-xtd
hi guys im new in django. i need to have comments,replay comments, like and dislike, count of replays, numbers of likes and dislikes. so i found django-comments-xtd package. i tried to set it in my project but i didnt found any documenttions that explains well about how use it. i found this link about that but it doesnt explain how i should define my model -
How do I fix my django admin page not loading css although having correct configuration?
I am aware this question has been asked a thousand times, but none of the solutions have worked for me... I was working on the Django tutorial, but when I created the superuser, and entered the admin page, the css was missing. The weird thing is, is that when I check the page source from chrome, and click one of the css references in the html, my computer manages to download the stylesheet. It only had a relative path, and when using chrome's debugger, I can see the page taking some time to download the css. So I guess the static paths are configured correctly, the page actually loads the css, but somehow it is not reflected in the view? I have no idea how such a thing can happen. Things I have tried until now: Setting STATIC_URL Setting STATIC_ROOT Setting PROJECT_DIR Setting static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to urlpatterns Deleting static files and doing manage.py collectstatic every time i modified any files Making migrations again Adding base dir + "templates" to TEMPLATES Setting DEBUG from False to True again I must be missing something simple, but I can't see it. Any help is greatly appreciated. In settings.py: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = … -
Django Grouping(annotating) by Order and Get all Values
I have following model class Attempt(BaseModel): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) answer = models.ForeignKey(to=ModelAnswer,null=True, blank=True,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) order = models.PositiveIntegerField(null=True, blank=True) def __str__(self): return self.category.name class Meta: ordering = ['order'] This model will have 10 records for common order id i.e 1 if there are 10 records on the attempt model same order number will be assigned to them i.e order =1 for the next 10 attempt, same order will be assigned i.e order=2 because 10 records are added at once. I just want to show those 10 records inside the same array as the response having order = 1 and next array for order=2 here are my views class ListAttemptSerializer(generics.ListAPIView): serializer_class = serializers.AttemptSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): data = Attempt.objects.filter(user=self.request.user).values('order').annotate( total=Count('order') ).all() return data Serializer.py class AttemptSerializer(serializers.Serializer): answer = ListAnswerSeiralizer(many=True) category = serializers.CharField() class Meta: model = Attempt fields = [ 'category', 'answer', ] My expected response will somehow look like this [ {"answer": [{ "id": 1, "user": 1, "questions": "what are the facts of this situation?", "subcategory": "Circumstance", "is_intentional": "True", "answer": "string", "created_at": "2022-09-05T10:59:59.551583" }, { "id": 2, "user": 1, "questions": "what are the facts of this situation?", "subcategory": "Circumstance", "is_intentional": "True", … -
how add row dynamically in django formset
In my django app I have two models i.e Product and Real which are connected by many to many relationship. To add the data dynamically in my tables I want to use javascript to Add row or Remove Row button in my forms but unable to do so. Here are the details: Models.py from dataclasses import Field from django.db import models class Product(models.Model): name = models.CharField(max_length = 150) quantity = models.IntegerField() cost = models.DecimalField(max_digits=15, decimal_places=0) sell = models.DecimalField(max_digits=15, decimal_places=0) class Real(models.Model): payment_id = models.CharField(max_length = 150) company = models.CharField(max_length = 150) product = models.ManyToManyField(Product, symmetrical=False) Forms.py from .models import Product, Real from django import forms from django.forms import formset_factory class ProductForm(forms.Form): name = forms.CharField() cost = forms.DecimalField() sell = forms.DecimalField() quantity = forms.IntegerField() ProductFormset = formset_factory(ProductForm) class RealForm(forms.Form): payment_id = forms.CharField() company = forms.CharField() product = ProductFormset() Views.py from django.shortcuts import render, redirect from django.forms import modelformset_factory from .models import Product, Real from .forms import RealForm, ProductForm, ProductFormset def post(request): if request.POST: form = Real(request.POST) form.product_instances = ProductFormset(request.POST) if form.is_valid(): real = Real() real.payment_id = form.cleaned_data['payment_id'] real.save() if form.product_instances.cleaned_data is not None: for item in form.product_instances.cleaned_data: product = Product() product.name = item['name'] product.cost = item['cost'] product.sell = item['sell'] product.sell = … -
Plot Chart.js scatter graph in Django using huge data
I'm developing a scatter graph to visualize the trend of product volume for every product count. x: product count y: product volume From django view, two array list was pass to chart javascript in django template. Here is the code: <script> const volume = {{product_volume}} // <--- array list of product_volume const count = {{product_count}} // <--- array list of product_count const p1ctx = document.getElementById('VolumeChart'); const P1Chart = new Chart(p1ctx, { data: { datasets: [{ type: 'scatter', label: 'Volume', data: volume, // <-------------------- Target to assign 'x' and 'y' data backgroundColor: 'rgb(255, 99, 132)' }], }, . . . </script> However, with huge data (approx.: 15,000), how can I simplify the process of data labelling in the JavaScript using array list of product count and product volume? -
how to autoupdate category by the amount of products in django model
I have a model of the category with title and count and I also have another model called Products which has category as one of its foreign-key. How can I auto-update the category count field by the number of products that comes under the same category? class Category(models.Model): title = models.CharField(max_length = 20) count = models.IntegerFIeld() class Product(models.Model): title = models.CharField(max_length = 20) category = models.ForeignKey(Category, on_delete = models.CASCADE) -
Only one json displays on localhost [closed]
I simply put JSON in variable li and try to show in localhost by return JsonResponse(li) But from the original list [{'_id': 'SC', 'cast_count': 60576}, {'_id': 'General', 'cast_count': 562298}, {'_id': 'OBC', 'cast_count': 389510}, {'_id': 'ST', 'cast_count': 2700}, {'_id': '', 'cast_count': 1904}] I got only random one of this such as: {'_id': 'ST', 'cast_count': 2700} Instead of the full list that has to display Note: I know I'm lacking in basic concept of django so pls help me and if there is some problem in question pls comment or flag instead of downvote -
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