Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
With django-filter, is there a quick way to support all possible lookups for fields?
django-filter allows you to easily declare filterable fields of a model. For example, class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username'] provides an exact lookup for the username field which is equivalent to this... class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { 'username': ['exact'] } I'm looking for a way support all possible lookup filters given the field so that I don't have to do this: class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { "username": ["exact", "iexact", "contains", "icontains", "startswith", ..., etc.] } -
list index out of range when upgrating python/django
fa = Fa.objects.filter(fa_name = tag)[0] It was working in python 2.7 and django 1.8 but now that I migrated to django 2.2 and python 3.6 its not working -
How to show query values in url lile webpage/?q='A'&q='B'.....&q='N' using a single input in html form
I am trying to create a url like this: web.com/?q='A'&q='B'.....&q='N' where N is the number of user created list of values using an html form. <input type="text" name="q" multiple> <input type="submit" value="Show" > It shows ?q=A%2C+B in the url if the input is 'A', 'B'. I am using Django in the backend and using `query = request.GET.getlist('q') to get the list of values. I guess I can do q[] to get an array if I know the number of list of values of user created list, but that is unknown and variable. Is there an elegant way of doing this just using html? I have searched for various SO questions like these: How to Submit Multiple Values in a single HTML Form? Pass Javascript Array -> PHP But these are not exactly what I want. I guess I can create a form which would accept a csv file and then then get processed in Django to get the url I want, but I am just curious if I can do it just by using html (and if necessary JavaScript). Thanks in advance. -
Heroku Scheduler Fails: Apps Aren't Loaded Yet
Im trying to set up Heroku Scheduler on my Django ASGI application instance, but am running into a pesky exception. Im running Django Channels via Daphne on this server. 2020-02-27T01:32:54.607743+00:00 app[scheduler.4282]: Traceback (most recent call last): 2020-02-27T01:32:54.607779+00:00 app[scheduler.4282]: File "api/push_notifications/run.py", line 1, in <module> 2020-02-27T01:32:54.607883+00:00 app[scheduler.4282]: from api.push_notifications.stream import * 2020-02-27T01:32:54.607884+00:00 app[scheduler.4282]: File "/app/api/push_notifications/stream.py", line 1, in <module> 2020-02-27T01:32:54.608022+00:00 app[scheduler.4282]: from .helpers.persist import * 2020-02-27T01:32:54.608025+00:00 app[scheduler.4282]: File "/app/api/push_notifications/helpers/persist.py", line 1, in <module> 2020-02-27T01:32:54.608174+00:00 app[scheduler.4282]: from api.serializers import PushNotificationSerializer 2020-02-27T01:32:54.608174+00:00 app[scheduler.4282]: File "/app/api/serializers.py", line 2, in <module> 2020-02-27T01:32:54.608282+00:00 app[scheduler.4282]: from api.models import * 2020-02-27T01:32:54.608282+00:00 app[scheduler.4282]: File "/app/api/models.py", line 4, in <module> 2020-02-27T01:32:54.608381+00:00 app[scheduler.4282]: from django.contrib.auth.models import User 2020-02-27T01:32:54.608383+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> 2020-02-27T01:32:54.608485+00:00 app[scheduler.4282]: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager 2020-02-27T01:32:54.608486+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> 2020-02-27T01:32:54.608604+00:00 app[scheduler.4282]: class AbstractBaseUser(models.Model): 2020-02-27T01:32:54.608604+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__ 2020-02-27T01:32:54.608726+00:00 app[scheduler.4282]: app_config = apps.get_containing_app_config(module) 2020-02-27T01:32:54.608727+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config 2020-02-27T01:32:54.608893+00:00 app[scheduler.4282]: self.check_apps_ready() 2020-02-27T01:32:54.608893+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready 2020-02-27T01:32:54.609020+00:00 app[scheduler.4282]: raise AppRegistryNotReady("Apps aren't loaded yet.") 2020-02-27T01:32:54.609030+00:00 app[scheduler.4282]: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 2020-02-27T01:32:54.750918+00:00 heroku[scheduler.4282]: State changed from up to complete 2020-02-27T01:32:54.732106+00:00 heroku[scheduler.4282]: Process exited with status 1 Ive tried adding django.setup() at the … -
In Django REST Framework, how to serialize the results of calling a given method on each member of a queryset?
I want to make a ListAPIView which looks up a queryset, calls a method on each member of that queryset, and then serializes the results with many=True. I can see several ways of doing this. Is there a convention? Iterate over the source queryset in the ListAPIView, calling the method on each object, and putting the results in a list. Then serialize that list. Wrap the source queryset to produce another queryset which calls the method when appropriate. This sounds like the sort of thing which would be built in, but I can't find it in the Django docs. Get the serializer to call the method as appropriate. This also seems like it would be built in, but I can't find it in the Django REST Framework docs. -
I want to call get_queryset on an object twice with in a view template. How should I do it?
I am trying to build a web app that helps studying languages. On the index page(home page), I want to show 2 sections: "Latest vocabulary" and "Random vocabulary". Hence, I want to filter the Spanish vocabulary list using two filters separately. First one is to arrange them according to date of being added to the database, and the other is to randomize and draw 20 random words. I found the get_queryset() is a way to do the 1st filtering, and I found another way to randomize from stackoverflow as well. But the problem is, get_queryset() returns the result to context_object_name, and I suppose there can only exist one context_object_name. So I don't know how to fetch the random_spanish_list and display it. Here is the code for the index page. {% if latest_spanish_list %} <div class="flexcontainer"> <div class="sectiontitle">Latest vocabulary </div> {% for spanish in latest_spanish_list %} <div class="card"> <div class="cardinner" onclick="this.classList.toggle('flipped');"> <div class="cardfront"> <a href="{% url 'geniusdennis:detail' spanish.id %}">{{ spanish.word_esp }}</a> <form action="/deleteword/{{spanish.id}}/" method="post">{% csrf_token %} <input type="submit" value="Delete"/> </form> </div> {% for english in spanish.english_set.all %} <div class="cardback"> <p>{{ english.word_eng}}</p> </div> {% endfor %} </div> </div> {% endfor %} </div> {% else %} <p>No Spanish words are available.</p> {% endif … -
sending notification to selected user in Django
I am working on a part of a project that when I create a group for a project and once I submit the form (where I can pick certain users to be in the group in the form), the users who I selected in the form will receive any type of notification. The idea I am having now is when the selected users log in, their web pages will receive the notification that they are selected to the group. I have looked at Django's message frameworks however, it seems like they don't have the information that I am looking for. Can anyone please give me suggestion on where to start and what should I look at? I am an extreme noob in Django so please help ! -
Computing the final average per grading categories using django
Good day everyone, I just had created my table inside my views.py, I just want to compute the average Per Grading Categories (please see the image of admin Site), This is my data in admin Site studentsgrade = studentsEnrolledSubjectsGrade.objects.filter( Teacher__in=teacher.values('Subjects')).distinct('Grading_Categories').order_by('Grading_Categories') gradingcategories = gradingCategories.objects.filter( id__in=studentsgrade.values_list('Grading_Categories')).distinct().order_by('id') print("gradingcategories",gradingcategories) gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories') print("gradepercategory",gradepercategory) count_id = studentsEnrolledSubjectsGrade.objects.filter( Grading_Categories__in=cate.values_list('id')).filter( grading_Period__in=period.values_list('id')).order_by( 'id').filter(Students_Enrollment_Records__in = studentenrolledsubject.values_list('id', flat=True)).count() this is the result of print("gradingcategories",gradingcategories) and print("gradepercategory",gradepercategory) gradingcategories <QuerySet [<gradingCategories: Quiz>, <gradingCategories: Homework>]> gradepercategory <QuerySet [<studentsEnrolledSubjectsGrade: Mary M Burabod>, <studentsEnrolledSubjectsGrade: Mary M Burabod>]> when i tried this to my gradepercategory gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories').aggregate(Sum('Grade'))['Grade__sum'] i get this error error This is how i create my table students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period__in=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter( Grading_Categories__in=cate.values_list('id')).filter( GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname','Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Middle_Initial','Grading_Categories', 'Grade').distinct() teacherStudents = StudentsEnrolledSubject.objects.filter( id__in=students.values_list('Students_Enrollment_Records')) Categories = list(cate.values_list('id', flat=True).order_by('id')) table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header.extend(list(cate.values_list('CategoryName', flat=True))) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = """Result of average … -
Add register on create django
So i'm trying to do a RESTFULL backend for an app on django. So no views needed, right now i'm adding this at the admin. i have created 2 models table 1, and category. Every time i add a table1 row i have to insert 4 categories and budget for every one, initaly 0. i've tried with a method inside table 1 class overriding the save method. and insert when its inserted but i got an error because referential integrity. i have some quiestions. 1.- What is the best way to do this? i've seen on_insert event but i've read as well that is not recomended to work with this. 2.- overide the save method leaving blank the reference to the table1? and then update with the last insert? 3.- other option? class table1(models.Model): table1field = models.CharField(max_length=100,default='') def add_cat(self,cat): category.objects.create(descripcion_categoria_insumo='category 1', category=cat, budget=0) category.save() category.objects.create(descripcion_categoria_insumo='category 2', category=cat,budget=0) CategoriaInsumo.save() pass def save(self, *args, **kwargs): created = self.pk is None super(table1,self).save(*args, **kwargs) # Call the "real" save() method. self.add_cat(self.pk) class category(models.Model): desc_category =models.CharField(max_length=100,default='') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) budget= models.DecimalField(default=0,max_digits=12,decimal_places=2 ,blank=True) category = models.ForeignKey(table1, on_delete=models.CASCADE,blank=True) def __str__(self): return self.desc_category -
How do I get a Django Server Error 500 report
I recently ran my tests on django for my project, one of them turned out as a server error 500. Thi confused me as I thought everything was passing. I currently have DEBUG=True. When I checked the documentation it said to set debug to true and add some admins to email for the full output. Is there an easier way to get the output or should I work on setting that up. For more info my project is still being developed. I dont really want to post my test code as I really need more debugging experience but if you people ask I will! Thanks for any help! -
Short Class Code For My Code For my Homework
class User(): """Represent a simple user profile.""" def __init__(self, first_name, last_name, username, email, location): """Initialize the user.""" self.first_name = first_name.title() self.last_name = last_name.title() self.username = username self.email = email self.location = location.title() self.login_attempts = 0 def describe_user(self): """Display a summary of the user's information.""" print("\n" + self.first_name + " " + self.last_name) print(" Username: " + self.username) print(" Email: " + self.email) print(" Location: " + self.location) def greet_user(self): """Display a personalized greeting to the user.""" print("\nWelcome back, " + self.username + "!") def increment_login_attempts(self): """Increment the value of login_attempts.""" self.login_attempts += 1 def reset_login_attempts(self): """Reset login_attempts to 0.""" self.login_attempts = 0 class Admin(User): """A user with administrative privileges.""" def __init__(self, first_name, last_name, username, email, location): """Initialize the admin.""" super().__init__(first_name, last_name, username, email, location) # Initialize an empty set of privileges. self.privileges = Privileges() class Privileges(): """A class to store an admin's privileges.""" def __init__(self, privileges=[]): self.privileges = privileges def show_privileges(self): print("\nPrivileges:") if self.privileges: for privilege in self.privileges: print("- " + privilege) else: print("- This user has no privileges.") eric = Admin('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska') eric.describe_user() eric.privileges.show_privileges() print("\nAdding privileges...") eric_privileges = [ 'can reset passwords', 'can moderate discussions', 'can suspend accounts', ] eric.privileges.privileges = eric_privileges eric.privileges.show_privileges() -
One to many, and one to one combined? Django
class Inquiry(models.Model): inquiry_id = models.AutoField(primary_key=True) inquiry_desc = models.CharField('Inquiry', max_length=5000) class Customer(models.Model): cust_id = models.AutoField(primary_key=True) inquiry_id = models.ForeignKey(Inquiry, on_delete=models.CASCADE) cust_f_name = models.CharField('Customer First Name', max_length=50) cust_l_name = models.CharField('Customer Last Name', max_length=50) cust_street = models.CharField('Customer Street', max_length=50) cust_city = models.CharField('Customer City', max_length=50) cust_state = models.CharField('Customer State', max_length=50) cust_zip = models.CharField('Customer Zip Code', max_length=10) Hi there! I am trying to model a one to many (a customer may have many inquiries) and a one to one (an inquiry may have one customer). Here are my difficulties/what I have tried so far: Inquiries as foreign key in Customer model. This works fine, however, you can only assign one inquiry object per customer. I would like to assign several (so Inquiry1, inquiry2, inquiry3, etc) to the customer. Pictured here/in the code Customer as a OneToOne field in Inquiry (thought this might work for some reason - but as OneToOne work, when I tried to add a a new Inquiry to an existing company it didn't work). I am looking for conceptual advice to do this. I think I'm getting confused. Thank you! -
Django application, vue.js only works if the the vue is in the HTML file
I have a django application, and im using vue.js, however the vue.js only works if the the vue is in the HTML file. As soon as I move it into a separate JS file it no longer work.I'm wondering if i'm missing something super obvious HTML FILE {% extends 'blog/base.html' %} {% block content %} {% load static %} <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11" type="text/javascript"></script> <script src="{% static 'blog/JS/main.js'%}" type="text/javascript"></script> <div class="con"> <button type="button" name="button" @click='addForm()'> new </button> <div class="car-body" v-for="(post, index) in posts"> <span style="float:right;background-color:green" @click='removeForm(index)'> x </span> <h4>Add Article (index:{{ index }})</h4> <div > <input type="text" name="" placeholder="Title" v-models='post.title'> <input type="text" name="" placeholder="Preview" v-models='post.preview'> </div> </div> </div> {% endblock content %} JS file var app= new Vue({ el: '.con', data:{ posts: [ { title:'', preview:'' } ] }, methods:{ addForm(){ this.posts.push({ title: '', preview:'' }) }, removeForm(){ this.posts.splice(index, 1) } } }) -
Getting objects via ManyToMany relation after filter in Django
I have these models: class Notebook(models.Model): title = models.CharField(max_length=200) class Tag(models.Model): name = models.CharField(max_length=63) notebooks = models.ManyToManyField(Notebook, related_name='tags') and I'm trying to find all Notebooks that have two particular tags (I can probably deduce the rest of the query if I can get two tags working) I'm defining a query for the two tags with: query = Q(name__iexact='dna') | Q(name__iexact='notebook') and I can filter the pertinent tags with: Tag.objects.filter(query) But I'm seeking the Notebooks associated with that tag. In SQL I would do a JOIN but the ORM method select_related apparently doesn't work with ManyToManyField -
Django get filenames without upload, filefield?
I have a modelform where I want the user to be able to populate a field with a filename from their local file system, ideally without typing or copy and pasting. I thought a solution might be a django FileField - models.py File = models.FileField(blank=True, null=True, verbose_name='File') This gives the user a nice button -> click filename workflow. I can get this rendering on the form OK but the purpose of FileField is clearly to upload files - I don't want the files to be uploaded, I just want to pick their names. Some of these files are extremely large, so I don't want to interact with them at all other than picking their name. -
How to add choice to Question model by login User
I'm learning django i had an idea to modify poll app from django tutorial. I wanted to add possibility to register and login and then i wanted to do a form where user could create a question and add choices. Firstly i tried to make it on one view, but i thought there will be a problem becouse i heve choice and question in separate models. Then i tried to make one vReverse for 'createChoice' with no arguments not found. 1 pattern(s) tried: ['polls\\/(?P<pk>[0-9]+)\\/choice$']iew for creating question and one for creating Choices, but here i've got this error: I would like to ask for some advice on how to do it. It would be great if i could do it in one page. Here is my code: models.py from django.db import models from django.utils import timezone import datetime from django.contrib import auth # Create your models here. User = auth.get_user_model() class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from … -
How do i hide items already selected in the checkboxes in Django Admin
So, i have this model on my app: class Loan(models.Model): loan_device = models.OneToOneField(Device, max_length=50, verbose_name='Dispositivo de Empréstimo', on_delete=models.CASCADE, null=True) Important: loan_device it's a One To One relationship with Device model On Django Admin, when someone choose any Device registered, it keeps showing in the checkboxes, even though it was previously selected. My question is: How do i hide items already selected in the checkboxes? -
Footer as a view?
On my footer I have a list of my categories. This means in every page view I loop over all my Category models. I also have a Footer model so I can choose the footer image, so I'm also calling that on every page aswell. I'm wondering if there is a better way to do this.. Here's what I mean: views.py # These are included on every page.. def homepage_view(request): context = { "categories": Category.objects.all(), "footer": Footer.objects.first(), } return render(request=request, template_name='main/index.html', context=context) models.py # Is there a better way to have a dynamic footer image? class Footer(models.Model): footer_image = models.ImageField(upload_to="footer/") class Meta: verbose_name_plural = "Footer" def __str__(self): return "Footer" Is it good practice to have a model just so I can have a changeable footer image? I don't need multiple footer models, I just want to be able to change my footers background image. -
Cómo crear un formulario en Dyango con cabecera y detalle
Necesito crear una forma en Django, similar a una factura con sus líneas de detalle, que se guarde de una sola vez. Por favor me pueden referir ejemplos. Muchas gracias. -
How To Redirect To Same Page After Post a Comment Using Django
as stated in my thread heading, i been on this issue for quite few days. Im trying to redirect to same page i was after making comment of a page irrespective of the paginated comments. Tried altering the get_success_url method but its not working. class ReadThread(MultipleObjectMixin, CreateView): query_pk_and_slug = True form_class = PostForm paginate_by = 3 template_name = 'read_thread.html' context_object_name = 'posts' def get(self, request, *args, **kwargs): self.thread = self.get_object() self.object_list = self.get_queryset() return super().get(request, *args, **kwargs) def get_object(self): thread = super().get_object( Thread.objects.filter(category__slug__iexact=self.kwargs['category_slug']) ) return thread def post(self, request, *args, **kwargs): self.thread = self.get_object() return super().post(request, *args, **kwargs) def get_queryset(self): return self.thread.posts.all() def get_context_data(self, **kwargs): context = super(ReadThread, self).get_context_data(**kwargs) context['thread'] = self.thread return context def form_valid(self, form): form.instance.thread = self.thread form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): return redirect(self.request.build_absolute_uri(self.thread)) -
Django: Search in Multiple Models
I want to implement a multi model search in django meaning that I want to search different fields in two models. My Two models are "Story" and "Place": from django.db import models from django.utils import timezone from django.contrib.auth.models import User from places.models import Place from django.urls import reverse class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Place = models.ForeignKey(Place, on_delete=models.PROTECT) audio = models.FileField(default='SOME STRING', upload_to='audio_stories/',blank=False) class Place (models.Model): name = models.CharField(max_length=100, blank=False) country = models.ForeignKey(Country, on_delete=models.PROTECT, null=True) city = models.ForeignKey(City, on_delete=models.PROTECT, null=True) description = models.TextField(blank=False) location_image = models.ImageField(default='default.jpg', upload_to='location_pics/', blank=False) def __str__(self): return self.name def get_absolute_url(self): return reverse('place-detail', kwargs={'pk': self.pk}) def save(self): super().save() img = Image.open(self.location_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.location_image.path) def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) My View merges both queries. from django.shortcuts import render, get_object_or_404, redirect from django.db.models import Q from django.views.generic import (ListView) from django.contrib.auth.models import User from places.models import Place from .models import Story class SearchResultsView(ListView):# template_name = 'story/results.html' def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: story_list = Story.objects.filter(Q(title__icontains=query)) place_list = Place.objects.filter(Q(name__icontains=query)) results = chain(story_list, place_list) return results … -
Django + Celery with AWS SQS - Running on localhost instead of AWS and not getting messages
Hello I am running Django and Celery on aws SQS, but it appears that AWS is not getting the messages. But the tasks are being executed: Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 uid=uid, euid=euid, gid=gid, egid=egid, -------------- celery@ba117e7c453f v4.4.0 (cliffs) --- ***** ----- -- ******* ---- Linux-4.9.125-linuxkit-x86_64-with 2020-02-26 20:21:14 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: config:0x7f10e26fada0 - ** ---------- .> transport: sqs://XXXXXXXXXXXXX:**@localhost// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . config.celery.debug_task . project.orders.tasks.create_log_test [2020-02-26 20:21:14,909: INFO/MainProcess] Connected to sqs://XXXXXXXXXXXX:**@localhost// [2020-02-26 20:21:15,327: INFO/MainProcess] celery@ba117e7c453f ready. [2020-02-26 20:21:32,895: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[d4c20965-b1f2-47dd-b8a8-6f9cbe35be29] [2020-02-26 20:21:53,648: INFO/ForkPoolWorker-2] Task project.orders.tasks.create_log_test[d4c20965-b1f2-47dd-b8a8-6f9cbe35be29] succeeded in 20.695041599974502s: None [2020-02-26 20:22:39,801: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[1d1b0892-078c-480c-ab7a-87662fd18ba3] [2020-02-26 20:22:41,622: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[6e755a91-b737-4e09-b910-03e84fd91c32] [2020-02-26 20:22:43,237: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[5fe1f145-a6d3-45d3-8ada-b1c636ee201c] [2020-02-26 20:22:44,506: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[84da9170-7861-488d-936f-5d3738e11af4] [2020-02-26 20:22:47,056: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[748dda1c-3b6d-40e6-b13b-637ea765dd72] And on AWS console: This is my settings.py: BROKER_URL = "sqs://{access_key}:{secret_key}@".format( access_key=quote(AWS_ACCESS_KEY_ID, safe=""), secret_key=quote(AWS_SECRET_ACCESS_KEY, safe=""), ) BROKER_TRANSPORT_OPTIONS = { "region": "eu-west-1", … -
Hyphenation in Jinja template (using Django Wagtail)
I have a Django Wagtail application, which employs the templating machine Jinja (or Jinja2, not entirely sure, but won't make a difference for this issue). When I e.g. want to use the templating to show the title of a blog post, I can write {{ post.title }} This works perfectly fine. But I cannot enforce hyphenation in this title. If the title holds a very long word, this crashes my layout on small devices. Anyone an idea how I can tell Jinja that hyphenation should be enabled? -
django run custom views class method with one url
I'm new to django. I want to manage my database with custom methods inside the views file. for example, I have this code I would like to run with javascript - I wrote this code: Js: $.ajax({ type: 'POST', url: '/ClassManager/', data: { data: data, csrfmiddlewaretoken: csrftoken, }, success: function() { alert("IT WORKED") }, error: function() { alert('error'); } }) views.py def expfunc(): if request.method == 'POST': user = User.objects.get(pk=1) addlst = List(content = "list content", creator = user) addlst.save() urls.py urlpatterns = [ path('ClassManager/', views.expfunc), ] now, the problem is, that for every new function that I want to create in the views.py, I need to add another line in the urls.py. my question is - if there a way to create a class with all of the custom methods, and access them with one url and different data? for example: Js: $.ajax({ type: 'POST', url: '/ClassManager/functionone()', data: { data: data csrfmiddlewaretoken: csrftoken, }, success: function() { alert("IT WORKED") }, error: function() { alert('error'); } }) views.py class DatabaseManager(): def functionone(): # add new list if request.method == 'POST': user = User.objects.get(pk=1) addlst = List(content = "list content", creator = user) addlst.save() def functwo(): # update username if request.method … -
Django change foreign keys to BigInt
I have two models (store and products) the primary key in both are BigInt but the relation column in products (store_id) is still integer. I dont want to use raw sql, how can I fix this issue using django?