Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Input model value by operation Django
I'm trying to input a model form by operation in Django, but i really don't know how to do it... Here is my code, where profit should be (valorContrato - valorGasto) I also would like that the user couldn't input anything manually in this field models.py class Contrato(models.Model): nome = models.CharField(max_length=60) bioContrato = models.TextField(null=True, blank=True) cliente = models.ForeignKey(Cliente, on_delete=models.SET_NULL, null=True) valorContrato = models.FloatField(max_length=45, null=True, blank=True) valorGasto = models.FloatField(max_length=45, null=True, blank=True) profit = models.FloatField(max_length=45, null=True, blank=True) dataContrato = models.DateField(null=True, blank=True) dataEntrega = models.DateField(null=True, blank=True) arquivos = models.FileField(upload_to='arquivos_contratos', null=True, blank=True) def __str__(self): return self.nome -
Is it okay to use the same Redis store for both cache and django-channels channel layer in Django?
I have a Django 3.1 app that uses Redis for its cache backing store (django-redis). I wish to use django-channels, which has the ability to use Redis for channel layers. Is it safe or unsafe to use the same Redis store for both? In other words, I wish to have the following in my settings.py, and I want to know if that's okay. import environ env = environ.Env() REDIS_HOST = env('REDIS_HOST', default='127.0.0.1') REDIS_PORT = env('REDIS_PORT', default='6379') CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', "LOCATION": "redis://" + REDIS_HOST + ":" + REDIS_PORT + "/0", 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'CONNECTION_POOL_KWARGS': {'max_connections': 30}, 'IGNORE_EXCEPTIONS': True, } } } CHANNEL_LAYERS = { "default": { 'BACKEND': 'channels_redis.core.RedisChannelLayer', "CONFIG": { "hosts": [(REDIS_HOST, int(REDIS_PORT))], }, } } -
Django html table - how to specify/locate a certain cell?
new to django and everything. I'm trying to figure out how to specify or locate a certain cell in a html table. I would like to change the background color of certain cells if certain conditions are met based on the generated grid. I've registered a simple_tag, and I would like to be able to tell it which cell to change. For example, if value of row 3, column 4 == x, then apply red background; or find cell of row 2, column 5, etc. How do I address it? Here's a simplified version of what I've done so far: from views.py: list1 = [a,b,c,d,e,f] # this is basically what the table (grid) looks like list2 = [b,c,a,d,f,e] list3 = [f,a,e,d,c,b] list4 = [c,d,a,b,f,e] list5 = [d,e,b,a,f,c] list6 = [e,b,a,c,d,f] grid = [list1, list2, list3, list4, list5, list6] result1 = [0, 1, 2] result2 = [4, 5] results = [result1, result2] .html {% for var in grid %} <table> <tr> <td class='{% bg_color var.0 %}'>{{ var.0 }}</td> <td class='{% bg_color var.1 %}'>{{ var.1 }}</td> <td class='{% bg_color var.2 %}'>{{ var.2 }}</td> <td class='{% bg_color var.3 %}'>{{ var.3 }}</td> <td class='{% bg_color var.4 %}'>{{ var.4 }}</td> <td class='{% bg_color var.5 %}'>{{ … -
Design question: How would you design a temporary user table?
I am in the process of designing a website that would allow sports coaches to create teams, and then add players to that team. The goal is to allow coaches to add players to their team and associate stats to them by entering match data. The issue I'm running into is the ability for players to create their own account and link their account to one of the players the coach made. The coach would be able to enter a player account's unique ID and select a player he created on the team, and give the player access to the stats he entered for the 'fake' user. The fake user would be deleted at this point. My initial design for tackling this is as follows: I will use the default 'Users' table, and link it to a 'Profile' table via a OneToOneField. Whenever a coach creates a player for their team, a user will be created and an associated profile. The fake user would have a UUIDField as an ID in the Profile table. I'm storing the stats for players as follows: class Stats(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) match = models.ForeignKey(Match, on_delete=models.CASCADE) player = models.ForeignKey(User, on_delete=models.CASCADE) ... ... several … -
COPY failed: stat /var/lib/docker/tmp/docker-builder713892078/requirements.txt: no such file or directory
When i build Dockerfile sudo docker build . Copy command inside simple Dockerfile fail. Operating system is Ubuntu Dockerfile: FROM python:3.8-alpine MAINTAINER mojtaba nafez ENV PYTHONUNBUFFERD 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user User user the folder "/var/lib/docker/tmp" in my ubuntu system is empty! Output of build Command that's mentioned above is: Sending build context to Docker daemon 68.61kB Step 1/10 : FROM python:3.8-alpine ---> ff6233d0ceb9 Step 2/10 : MAINTAINER mojtaba nafez ---> Using cache ---> 45e8f256f9ce Step 3/10 : ENV PYTHONUNBUFFERD 1 ---> Using cache ---> dec1458c5753 Step 4/10 : COPY ./requirements.txt /requirements.txt COPY failed: stat /var/lib/docker/tmp/docker-builder733337810/requirements.txt: no such file or directory requirements.txt: Django>=2.2.0,<=3.1.2 djangorestframework>=3.9.0,<3.10.0 Dockerfile and requirements.txt are in the same folder -
Hide components in Django Forms
I am currently working on a django project and I would like to be able to hide some components in the form until the user triggers it. I decided to use the form manually and I have not been able to get the desired results. Below is an image of the form in it simplest state I would want the page to load with only 'First Name', 'Last Name' and 'Your Choice' displaying and the choice of the user should trigger either 'Your Hostel' or 'Your City' to pop up. Below is the manual form <form method="post" class="order-form"> {{ form.non_field_errors }} <div id="first" class="fieldWrapper"> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }}">First Name:</label> {{ form.first_name }} </div> <div id="last" class="fieldWrapper"> {{ form.last_name.errors }} <label for="{{ form.last_name.id_for_label }}">Last Name:</label> {{ form.last_name }} </div> <div id="option" class="fieldWrapper"> {{ form.delivery_option.errors }} <label for="{{ form.delivery_option.id_for_label }}">Your Choice:</label> {{ form.delivery_option }} </div> <div id="hostle" class="fieldWrapper"> {{ form.hostel.errors }} <label for="{{ form.hostel.id_for_label }}">Your Hostel:</label> {{ form.hostel }} </div> <div id="city" class="fieldWrapper"> {{ form.city.errors }} <label for="{{ form.city.id_for_label }}">Your City:</label> {{ form.city }} </div> Can someone kindly help me. I'm new to this environment. Thanks in advance -
django: validate count of a many to many relation before saving to database
I'm a little bit stuck in my django project. I want to do the following: I have two models(unnecessary parts left out): models class UserGroup(models.Model): max_users = IntegerField() @property def user_count(self): return len(self.user_set.objects.all()) class User(models.Model): groups = models.ManyToManyField(UserGroup) forms class RegisterForm(ModelForm): class Meta: model = user fields = ['usergroup'] widgets = {'usergroup': CheckboxSelectMultiple()} def clean_usergroup(self): qs = self.cleaned_data['usergroup'] a = len(qs) if len(qs) > 2: raise ValidationError("Your group limit is 2") return qs The UserGroups can be defined, usually there are 3 to 5 and each UserGroup has a maximum of users that can join it. However a user is able to join multiple groups, but he should be restricted to join 2 groups at maximum. The user can choose his groups via a ModelForm which is generated from the User Model. My approach was to override the clean() method of the form and the clean_groups() of the form, but I always ran into the problem, that when the form is reloaded I get an Exception: ValueError: "<User: User object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. I know this makes sense since there isn't a saved m2m relation that can … -
Where is the error? Why average_rank does not displayed?
Friends , where is the problem , average_rank does not diasplayed in GET response My Models.py class Car(models.Model): Make_Name = models.CharField(max_length=100) Model_Name = models.CharField(max_length=100) class Rating(models.Model): RATING_CHOICES = ( (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) rating = models.IntegerField(choices=RATING_CHOICES) car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='rating') Views.py class CarViewSet(ListCreateAPIView): serializer_class = CarSerializers def get_queryset(self): queryset = Car.objects.all() Car.objects.aggregate(average_rank = Avg('rating__rating')) return queryset serializers.py: class CarSerializers(serializers.ModelSerializer): average_rank = serializers.DecimalField(read_only=True,decimal_places=1,max_digits=10) class Meta: model = Car fields = ['Make_Name','Model_Name','average_rank'] -
Posting Base64 with Axios cause [Errno 54] Connection reset by peer
I am currently working on a web-application using VueJS for the front-end and Django (Django Rest Framework) for the back-end. One of the feature of the application is to send a pdf invoice by mail. So I was able to generate the pdf using "jspdf" library. And on Django side, I made an API end-point in order to send an email (with the pdf attached). So the logic is (tell me if it's wrong to do that): Converting the output pdf to Base64 on the front-end in order to post it to my "sendmail" endpoint with Axios. Decoding the Base64 string on the back-end, write a temp pdf file, and attached it to send the mail. It works perfectly, I tested it, the post request have a status 200. I receive the mail with the pdf attached... But on django side, I got "[Errno 54] Connection reset by peer". Here's the full error: [24/Nov/2020 21:50:53] "POST /api/sendmail/ HTTP/1.1" 200 0 -------------------------------------------- Exception happened during processing of request from ('127.0.0.1', 59267) Traceback (most recent call last): File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 696, in __init__ self.handle() File … -
Create a one to many relationship with Django
Hey guys I'm making a social media app and I have a User table with the generic User Model from Django used. I'm now creating a Follow table where I want to keep track of the different usernames the user follows and a count of those following him (I don't need to display the names for the followers field just the amount of followers a user has). How would I go about doing this? Right now this is what I have, but I'm unable to view the actual data in the database so I'm not sure how it works. Is there a column for username that is borrowed from the User model? I can't find solid information on how this works. from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import ArrayField from django.db import models class User(AbstractUser): pass class Follow(models.Model): followers = models.IntegerField(default=0) following = models.ForeignKey(User, related_name = 'follow_to_set', on_delete = models.CASCADE) class NewPost(models.Model): username = models.CharField(max_length=64) body = models.CharField(max_length=64) likes = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) -
Django REST serialize customizing field mapping group by date
Problem: Not able to group my JSON output by date I am serializing a model and getting this output: [ { "date": "2020-11-24", "name": "Chest", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 80 } }, { "date": "2020-11-24", "name": "Chest", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 85 } }, { "date": "2020-11-24", "name": "Chest", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 90 } }, I want to get it like the JSON below and group it by date. [ { "date": "2020-11-24", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 80 }, "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 85 }, "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 90 }, } ] I have one model: class WorkoutLog(models.Model): date = models.DateField() name = models.CharField(max_length=50) #When save() name = Workout.name exercise = models.ForeignKey('Exercise', related_name='log', on_delete=models.CASCADE) repetitions = models.IntegerField() weight = models.IntegerField() Trying to serialize and group the JSON by date: class WorkoutLogSerializer(serializers.ModelSerializer): class Meta: model = WorkoutLog fields = ['date', 'workout'] workout = serializers.SerializerMethodField('get_workout') def get_workout(self, obj): return { 'name': obj.name, 'exercise': obj.exercise_id, 'repetitions': obj.repetitions, 'weight': obj.weight, } The code lets me custom the field layout, but not really grouping it by date. … -
Running Pillow Django Python
I Have a Django project working just fine on my windows machine with python 3.6 and now I am trying to run my Django code on this iOS machine but sadly when I run pip3 to instal my requirements it prints this error: Running setup.py install for Pillow ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-install-nlvm4jl5/pillow/setup.py'"'"'; __file__='"'"'/private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-install-nlvm4jl5/pillow/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-record-3zn9ygo2/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/Pillow cwd: /private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-install-nlvm4jl5/pillow/ Complete output (172 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.9 creating build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpoImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageMode.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PngImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/XbmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PcxImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SunImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/TarIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FitsStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpegImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/BdfFontFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GribStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageStat.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PixarImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageColor.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ContainerIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MspImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MicImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/_version.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImtImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GifImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PalmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageQt.py -> build/lib.macosx-10.9-x86_64-3.9/PIL … -
Django Rest Framework: How to show fields of many to many field?
I'm finding a way to serialize model fields of a Many To Many relation object. Models class Tag(models.Model): name = models.CharField(max_length=150) description = models.TextField(blank=True) class Book(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=255, unique=True) tag= models.ManyToManyField(Tag, related_name='books', blank=True) Serializers - class BookSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) slug = serializers.SlugField(read_only=True) class Meta: model = Book fields = '__all__' Views - class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() lookup_field = 'slug' serializer_class = BookSerializer def perform_create(self, serializer): return serializer.save(owner=self.request.user) I want to add the tag name to the response of the detailed view as well as the list view of books. If I try to create a serializer for the Tag model and use it in the book serializer, I'm not able to create or update the Book. What should I do? Also, is there a way to update only the tag field? -
How do I email a user a temporary password in Django and allow them to change their password?
I need to send a Django user a random temporary password to their email, so that they can use it to change their forgotten password. They should be able to come back to the forgot password page and type in their temporary password to change it to a new one. How do I do this in Django? This is only for testing purposes and not for actual development. What's the best way to quickly implement this feature and test it in Django? -
i want to change on 2 webpages at same time
[ana document.addEventListener('DOMContentLoaded',function(){ document.querySelector('.first').addEventListener('dragover',dragOver); document.querySelector('.first').addEventListener('drop',drop); }) function dragOver(event){ event.preventDefault(); } var count=0; function drop(event){ if (count!==0){ document.querySelector('.drag_btn_btn').style.display='none'; document.querySelector('.text-btn-index').style.display='block'; } else{ document.querySelector('.drag_slider_btn').style.display='none'; document.querySelector('.slider-index').style.display='block'; count++; } } /* 1st page */ <Button>Run</Button> <div class="second" style="padding-left: 40px;"> <button class="drag_slider_btn" style="background-color: gray; position: absolute; left: 35px; top:80px;" draggable="true">Slider</button> <button class="drag_btn_btn" style="background-color: gray; position: absolute; left: 35px; top:200px;" draggable="true">TextField</button> </div> <div class="first"> <section class="sec1" style="width: 70%; height: 100px; position: absolute; left: 100px;" id="section1_index"> <input type="range" min="-2" max="2" value="0" class="slider slider-index" id="slider" draggable="false" style="width: 300px; display: none;"> </section> <section class="sec2-i" style="width: 70%; height: 100px; margin:40px; margin-top:5px;"> <button style="background-color: gray; position: absolute; left: 180px; top:200px; display: none;" class="text-btn-index" draggable="false">0</button> </section> </div> /*second page */ <div class="second" style="padding-left: 40px;"> <h3 style=" border:1px solid black; background-color:grey; height:80px; width:100px; margin-top: 80px;" class="dropitem h3-d" id="text-box" draggable="true">Python code</h3> </div> <div class="first"> <section class="sec1" style="width: 70%; float: left; height: 100px; margin:40px; margin-top: 5px;"> <button class="diagram-slider" style=" display:none; background-color: gray; position: absolute; left: 30px; top:70px;">Slider</button> </section> <section class="sec2" style="width: 100%; height: 170px; position:absolute; top:120px; left:0px; margin-top:5px; border:1px solid black;"> </section> <section class="sec3"> <button class="diagram-textbox" style=" display:none; background-color: gray; position: absolute; left: 300px; top:300px;">TextField</button> </section> </div> ]1i have 2 webpages and i have already defined the slider in both the property is set to none i … -
Django is not showing image when using AWS
I am having an issue displaying an image from the AWS bucket in django, here a brief explanation: I am passing dynamic data (image) from django to HTML. When running the app locally it shows the image, but when using Heroku/AWS Bucket it doesn't. This only happens when passing dynamic data to CSS format inside an HTML file, but other dynamic data (also image) works well. Another thing to include is that the image gets properly saved into the AWS bucket. It can be accessed from the bucket. Here is my index.html: ''' {% load static %} {% static "img" as baseUrl %} . . . <style> .Modern-Slider .item-1 .image { background-image: url('{{img.0.url}}'); } .Modern-Slider .item-2 .image { background-image: url('{{img.1.url}}'); } </style> . . . <body> <div class="slider"> <div class="Modern-Slider content-section" id="top"> {% for info_home in information_home %} <div class="item item-{{forloop.counter}}"> <div class="img-fill"> <div class="image"></div> <div class="info"> <div> <div class="white-button button"> <a href="{{info_home.home_destination}}">{{info_home.button_home}}</a> </div> </div> </div> </div> </div> {% endfor %} </div> </div> </body> ''' Here is my views.py : ''' def index(request): information_home = Info_Home.objects.all() lista_imagenes = [] for info in information_home: imagen = info.image_home lista_imagenes.append(imagen) return render(request, "index.html", {'information_home': information_home, 'img': lista_imagenes}) ''' -
why my django-ckeditor Link tab does not have Target option?
I am using django-ckeditor=6.0.0 for my django app. I used earlier version of django-ckeditor before, and I remembered that the Link tab has Target option, so you can choose whether to open a new tab/ open a new window/ or _blank, etc. I could not figure out why in current version, there is not Target option. I am using default toolbar. -
Django Signal Loop
Can someone help me resolving this problem. I've created an django-app with two models. One model is an Wallet model and other is Transaction model. Every transaction is conneted to a wallet with models.ForeignKey. I've also created two signals, one is for updating cryptocurrency balance (eg. BTC, ETH) in Wallet when transaction is made and the other signal i want to update Total_Balance (which is all other balances converted to USD). And here I have a problem because my signal is POST_SAVE and in it I have a save() method which causes infinity loop. I think if I would do a whole thing in my first signal it would work but in future i want to add new model which also will be connected to Wallet and it would pop-up my total_balance, therefor i would need same logic in third signal and I would end up with same code in two signals. I know my description is a little messy. Here is some code to help understand it. My Models: class Wallet(models.Model): name = models.CharField(max_length=50) total_balance = models.IntegerField(blank=True) btc_balance = models.DecimalField(max_digits=15, decimal_places=8) xrp_balance = models.DecimalField(max_digits=15, decimal_places=8) eth_balance = models.DecimalField(max_digits=15, decimal_places=8) class Transaction(models.Model): wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE) currency_paid = models.CharField(choices=CURRENCY, max_length=3) … -
Sharing an image to LinkedIn using Django 2.2
To share an image on LinkedIn you need to follow the instructions at https://docs.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context What I don't understand is how to make this curl request "curl -i --upload-file /Users/peter/Desktop/superneatimage.png --header "Authorization: Bearer redacted" 'https://api.linkedin.com/mediaUpload/C5522AQGTYER3k3ByHQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJbrN86Zm265gAAAWemyz2pxPSgONtBiZdchrgG872QltnfYjnMdb2j3A&app=1953784&sync=0&v=beta&ut=2H-IhpbfXrRow1'". Using Django's requests library. So Basically what I need help with is converting the curl request above into a regular HTTP call such as get, post, put, etc. To Whom it may concern, Jordan -
Django session_key get new value for each request
I create session like this: request.session['user_id'] = 111 if not req.session.session_key: req.session.save() Then in another view, I print: print(request.session.get('user_id')) print(request.session.session_key) session data (user_id) showing correctly, and session_key looks like: eyJ1c2VyX2lkIjoiMTAwIiwidXNlcl9uaWNrIjoibmljazEifT:1khfFA:rwQnzaXk4HQ9XdKPuL1fhRPuLbl8w-TUNR3RMPsNQQr though, for every request, (page refresh) session_key prints different value (BTW part before first ":" stays same). Question: is this behaviour normal? does not session_key must to be same, while session is "alive" ? -
add fields in Django auth Group
I edit the django admin form to show users list with the permission to create group of users to to som actions I want to add a new field without creation a new modal is it possible? forms.py class GroupAdminForm(forms.ModelForm): class Meta: model = Group exclude = [] users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple('users', False) ) def __init__(self, *args, **kwargs): super(GroupAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['users'].initial = self.instance.user_set.all() def save_m2m(self): self.instance.user_set.set(self.cleaned_data['users']) def save(self, *args, **kwargs): instance = super(GroupAdminForm, self).save() self.save_m2m() return instance admin.py admin.site.unregister(Group) class GroupAdmin(admin.ModelAdmin): form = GroupAdminForm filter_horizontal = ['permissions'] admin.site.register(Group, GroupAdmin) the filed I want to add I have triyed thois but it is not working: models.py class MyGroup(Group): notes = models.TextField(blank=True) def __unicode__(self): return self.name when I add this model I have edit the model in the GroupAdminForm to use this model but no sucess ? -
How to filter foreign key on datatables with server side processing?
How do i filter Foreign keys on a datatable with server side processing? I'm using a datatable to display 3.500 entries from my sql server within Django/Ajax/Rest-Framework. The table is working as intended when searching columns within the given table, but: Foreign key filtering appears not to be working. error i get when searching: raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'bib_tipo_nome' into field. Choices are: autor, cadastro_id, datacriado, emailautor, referencia, tema, tema_id, tipo, tipo_id Is there a solution for this? Do i need client-sided processing? -
Unable to download zip file from server with %20 in it's name but when I copy the link from html it works fine
I am trying to figure out the exact issue but with little success. I have rendered a template containing the link for a file in media directory of my server. The filename has a space in it in the media directory and in the database this space has been replaced with %20 in the filename. I am fetching the filename from the database and passing it to the HTML template with the media url. When I check the rendered html, it has %20 and if I copy the link from the HTML and try to download the file, it is getting downloaded. e.g. The file in the HTML looks like : http://abc.domain.com/media/Demo%20Report.xlsx The file in the media directory is "Demo Report.xlsx" -
DJANGO Static Image deletion
I am experiencing an issue with images saved in the static/images directory in Django. My website was rendering images appropriately, by referencing the name of the image e.g., Image_1. However, once I've tried to delete this image and include a new one in the static/images directory with the same name, Image_1, the website keeps rendering the old image. New images added in the same directory with new names are rendered without issues. Since then I have specified all STATIC_ROOT, MEDIA and MEDIA_ROOT routes in settings.py, I have run manage.py collectstatic and I have checked the images stored in these directories. The "old" version of Image_1 is not there anymore, but the new one is, and the website still renders the "old" version of it. Does anybody have an explanation for this, and how to fix it? Thanks in advance! -
ModuleNotFoundError: No module named 'django_countries'
I have a docker django project and I want to use django-countries. This is my requirements.txt .... django-countries django-cities This is the INSTALLED_APPS in settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_countries', ... (others) ] When I run docker-up, I receive the below error: docker_name | Traceback (most recent call last): docker_name | File "/app/manage.py", line 22, in <module> docker_name | main() docker_name | File "/app/manage.py", line 18, in main docker_name | execute_from_command_line(sys.argv) docker_name | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line docker_name | utility.execute() docker_name | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute docker_name | django.setup() docker_name | File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup docker_name | apps.populate(settings.INSTALLED_APPS) docker_name | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate docker_name | app_config = AppConfig.create(entry) docker_name | File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 90, in create docker_name | module = import_module(entry) docker_name | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module docker_name | return _bootstrap._gcd_import(name[level:], package, level) docker_name | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import docker_name | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load docker_name | File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked docker_name | ModuleNotFoundError: No module named 'django_countries' Any ideas?