Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django docker logging
I am running docker on my Mac. I am having an issue with my views.py and I am trying to print out to the Mac docker desktop some messages to try to debug my code. I have followed Django and docker: outputting information to console and it doesn't seem to work for me. The only thing that gets printed out to the docker desktop logs is just errors when they occur, Normally all I get is just the 200 ok from the http request. I have used the print statement and the info statement and neither of them print out. ------------------------------------ setttings.py ------------------------------------ from pathlib import Path import os import logging.config import json # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #Logging Config LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '[DJANGO] %(levelname)s %(asctime)s %(module)s ' '%(name)s.%(funcName)s:%(lineno)s: %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'default', } }, 'loggers': { '*': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, } }, } ------------------------------------ views.py ------------------------------------ from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse_lazy from .login_model import LoginForm import logging logger = logging.getLogger(__name__) # … -
using primarykeyrelated for post and string for get call in django rest framework
I have a model in which some fields are a foreign key to another model. Hence while creating the object of that model I have to use primary key but while calling get api I need to show those fields as stringrelated field. How to achieve that?? My model: class Example(models.Model): tour = models.ForeignKey( Package, on_delete=models.CASCADE, null=True, related_name="example" ) site = models.ForeignKey( Destination, on_delete=models.CASCADE, null= True, related_name= "example", ) location = models.CharField(blank=True) /...........other fields........../ My serializer: class ExampleSerializer(serializers.ModelSerializer): # tour = serializers.StringRelatedField() # site = serializers.StringRelatedField() class Meta: model = OnlineClass fields = ['id','tour','site','other fields.....'] def to_representation(self, instance): data = super(ExampleSerializer, self).to_representation(instance) return data Here while creating the example object, I need to pass tour and site as ids but while calling list method I need to show both fields as string related fields. As I define them as stringrelated field as above (later commented out) , I can create the object but those fields will be set as null. I don't want to make another serializer. How to achieve this?? -
Django validate_unique error while updating from admin
I have created a validate_unique based in two fields (asset and portfolio), it work well when i try to create a new object that already exists, i get the correct message. But i get the same error message if i try to update an existing object. Should i change something to make the update work? class PortfolioAsset(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) asset = models.ForeignKey(Asset, on_delete=models.CASCADE) shares_amount = models.FloatField() share_average_price_brl = models.FloatField() total_cost_brl = models.FloatField(editable=False) total_today_brl = models.FloatField(editable=False) def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) if self.__class__.objects.\ filter(portfolio=self.portfolio, asset=self.asset).\ exists(): raise ValidationError( message='This asset already exists in this portfolio.', code='unique_together', ) def save(self, *args, **kwargs): self.total_cost_brl = round(self.shares_amount * self.share_average_price_brl, 2) self.total_today_brl = round(self.shares_amount * self.asset.price, 2) super(PortfolioAsset, self).save(*args, **kwargs) -
How to authenticate user using custom model in Django?
I am working on a Django project. The project has three pages Home, login, registration. Home page's nav bar has three buttons Home, login and registration. I have created a custom model I don't want to admin model. I already did the login part but now I want is after login the home nav login and register button disappear and a new button/text appear Hello user or whatever the name whoever is logged in. Is there any way to do it I know we can do it with the admin User model but I don't know how to do it with a custom model? -
Django Admin Access Parent Object Value From Tabular Inline
I am attempting to setup an admin TabularInline and carry the value of the GenerationMode selection to the ModeVersion mode field. models.py: class GenerationMode(models.Model): mode=models.CharField(max_length=35, choices=GENERATION_CHOICES, default='None', blank=False, null=False) disabled=models.CharField(max_length=1, choices=DISABLED_CHOICES, default='N', blank=False, null=False) active=models.CharField(max_length=1, choices=ACTIVE_CHOICES, default='Y', blank=False, null=False) created_when=models.DateTimeField(auto_now_add=True) modified_when=models.DateTimeField(auto_now=True) class Meta: db_table = 'main_GenerationModes' def __str__(self): return self.mode def __unicode__(self): return self.mode class ModeVersion(models.Model): mode=models.CharField(max_length=35, choices=GENERATION_CHOICES, default='None', blank=False, null=False) version=models.DecimalField(max_digits=5, decimal_places=2, blank=False, null=False) active=models.CharField(max_length=1, choices=ACTIVE_CHOICES, default='Y', blank=False, null=False) created_when=models.DateTimeField(auto_now_add=True) modified_when=models.DateTimeField(auto_now=True) FK_mode=models.ForeignKey(GenerationMode, on_delete=models.SET_NULL, blank=True, null=True) class Meta: db_table = 'main_ModeVersions' def __str__(self): return self.mode + '_' + self.version def __unicode__(self): return self.mode + '_' + self.version admin.py: from .models import GenerationMode from .models import ModeVersion class GenerationModeVersionInline(admin.TabularInline): model = ModeVersion min_num = 1 extra = 0 class GenerationModeAdmin(admin.ModelAdmin): inlines = [GenerationModeVersionInline] model = GenerationMode list_display = ['mode', 'disabled', 'active'] admin.site.register(GenerationMode, GenerationModeAdmin) I've looked here, as well as, read the docs. I am confused on how to achieve what I am trying to do. Is there a recommended approach to solve this? -
SMTPAuthenticationError at /reset_password/ (535, b'5.7.8 Username and Password not accepted in django
When i use any email from these in reset password it is giving me the error SMTPAuthenticationError at /reset_password/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o10sm21802621wri.19 - gsmtp') But when i use any email which is not present in these emails i am not getting any mail what should i do? My EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are right i manually checked it. -
Sharing data in local thread python in different threads
I have stored request_id in local thread python, this thread creates three more threads which won't have access to request_id. How can I share or send request_id info from one thread local to another. -
Django aws getting mysql OperationalError
I was using localhost mysql database. After integrating aws rds mysql I am getting this error django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') Here is my mysql configuration for aws rds: settings.py DATABASES = { 'default': { 'ENGINE': config('AWS_MYSQL_ENGINE'), 'NAME': config('AWS_MYSQL_DB_NAME'), 'USER': config('AWS_MYSQL_DB_USER'), 'PASSWORD': config('AWS_MYSQL_DB_PASSWORD'), 'HOST': config('AWS_MYSQL_DB_HOST'), 'PORT':config('AWS_MYSQL_DB_PORT'), } } my local host mysql is working fine. I am not understanding why I am getting this error after move to aws rds. I am straggling from several hours for solve this problems. I tried to run migrate after delete all of my migrations files but didn't work. here is full error log: site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') -
How can I check if a boolean from a different model is true for a user of a team?
I have the following model I want to use to add rights to users that are part of a team: class Rights(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Teams, on_delete=models.CASCADE) read = models.BooleanField(default=True) write = models.BooleanField(default=False) edit = models.BooleanField(default=False) Some Users need to be able to make new entries. Some are not allowed to have that possibility. So, if some user sends a request, how can I check if one or more of these boolean values are true or false for this specific user? -
How to access auth_user_group table by ID
How can I directly specify the ID column of auth_user_group table in queries/DML? I am referring to auth_user_group.id, not auth_group.id nor auth_user_group.group_id. For example, I want to directly issue DML like: delete from auth_user_group where auth_user_group.id = 1 select id, user_id, group_id from auth_user_group where auth_user_group.id = 1; I am not interested in the following workaround which avoids auth_user_group by requiring knowledge of the group name, instead of the auth_user_group.id, and results in two queries instead of 1: group = Groups.get(name='foo') user.groups.remove(group) If you wanted to directly query a junction/M:N table in Django, normally you would create a "through Model" and can then query it directly. However in this case, the django.contrib.auth.models definition do not use a through model. -
in status field should be approved once boolean field is true how to write syntax
mode.py this image of model file in this once Boolean is true the status field value should be approved how to write syntax -
Apply widget dynamically depending on field value
In a Django project, I have a form with a use_format checkbox (unchecked by default) and a post CharField. Because I want to be able to add extra features to the post text field, like text formatting, I have imported a RichTextEditor widget to do so. The thing here is that I only want to use the RichTextEditor widget in post if use_format is checked. class ArticleForm(ModelForm): def __init__(self, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) if not self.instance.use_format: self.fields['post'] = forms.CharField(widget=forms.Textarea) class Meta: model = Article fields = '__all__' widgets = { 'post': RichTextEditor(options={...}), } So far, what I've been doing when I want to create an article with formatting is to create the article with use_format checked. Save. Then edit the article and there I have the post with the RichTextEditor. I would like to have the post changing automatically between CharField or RichTextEditor as I check or uncheck the use_format checkbox. First, is this possible? What I've been trying: I've added a custom script on my ModelAdmin to detect changes to the use_format value class ArticleAdmin(admin.ModelAdmin): form = ArticleForm class Media: js = ('js/toggleUseFormat.js') toggleUseFormat.js: if (!$) { $ = django.jQuery; } $(document).ready(function () { $("#id_use_format").change(function () { // … -
html file in django project not working properly
I am new to django, i created two folder static and templates in django project, i created a html file in templates folder index.html, but VS code is not working properly here, i.e not showing emmet and html tag suggestion as VS code suggest normally, while on other files of other project not belong to django , VS code working properly , please anyone know about it ? -
Django No Reverse Match Error - Nothing is working
When rendering a new page, the html form action on that new page is stopping the page from being rendered... even though it has nothing to do with the page itself being rendered (if I remove that one line of HTML code, the page loads just fine). I've been working on solving this problem for over 3 days, tried hundreds of possible solutions, nothing works. Please help This is the error: Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P[^/]+)/(?P<gallery_id>[0-9]+)\Z'] This is the line of code being highlighted as cause for error (form action): <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'> Views.py: @login_required def newgallery(request, username): if request.method == 'GET': form = NewGalleryForm context = { 'form': form, 'username': username, } return render(request, 'galleries/newgallery.html', context) def editgallery(request, username): if request.method == "POST": form = NewGalleryForm(request.POST) if form.is_valid(): new_gallery = form.save(commit = False) ## connect the new gallery with the user (foreign key) new_gallery.user = request.user new_gallery.save() url = "https://api.opensea.io/api/v1/assets?order_direction=desc&offset=0&limit=5" params={'owner': new_gallery.wallett_address} headers = { "Accept": "application/json", "X-API-KEY": "" } response = requests.request("GET", url, headers=headers, params=params) response = response.json()["assets"] list_of_nfts = [] for dictionary in response: token_id = dictionary["token_id"] token_address = … -
What Is Can Order In Django Formsets Actually For?
I've spent a fair amount of time the last day or so exploring the can order field with Django Formsets but I can't for the life of me actually figure out what it's for. Apparently it doesn't update the database...and it does put an order number field with the form....but beyond that what is it for? I can't find any useful documentation on how to actually use this field. Do I have to write Javascript in order to get this field to do anything actually meaningful? I get the delete option...and you have to add code in to delete the record...So I guess I'm to take it the same is required for the can_order field? Sorry if this is a silly question but I've spent more time trying to figure this out than what would be reasonable by now. -
CSP error for bootstrap image in navbar hamburger
I just added content security policy to my Django site. I have everything working correctly except these two errors for images that I had no idea what they were I spent a bunch of time trying to figure it out until I noticed that the icon on the bootstrap hamburger menu was gone In the CSS I found this telling me that this must be the image in the navbar causing this error. I found a few workarounds online but they presented security vulnerabilities and i would like to do it properly How can I go about solving this issue. CSP CSP_STYLE_SRC = ("'self'", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css", ... ) CSP_SCRIPT_SRC = ("'self'", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/", ... ) -
MY 'image' attribute has no file associated with it
With my reading of many answers to questions similar to mine, all of those answers did not find a solution to my problem.. so I will present them so that I may find a solution that fits my problem: my View file: enter image description here my Template File: enter image description here my Admin file: enter image description here The Error: enter image description here enter image description here I tried every solution with no hope. -
Server down when uploading a file in a Django App on DigitalOcean
I have developed an application where a user can upload a zip file, the zip file gets uncompressed and stored in a newly created folder using os.mkdir() On the local machine the process works perfectly, but when uploaded to digitalocean in production mode (gunicorn + nginx), the upload process results in a "Site cannot be reached" browser error, not even an HTTP error where we can trace the problem. Here are all the elements that you might need to see: views.py: @user_passes_test(lambda u: u.is_staff or u.is_superuser) def createCategory(request): if request.method == "POST": name = request.POST.get("name_kw") lang = request.POST.get("lang_kw") moduleid = request.POST.get("module_kw") zip = request.FILES.get("zip_kw") category = Category() category.name = name category.lang = lang category.module = Module.objects.get(id=moduleid) category.zip = zip category.created_by = request.user try: if zip.name.endswith(".zip"): rtn = publish_doc(category.name, zip) if rtn == "No index file found": messages.error( request, "Pas de fichier index.html détecté. Assuez-vous qu'un fichier index.html est présent dans votre fichier ZIP", ) return redirect("categoryList") else: category.root = rtn category.save() messages.success(request, "Catégorie créée avec succès") print("categorie et zip créées") return redirect("categoryList") else: messages.error( request, "Seuls les fichiers .ZIP sont acceptés", ) return redirect("categoryList") except IntegrityError: print("erreuuuuuuuur") messages.error( request, "Une erreur s'est produite. Veuillez réessayer plutard, ou contacter notre équipe … -
Mocking a request object to pass to ViewSet create() method
I'm learning unittest and unittest.mock, and struggling with the concepts and implementations primarily with mock. For context, what I'm playing with is a Django / DRF API and Redis. I'm trying to write tests which require mocking the Redis calls. Here is the test I'm working on: # tests.py import unittest from unittest.mock import patch from core.views import KeysViewSet class KeysViewSetTestCase(unittest.TestCase): def setUp(self): self.json_object = {'key': 'hello', 'value': 'world'} self.view = KeysViewSet() def test_create(self): with patch('core.views.RedisUtil.create') as mocked_create: mocked_create.return_value.data = True created = self.view.create(self.json_object) The views.py: # viefws.py # Third party imports from rest_framework import status, viewsets from rest_framework.response import Response # Croner imports from .serializers import KeysSerializer # Import Redis from .utils import RedisUtil class KeysViewSet(viewsets.ViewSet): """ METHOD URI DESCRIPTION GET /api/keys/<:key>/ Returns specific value from key POST /api/keys/ Creates a new key/value DELETE /api/keys/<:key>/ Deletes a specific key """ def __init__(self, *args, **kwargs): """ Instantiate the RedisUtil object. """ self.redis_util = RedisUtil() def create(self, request): """ Creates a key/pair in the Redis store. """ print(request) # Serialize the request body serializer = KeysSerializer(data=request.data) # If valid, create the key/value in Redis; if not send error message if serializer.is_valid(): return Response(self.redis_util.create(serializer.data)) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And the utils.py that … -
How to create a button that submit a form and download file in Django
How to create a button that submit a form and download file in Django I know use this code and download file <html> <title>Download File</title> </head> <body> <enter> <h1>Download File using Django</h1> <a href="{% url 'download_pdf_file' filename='CF.pdf' %}">Download PDF</a> </center> </body> </html> I also know how to create a button that submit some data <input type="submit" value='submit' class="btn btn-primary btn-sm"> But how could I combine them into in button The reason why I need to do that is I want to update the exist file and download it in the same page. -
How can I add a voice recorder in webpage from user and save it in filefield at django model?
I am studying for a long on a voice recorder from the webpage and I need that to send this data to the backend. I don't know how to do that. If someone can guide me that would be a great help. Thanks in advance. -
Django AttributeError object has no attribute 'upper'
I am implementing an API for an image labelling app. I have customised a create() method for Tagging. A Tagging contains a tag, which is an object containing a name and a language. To make tags easier to compare to each other, I have to save all tags either in upper or lower case. serializers.py def create(self, validated_data): """Create and return a new tagging""" user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user score = 0 tag_data = validated_data.pop('tag', None) if tag_data: tag = Tag.objects.get_or_create(**tag_data)[0] validated_data['tag'] = tag tagging = Tagging( user=user, gameround=validated_data.get("gameround"), resource=validated_data.get("resource"), tag=validated_data.get("tag"), created=datetime.now(), score=score, origin="" ) tagging.save() return tagging I have tried both this tag=validated_data.get("tag").upper() and this: tag=validated_data.get("tag").lower() and I get an AttributeError 'Tag' object has no attribute 'upper' or 'Tag' object has no attribute 'lower'. I want for this tag: { "gameround_id": 65, "resource_id": 11601, "tag": { "name": "TagToTestNow", "language": "de" } } to be saved something like "TAGTOTESTNOW" or "tagtotestnow" to make Tag comparison easier. How can I achieve this? -
Recursive function to calculate the children of a parent
I have a set of data that looks like this: Person1 is the parent of Person2 Person2 is the parent of Person3 and Person4 Person3 is the parent of Person1 If I try to calculate the whole tree for Person1, the max recurssion will be exceeded and the program will terminate in an error. The expected result would be Person1 -> [Person2, Person3, Person4], so basically in the case the the calculation has to be repeated for an element that is already in the list, this has to be ignored. Do you have an idea, how could I solve this problem? My function looks something like this: def compute_children(self): children = [] children.extend(self.child) for child in children: temp = child.compute_children() if 0 < len(temp): children.extend(temp) return children -
How to let the user select multiple choices while filtering data using django-filter?
I have a model: class Radiations(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None) date=models.DateField(default=datetime.date.today) done_fractions=models.IntegerField(default=0) base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None) remarks=models.TextField(max_length=500, blank=True, default=None) radiations_date=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) Its filter looks like this: class RadiationsFilters(django_filters.FilterSet): patient__name=django_filters.CharFilter(lookup_expr='icontains', label='Name') from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='From - Date ', lookup_expr='gte') to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='To - Date ', lookup_expr='lte') Now, I want the user to be able to select multiple patients which are saved in the database, how can I bring them into my filter code? Someone please help. Thanks in advance. -
JsonPickle decodes a function into None value
I am using jsonpickle in a django project to store lists, sets or dicts of custom objects in a models.JSONField. I'm running tests to check my code: everything is fine, but goes wrong if I just try to .reload_from_db() an instance containing this kind of JSONField in it. The problem comes from json decoding. After digging this, I found that this string: { "py/set": [ { "py/function": "Main.files.Effects.AddEffectToAttacks.apply.<locals>.remove_effect.<locals>.wrapper" } ] } becomes: {None} let's say: s = '{\n "py/set": [\n {\n "py/function": "Main.files.Effects.AddEffectToAttacks.apply.<locals>.remove_effect.<locals>.wrapper"\n }\n ]\n}' jsonpickle.decode(s) will return {None} when it is obviously not None but a function: Main.files.Effects.AddEffectToAttacks.apply.<locals>.remove_effect.<locals>.wrapper Does someone have an explanation and a solution for this please?