Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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>]>] -
Reading an SPSS file (.sav or .zsav) inmemory using pyreadstat
I've been developing a Django application. I know that there are some different of reading an SPSS file. One way is using pandas. import pandas as pd file_path = "./my_spss_file.sav" df = pd.read_spss(file_path) Another way is using pyreadstat import pyreadstat df, meta = pyreadstat.read_sav('./my_spss_file.sav') As you can see above, unlike pandas, using using pyreadstat I can get the meta information such as variables and values of labels. So, that is what I am using. The problem with this pyreadstat is that I cannot use it for inmemory read. After uploading an spss file from a browser, each time I have to upload it to a directory and then read the file from there using pyreadstat module. def upload_file(request): result = None # Get the context from the request. context = RequestContext(request) if request.is_ajax(): if "POST" == request.method: global my_df global _explore global base_dir file = request.FILES['file'] file_name = file.name base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) try: my_df = None # Determine the type of the file and get the dataframe if file_name.endswith('.csv'): my_df = pd.read_csv(file, header=0) elif file_name.endswith('.xlsx') or file_name.endswith('.xls'): my_df = pd.read_excel(file, header=0) elif file_name.endswith('.sav') or file_name.endswith('.zsav'): handle_uploaded_file(file, str(file)) file_path = os.path.join(base_dir, "upload\\") + file_name my_df = util.read_spss_file(file_path) def read_spss_file(f_name): df, meta … -
generic class based view CreateView - how to compare the request.user to a certain modelobject.user
Inside my generic CreateView class based view, I want to compare the request.user to a certain modelinstance.user, and if the users dont match, I want to raise a 404 error, how can I achieve this? Which method inside the generic.CreateView should I modify and how? Thanks! -
ERROR while connecting static and media files in django
i have tryng configure my static files but still dont works so as i guess when i run gunicorn service and it takes wsgi file to run in 8000 port also takes settings with allows hosts and databases and i wonder why it cannt read static files when i run server its not django responsible to read static file and i need to set in nginx conf file ? what am doing wrong?thanks web is main file with manage.py my nginx.conf file server { listen 80; server_name examples.com www.example.com; client_max_body_size 4G; charset utf-8; location /media/ { alias /var/www/html/web/media/; } location /static/ { alias /var/www/html/web/static/; } location / { proxy_pass http://127.0.0.1:8000; } production settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ("/var/www/html/web", ) -
How can I call in Django template a coordinate of a list's element?
I created a class that has some attributes. One of them is a list that has coordinates as elements. Here's the python code: @attr.s class ProductMetadata: features: list = attr.ib() #some other attrs standard = ProductMetadata( features=[(True ,"Up to 1000 DMs"), (False, "Ludicrous mode"), (False, "Premium Support")], # the other attrs ) And, since I'd like to write a list where the customer can see whereas he can benefit from a feature given his package, here's the code somehow I'd like to write: <ul> {% for feature in product.metadata.features %} <li> <i class="lni {% if the first coordinate of the element is True %}lni-checkmark active"{% else %} lni-close {% endif %}></i>{{ the second coordinate }}</li> {% endfor %} </ul> Here's the result I'd like to get (visually): Also, given that the class name is ProductMetadata, and that the product.attr works when I just use Stripe (without the class), is using product.metadata.attr correct? Thanks a lot! -
Django Dynamic Table Class Objects
I cannot figure out a way in models.py to pull data from the database to populate the objects in another class. models.py: from django.db import models informationtitles = ["title1" , "title2"] class informationtable(models.Model): informationtitle = models.CharField(max_length=30, null = True) class storedinformation(models.Model): pass for dataHeaders in informationtitles: storedinformation.add_to_class(dataHeaders, models.CharField(max_length=30, null = True)) This code works but I would like: informationtitles = ["title1" , "title2"] To be something like: informationtitles = informationtable.informationtitle.objects.all() -
Django Listview pagination; Page is paginated correctly but page_obj not working in template
I am new to Django and trying to refactor my function-based views to CBVs. I got everything else working, and the pagination works(it shows "JOBS_PER_PAGE" jobs on each page), but the only problem is that in the template, page_obj does not work. Although the page has next pages, the page navigator is all greyed out and disabled. page_obj.number doesn't return anything. I looked at other posts, but I couldn't find any useful information. Is there any extra step I need to do to get page_obj to work correctly in the template? urls.py urlpatterns = [ path('', views.landing_page, name='landing-page'), path('search/<int:pk>/', views.SearchView.as_view(), name='search'), path('apply/<int:pk>/', views.apply, name='apply'), path('result/<int:pk>/', views.result, name='result'), path('start/', views.start, name='start'), path('eor/<int:pk>', views.end_of_round, name='end-of-round'), path('closing/<int:pk>', views.closing, name='closing') ] views.py class SearchView(ListView): model = Job context_object_name = 'jobs' template_name = 'simulation/search.html' paginate_by = JOBS_PER_PAGE def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.respondent = Respondent.objects.get(pk=self.kwargs['pk']) if self.respondent.is_out_of_money(): self.respondent.increment_round() self.respondent.save() return redirect('simulation:end-of-round', pk=self.respondent.id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['respondent'] = self.respondent return context def post(self, request, *args, **kwargs): self.respondent.subtract_from_balance(request.POST.get('more_info_fee')) self.respondent.add_to_jobs_more_info(request.POST.get('selected_job')) self.respondent.log_time_spent() self.respondent.increment_stage() self.respondent.save() return redirect('simulation:search', pk=self.respondent.id) search.html {% if is_paginated %} <nav aria-label="..."> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ … -
Display Polygon in Leaflet Map from Geodjango
I'm developing a geospatial mapping application using geodjango and django-leaflet which lets users draw a polygon on a map and save that polygon to a model. I thought it would be simple to extract the saved polygon from the model and render it on a Leaflet map embedded in a template. However, I'm having considerable difficulty doing so. This is mostly due to me being a new web developer (I'm especially new to JS). Here's what I have so far: models.py: class newJob(BaseModel): job_name = models.CharField(max_length=64) job_desc = models.CharField(max_length=64) job_loc = models.PolygonField() user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) The spatial data is saved successfully to the model using the form I have created (not shown). I have then created a simple function-based view to pull the required data from the database. I have created a 'raw' object (job_loc) and also serialized the data to geojson to create json_loc (as I'm not sure which is best to work with). views.py: def viewjob(request): req = request.GET job_name = newJob.objects.values_list('job_name', flat=True).get(pk=req['search']) job_desc = newJob.objects.values_list('job_desc', flat=True).get(pk=req['search']) job_loc = newJob.objects.values_list('job_loc', flat=True).get(pk=req['search']) json_loc = newJob.objects.filter(pk=req['search']) json_loc = serialize('geojson', json_loc, geometry_field='job_loc') context = { 'job_name': job_name, 'job_desc': job_desc, 'job_loc': job_loc, 'json_loc': json_loc } print(context) return render(request,'viewjob.html', context) … -
Django NoReverseMatch but parameter is passed in
I know this seems a pretty common error but after spending the best part of 90 minutes searching the site for an answer that helps me I just cannot figure out what's causing it. in my profile.html I have a link to view a users list of followers <a href="{% url 'view_user_followers' viewuser.user.id %}" class="text-white followers-link">Followers: {{ followers_count }}</a> but when I have this link in the page it throws me this error: Reverse for 'view_user_followers' with arguments '(11,)' not found. 1 pattern(s) tried: ['users/view_user_followers$'] the view for this in my views.py is: def view_user_followers(request, user_id): viewusers = Profile.objects.filter(user_id=user_id) following_count = Follow.objects.order_by('-created').filter(user_id=viewusers.user_id).count() followers = Follow.objects.order_by('-created').filter(following_user_id=viewusers.user_id) followers_count = Follow.objects.order_by('-created').filter(following_user_id=viewusers.user_id).count() context = { 'viewusers': viewusers, 'followers': followers, 'following_count': following_count, 'followers_count': followers_count } return render(request, 'accounts/user_followers.html') and in my urls.py I have: urlpatterns = [ path('<int:user_id>', views.profile, name='profile'), path('view_user_followers', views.view_user_followers, name='view_user_followers') ] Whats confusing me most is that also in my views.py for Profile I have: def profile(request, user_id): viewusers = Profile.objects.filter(user_id=user_id) reviews = Review.objects.order_by('-review_date').filter(user_id=user_id) favourites = Favourite.objects.order_by('id').filter(user_id=user_id) does_follow = Follow.objects.filter(following_user_id=user_id, user_id=request.user.id).exists() following = Follow.objects.order_by('-created').filter(user_id=user_id) following_count = Follow.objects.order_by('-created').filter(user_id=user_id).count() followers = Follow.objects.order_by('-created').filter(following_user_id=user_id) followers_count = Follow.objects.order_by('-created').filter(following_user_id=user_id).count() context = { 'viewusers': viewusers, 'reviews': reviews, 'favourites': favourites, 'does_follow': does_follow, 'following': following, 'followers': followers, 'following_count': following_count, 'followers_count': followers_count …