Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have Django raise ValidationError as Popup?
I am using a custom clean() function on one of my forms for a conditional field requirement. I am able to raise the validation error on my template as a part of the DOM using {{ form.non_field_errors }}. I would like to have the validation error come up as a popup like the default errors do, but do not know how. Here is the custom clean() function: class ReportForm(forms.Form): def clean(self): cleaned_data = super().clean() class_type = cleaned_data.get("class_type") class_other = cleaned_data.get("class_other") if class_type == "Other": if not class_other: msg = "Please fill out this field." raise ValidationError(msg) I don't know what to put in views or the template to have it show as a popup - I don't currently have anything special there. Is it possible with Django, or do I need to use javascript? -
Django Model @property duplicates queries
Django model properties is useful to access in run time, however this does not come without cost. Below property cause huge duplicate queries due to database hit with each query (product). @property def total_stock(self): """ SKU total stock """ total = SKU.objects.filter( product=self ).values_list("stock").aggregate(Sum(F("stock"))).get("stock__sum") or 0 return total Any thought how to use django model @property in efficient way? -
Fabric keep asking for user password, although key_filename is set
I am using fabfile for django deployment. I am connecting to my deployment servers through bastin host (using env.gateway option in fabfile, env.gateway=bastin_IP) and then running required commands. Following options are set in fabfile, added for reference. env.gateway = 'user@xx.xx.xx.1' #bastin_IP env.key_filename = ['path/to/pem/file'] env.user = 'user' env.port = 22 Now whenever I run command, it always prompt for password of user, message shown like this. [xx.xx.xx.002] Login password for 'user': Note: here IP shown before message is the IP of my deployment/prod server. What I am assuming (after seeing above message) is that connection is being made with bastin successfully, but it is not connecting with deployment/prod server. Although whenever I try to connect via putty (on windows), I can login to bastin host (using openssh private key) then from bastin to any other deployment/prod server without password. Please let me know, what is the actual issue and how to resolve that. What I am doing wrong? Any help is appreciated. -
Call Microsoft Authentication in a Custom Login Form
So I'm creating a custom login form and really would like to include the option so that users can login in via office365 account. To do this I have used the django_microsoft_auth functionality. When going to admin it is working perfectly, however really would like to know how should I use it in a custom form. I did not find any documentation how this can be done and really would like some feedback on this. So in my login there will be a button then when pressed it will redirect to Microsoft authentication site and when completed it will redirect to the homepage. What do I need to include the the href in my template? and do I need to add something in the views.py or there is no need? Thanks -
autoreload.restart_with_reloader - how to reboot with --noreload key? [django]
how to restart the server with the --noreload key and back? from django.utils import autoreload autoreload.restart_with_reloader(--noreload) #for example #some code autoreload.restart_with_reloader() can i restart the server with the --noreload key? and then back with no key? if manually, but it is necessary in the code dynamically python manage.py runserver ctrl+c python manage.py runserver --noreload ctrl+c python manage.py runserver -
Get a string variable from views to urls in Django
I am a beginner at python and especially Django, I am trying to solve a problem where when a user searches, if that search is valid, i want to get that search = var_X, in my URL like: "www.website.com/search/var_X" or something like, "www.website.com/search/<df.item>" -Views.py- def views_search(request): temp_dict = {} if request.method == 'POST': var_X = request.POST['var_X'] try: df = wsc.Summary(temp_dict, var_X) except Exception as e: df = "ERROR" return render(request,'search.html', {'df' : df}) else: return render(request,'home.html', {'var_X' : "Not Found"}) -- Urls -- from django.urls import path from . import views from requests import * urlpatterns = [ path('search/<var_X>', views.views_search, name="url-search"), ] -- HTML -- <form action="{% url 'url-search' var_X %}"class="d-flex" method="POST"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Enter String" aria-label="Search" name="var_X"> <button class="btn btn-outline-secondary" type="submit">Search</button> </form> -
Convertir lista a formato fecha en Django [closed]
estoy intentando convertir esta lista: `[datetime.date(2021, 1, 19), datetime.date(2021, 1, 20), datetime.date(2021, 1, 22)]` a un formato date() que se mire de la siguiente manera: [2021-01-19,2021-01-20, 2021-01-22...] estoy usando Django y no encuentro la manera de hacerlo convertir la lista a un formato date. -
django not picking up migration where managed = False
I have a simple web-app I'm trying to create to visualise some carbon data (to teach myself Django!) As my data model is a little complex I use the managed=False and import a view from my postgres database where I wrangle my data. When I first ran the migration I noticed I left in a field that I didn't have in my view, so naturally I changed it. Now when I run makemigrations for my app called carbon it says there are no changes. What is the correct way to remedy this? additionally, for some reason when I try to run an orm query to pull in some data it expected me to have an id field in my view, can someone explain this, if possible? models.py class CarbonViewHour(models.Model): daily_hour = models.CharField(max_length=50) reading = models.FloatField() #date = models.DateField() This was removed class Meta: managed = False db_table = 'carbon_v_hourly_meter_readings' def __str__(self) -> str: return f"{self.meter}-{self.reading}-{self.date}-{self.daily_time}" the change I made was to remove a field from CarbonTimeView date = models.DateField() views.py class CarbonTimeView(TemplateView): template_name = 'carbon/chart.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['qsm'] = CarbonViewMinute.objects.all().order_by('date') context['qsh'] = CarbonViewHour.objects.all() context['title'] = 'Daily Carbon Data' return context SQL View. DROP VIEW IF EXISTS … -
django storages AWS S3 SigVer4: SignatureDoesNotMatch
My configuration (very basic): settings.py AWS_S3_REGION_NAME = 'eu-west-3' AWS_S3_FILE_OVERWRITE = False # S3_USE_SIGV4 = True # if used, nothing changes # AWS_S3_SIGNATURE_VERSION = "s3v4" # if used, nothing changes AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "xxx" AWS_STORAGE_BUCKET_NAME = 'xxx' # AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' # if used, no pre-signed urls AWS_DEFAULT_ACL = 'private' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'xxx' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' INSTALLED_APPS = [ ..., 'storages' ] models.py class ProcessStep(models.Model): icon = models.FileField(upload_to="photos/process_icons/") What I get: Pre-signed url is generated (both in icon.url and automatically on admin page) Pre-signed url response status code = 403 (Forbidden) If opened, SignatureDoesNotMatch error. With text: The request signature we calculated does not match the signature you provided. Check your key and signing method. Tried: changing access keys (both root and IAM) changing bucket region creating separate storage object for icon field (same error SignatureDoesNotMatch) changing django-storages package version (currently using the latest 1.11.1) Opinion: boto3 client generate_presigned_url returns url with invalid signature Questions: What should I do? Why do I get the error? -
dictionaries of objects as fields in models.py
I want to create an option of inventory and skills list and for that I wrote those classes: class Drop(models.Model): name = models.CharField(max_length=200) description=models.CharField(max_length=2000) class Skill(models.Model): name = models.CharField(max_length=200) description=models.CharField(max_length=2000) manaCost=models.IntegerField() then I want the player to have them as dictionaries, the key will be "name" and the value all the object. here is the code for character modle: class Character(models.Model): raceList = Race.objects.all() roleList = Role.objects.all() user=models.ForeignKey(User,related_name='characters',on_delete=models.CASCADE) name=models.CharField(max_length=200) description=models.TextField() race = models.ForeignKey(choices = raceList,on_delete=models.CASCADE) role = models.ForeignKey(choices = roleList,on_delete=models.CASCADE) attack = race.attack+role.attack deffence = race.deffence+role.deffence intelligence = race.intelligence+role.intelligence agility = race.agility+role.agility wisdom = race.wisdom+role.wisdom charisma = race.charisma+role.charisma i want to add the fields "inventory" and "skills" -
Admin static files not loading in production for Django site
Django==2.1.1 I'm using Amazon ElasticBeanstalk I've ran collectstatic and the files are properly stored in my /Assets folder My main website images all load perfectly fine when I deploy. But the admin page does not load any statics, just get 404 errors. I already have 'django.contrib.staticfiles' installed under settings. here is a portion of my settings.py; STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = os.path.join(BASE_DIR,'assets') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' Thank you. -
How to seperate wagtail image's tags from page's tags?
Suppose we have a wagtail page defined like this: class PostTag(TaggedItemBase): content_object = ParentalKey( 'PostPage', related_name='tagged_items', on_delete=models.CASCADE ) class PostPage(Page): ... tags = ClusterTaggableManager(through=PostTag, blank=True) ... content_panels = Page.content_panels + [ ... FieldPanel('tags') ] When I want to edit tags field on wagtail admin, it suggests not only pages' tags but also images' tags. I want to some how remove images' tags from suggestions. In my project, pages' tags are not related to image's tags. To understand the scenario, look at these two pictures: The first one shows adding river as a tag into one of the images. The second one shows the tags field on PostPage. I don't want to see the river tag as a suggestion on page's tags: Is that possible? If not, Is it possible to remove tags field from wagtail image model? -
Django send email to user that is in the same group that login user is in
I have an app that sends the email to the director of the respective department when the manager of that particular department approved a leave. However, for some reason, when the manager approved the leave. The app also sends the email to the directors who are from different departments instead of one director who is in the same group as the manager. I want to send an email to only the director that is in the same group as the manager. For instance, I have three groups. finance, accounts, ICT. if the manager that approves the leave is in the finance department then when the finance manager approves the leave an email should be processed and send only to the director of finance. Here is the function that send the email to the director @login_required(login_url='home') def Manager_send_sick_leave_email_to_Director(request, staff_id): query_set = Group.objects.filter(user=request.user) in_group = User.objects.filter(groups__name="Director").filter(groups__name=query_set[0]).filter( groups__name="authorizer") for a in in_group: to_send = [a.email] send_mail("Approved Sick Leave", "The unit Manager" + " " + staff_id.Authorized_by_Manager + " " + "have " + staff_id.Manager_Authorization_Status + " " + staff_id.user.first_name + "'s" + " " + "Sick leave and we have forwarded it to you for " "final " "authorization\n" + "Please login to … -
Django inspectdb unable to inspect table - relation doesn't exist error
So, what I'm trying to achieve is to map the tables I have in my postgres database to django models. I've tried using inspectdb, but it keeps throwing errors and I'm out of ideas on how to fix it. Here is the code I ran: python3 manage.py inspectdb account And the output it gives me is: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'account' # The error was: relation "account" does not exist LINE 1: SELECT * FROM "account" LIMIT 1 What I think is going on here is that for some reason the inspectdb is wrapping the table name with double quote which is incorrect to psql syntax and this is … -
How to customize Django modle's field.value_to_string(self) for datetime field
Let's say I have a model class Job(Model): created_on = DateTimeField(_("Created On"), auto_now=True, editable=False) name = CharField(_("Name"), max_length=300, blank=False) Now I am trying to aggregate all fields with their verbose name and value to display it in a template. My aggregating function: def get_fields(self): result = [] for field in Job._meta.fields: result.append((field.name, field.verbose_name, field.value_to_string(self))) This gives me the values as string properly, however for a datetime field, I end up with a dumb unformatted string like 2021-02-13T22:39:47.561045+00:00 I really don't want to check and modify the value in some way by specifically checking for the particular field as that is the whole point of my get_field function I feel any of the following should work fine for me: Somehow provide the default format to use when calling value_to_string() Get a proper dateTime object instead, in which case the value should show up fine on the template Get field type and then instead of calling value_to_string() I manually convert the string to this type (This seems feasible from what I see but feels too hacky of a solution) -
What will happen if a Django request gets to long?
I am tryying to figure out a microservices architecture for my Django Restfull webapp.This Engineering app will envolve with heavy mechanical and geometrical calculations in some places. Due to the Django's slow (actually python's) calculation nature I will make main app with Django(becaue of its killer nice features) and also I want to design microservices as side functions on C# asp.net(due to its calculation power).This will allow me through heavy calculations on it so i can keep Django main app just like a bridge. So my questions; When Django main app sends a request to microservice What will happen if a calculation gets too long on micromicroservice? Lets say 10sec. , will my whole app be frozen along the 10sec.? I want to use async fuctions on ASP.NET, will it negativelly effect the sync Django main app? -
In Django, only the first form is evaluated in writing order. Why?
I have created some forms using the Django form model class But the strange problem I have is that the first form is always evaluated in writing order, even when another form is sent, that form is called I searched a lot but did not find a solution Form values are sent to the server in Ajax It works properly when I do not create the form from the Django model form class and write a normal HTML form without using the class views.py Ajax Code forms.py Html Models The form_default_user form is always validated even when it has not been submitted and another form is sending values enter image description hereenter image description here -
Select2MultipleWidget in formset
I'm trying to get a formset with Select2MultipleWidget widgets but am not successful. Using Django 2.2 LTS. class MealUpdateForm(forms.ModelForm): class Meta: model = Meal fields = ('noon', 'noon_options', 'evening', 'comments', ) widgets = { 'noon_options': Select2MultipleWidget, } When I render the above through a test form for a single item, everything is working fine: I get a Select2MultipleWidget for the noon_options field. Whenever I add the form to a modelformset_factory though, I'm getting Django's default SelectMultiple widget, which is not what I want. MealFormSet = modelformset_factory(Meal, extra=0, fields=('noon', 'noon_options', 'evening', 'comments', ), form=MealUpdateForm, ) I'm rendering the formset in my template pretty straightforward as: {% for form in formset.forms %} <tr> <td> {{ form.id }} </td> <td> {{ form.noon }} </td> <td> {{ form.noon_options }} </td> <td> {{ form.evening }} </td> <td> {{ form.comments }} </td> </tr> {% endfor %} Any idea what I'm doing wrong? I tried adding widgets={'noon_options': Select2MultipleWidget} to the modelformset_factory definition, this doesn't help. -
django.db.utils.ProgrammingError: (1146, "Table '' doesn't exist")
I'm trying to migrate my db from the local sqllite to a mysql one in aws, following the commands: 1)python manage.py dumpdata > db.json 2)Change the database settings to new database such as of MySQL / PostgreSQL. 3)python manage.py migrate 4)python manage.py shell Enter the following in the shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() 5)python manage.py loaddata db.json _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'mydb.mytable' doesn't exist") The above exception was the direct cause of the following exception: ... django.db.utils.ProgrammingError: (1146, "Table 'mydb.mytable' doesn't exist") -
ElasticBeanstalk - SQLite version is wrong, how do I fix this for my django project?
I'm running a Django Project on Amazon Elastic Beanstalk. I encountered a 500 error. I've traced my error to do with SQLite [Sun Feb 14 20:02:02.485066 2021] [:error] [pid 419] check_sqlite_version() [Sun Feb 14 20:02:02.485072 2021] [:error] [pid 419] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/ sqlite3/base.py", line 67, in check_sqlite_version [Sun Feb 14 20:02:02.485075 2021] [:error] [pid 419] raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % D atabase.sqlite_version) [Sun Feb 14 20:02:02.485096 2021] [:error] [pid 419] django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (fo und 3.7.17). I don't have any power to upgrade SQLLite on EB it seems. My SSH access is Read-only. How am I supposed to get Django to work in this environment? Requirements.txt: asgiref==3.3.1 Django==3.1.6 Pillow==8.1.0 pytz==2021.1 sqlparse==0.4.1 -
Django Match Model Choice Field to Foreignkey
I'm trying to make a Quiz App for my College... I want to map every department to a Faculty models.py Class Faculty(models.Model): faculty_choice = [ ("FOE","faculty of engineering"), ("FOS","faculty of science"), ("FOA","faculty of Agriculture"), ] faculty = models.CharField( max_length=3, choices=faculty_choice, default=FOE, ) Class Department(models.Model): Faculty = models.FOREIGNKEY( Faculty, on_delete=CASCADE) #this is where my problem is I don't know the next step Under the Faculty of engineering we have other options to Like Faculty Of Engineering Mechanical Electrical Civil Faculty Of Science Mathematics Physics Chemistry Faculty Of Agriculture Animal Plants Economy and extension hope my question is descriptive enough❓ -
Can users guess the media url in django if I don't expose it in the templates?
If they can, is there a way to protect the url? If yes, please share. -
How to disable tags on wagtail images?
I'm using wagtail as an amazing and customizable CMS in my project. One of the things I want to customize is disabling tags on wagtail images. In my project, it's really meaningless to have tags on images. Only tags on pages are required. I've tried creating a custom image model but I got wired errors. I guess it's only intended to add fields to the wagtail image model. And it cannot be used to remove a field (tags in this case). How should one remove/disable tags on wagtail images? -
Django Rest Framework: How call check_object_permissions() with APIView or GenericAPIView
I want to allow only object creators to be able to see their object. So, I want to verify that the user is equal to the created_by field of the object. I use only APIView or GenericAPIView for my views: class CertificateDetailApi(APIView): permission_classes = [IsCreator] class OutputSerializer(serializers.ModelSerializer): class Meta: model = Certificate fields = ('__all__') def get(self, request, pk): certificate = get_object_or_404(Certificate, pk=pk) serializer = self.OutputSerializer(certificate) return Response(serializer.data) Here is my permissions: class IsCreator(BasePermission): def check_object_permissions(self, request, view, obj): return obj.created_by == request.user My problem is that the check_object_permissions() method is never called. What I have tried: To replace APIView by GenericAPIView To call check_object_permissions() in the view, before return Response(serializer.data) To implement get_object() method in the view None of these solutions worked. I don't understand what to call check_object_permissions(). Any help would be welcome! -
Removing duplicate objects within a Django QuerySet
This is a question that I've seen asked a few times but I could not really find a solution that made much sense for my problem. >>> query = ['software', 'engineer'] >>> hits = [] >>> for q in query: ... x = Vacancy.objects.filter(Q(job_title__icontains=q)) ... hits.append(x) ... >>> hits [<QuerySet [<Vacancy: 6 Software Engineer>]>, <QuerySet [<Vacancy: 6 Software Engineer>]>] How can I clean up the hits QuerySet so it doesn't have any duplicates? I tried the below but that was unsuccessful: >>> hits = list(dict.fromkeys(hits)) >>> hits [<QuerySet [<Vacancy: 6 Software Engineer>]>, <QuerySet [<Vacancy: 6 Software Engineer>]>]