Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sessions slow
I am building a webapp with Django (nginx + uWSGI + django on DigitalOcean). The app is basically an interface to a finite element solver. The user uploads the input data which is then sent to a computation unit. When uploading the data, I store it in requests.sessions. Question 1: is this bad practice? What would be a better alternative? As backend for the session data, I use a database (which is the default). The user can upload data up to 30MB. Question 2: is this database or the data I store in request.sessions stored in RAM? Or on the disk? After uploading the data, my app is very slow. If multiple users upload at the same time, often the upload doesn't go through. Question 3: why? How to avoid this? -
Email Verification Throwing Error If The User Isnt Signed In Before Clicking The Verify Email Link
Im using allauth with email confirmation. If I register a new user, then log in (without being verified), then open the email and follow the link, the user gets successfully verified in the db and can continue using the site. However, if I register a new user, then log in (without being verified), then open the email and follow the link, the user gets successfully verified in the db, but the link throws this error: NoReverseMatch at /accounts/confirm-email/MzA:1jZWYM:JgeeuPYRC3QnGOPs3L7kzZEFi5M/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. So basically, the user has to already be logged in when they click the link in the email for it to work without error, but if they are not logged in and follow the verify link in the email, they get verified in the db but an error is thrown. PS- this is using normal registration (nothing to do with social accounts). Thank you. -
Django: Define custom field in ListView
I want to check if the currently logged in user liked a post. Here are my models: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = models.Manager() image = models.ImageField(upload_to='post_pics', default='default.jpg') def __str__(self): return self.title @property def useremail(self): return self.author.email @property def owner(self): return self.author def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) def get_like(self): liked = "False" User_id = request.user.id if self.like_set.filter(user=User_id): liked = "True" return liked class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) I tried setting it up in models (see 'get_like' function) however, as per link it is not possible to do. How can I set it up in a view? My view: class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 In html I have a loop {% for post in posts %} 'html' {% endfor%} I would need to call something like this in html post.like_set.filter(user=request.user).first() however, if I put {{ post.like_set.filter(user=request.user).first }} in the for loop I receive a template syntax error: "Could not parse the remainder: '(user=request.user).first' from 'post.like_set.filter(user=request.user).first'" PS: Same thing happens even if I put 'user' instead of 'request.user' -
How to make a cart(add_to_cart and remove_from_cart) using a Menu and Order Model
I am trying to design a cart system from two models, a Menu Model and an Order Model. A third Model called the Orderstatus has a foreignkey to the Order Model and it's default is False. How exactly can I create a add_to_cart and remove_from_cart working with these tables. I am looking for a way to to do without creating a MenuItems Model. models.py class Menu(models.Model): none = 0 Daily = 1 Weekly = 7 Monthly = 30 Quarterly = 90 SemiAnual = 180 Yearly = 365 Frequency_Of_Reocurrence = ( (none, "None"), (Daily, "Daily"), (Weekly, "Weekly"), (Monthly, "Monthly"), (Quarterly, "After 3 Months"), (SemiAnual, "After 6 Months"), (Yearly, "After 12 Months") ) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) name = models.CharField(verbose_name="food name", null=False, blank=False, max_length=100) description = models.TextField(verbose_name="Food Description", null=False, blank=False) price = models.FloatField(verbose_name="Price (₦)", default=0.00) quantity = models.PositiveIntegerField(default=1) isrecurring = models.BooleanField(default=False) frequencyofreocurrence = models.IntegerField(choices=Frequency_Of_Reocurrence) datetimecreated = models.DateTimeField(verbose_name='date-time-created', auto_now_add=True) def __str__(self): return self.name + " by " + f'{self.vendor.user.first_name}' def get_total_menu_price(self): return self.price * self.quantity def get_final_price(self): if self.price: return self.get_total_menu_price() class OrderStatus(models.Model): name = models.NullBooleanField(default=False) def __str__(self): return '{}'.format(self.name) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) description = models.TextField(verbose_name="Order description", null=False, blank=False) itemsordered = models.ManyToManyField(Menu, verbose_name="menu", default=None, blank=True) amountpaid … -
Multithreaded Django UWSGI
I am facing issues with my Django app behind multithreaded UWSI. JSON requests, with simple database (mysql) queries, randomly take up to 10 times compared with the normal response time to be completed (from 50ms to 500ms). I noticed that removing multithreading from my uwsgi.ini file solved the problem. My guess is that Django is sharing database connections between threads and multiple requests slow down the query time. This is the UWSGI incriminated configuration: processes = 2 ; without the next two lines my app works fine enable-threads = true threads = 2 I can remove threading (the application does not need to serve many requests), but I would like to know if anyone have had the same problem and if my guess is right. -
Average age from birth date in django
In my django(3.0.5) application I am trying to get average age from date of birth in a model. I am using MySql database. Here is how I tried: Model: class ShippingStaff(models.Model): full_name = models.CharField('Full Name', max_length=200) birth_date = models.DateField('Date of Birth', null=True, blank=True) Customer Filter: @register.filter(name='age') def age(bday, d=None): if d is None: d = datetime.date.today() return (d.year - bday.year) - int((d.month, d.day) < (bday.month, bday.day)) Views: def home(request): shipping_staff = ShippingStaff.objects.aggregate(staff_count=Count('full_name'), avg_age=Avg(custom_time.age('birth_date')) I get error like: Exception Value: 'str' object has no attribute 'year' Exception Location: /home/smrashel/jahaji/crewdatabd/templatetags/custom_time.py in age, line 31 which is return (d.year - bday.year) - int((d.month, d.day) < (bday.month, bday.day)) How can I solve this? Any help will be much appreciated. -
Django send_mail() "502 Bad Gateway" error in production
I need expert advice. I have set my Django web application on Digital Ocean. It is using ubunto OS with Nginx and gunicorn. Everything working great except when it comes to send email. Everytime when I send email from my website I get "502 Bad Gateway error". I am exploring google from past three days but nothing seems to work for me. Note: When I put my gmail configurations in settings.py, everything works perfect. I suppose there is something wrong with my domain email configurations, that are: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'golf.mywebsitebox.com' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 465 EMAIL_USE_TLS = True But I have thrice checked them with my domain providers and they say these configuration are correct. Now I don't know what is the cause of this problem? To whom I consult in this regard? -
Django, how to set form value with cleaned_data?
I have the following model: STATUS_CHOICES= [ ('VARIABILE', 'VARIABILE'), ('FISSO', 'FISSO'), ] status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="") And I want to hide this field in my tempaltes'forms and set it value automatically to "VARIABILE". I was trying to set it in the following way: modCollaboratori_form = ModCollaboratoriFormSet(self.request.POST) if modCollaboratori_form.is_valid(): modCollaboratori_form.cleaned_data['status']= "VARIABILE" But I obtain the following error: list indices must be integers or slices, not str -
Lets Encrypt gives an error on Django Apache
I am trying to install Lets Encrypt SSL certificate on my Django site hosted on Apache / Ubuntu 18. However, I get the following error: Domain: example.com Type: unauthorized Detail: Invalid response from https://www.example.com/.well-known/acme-challenge/zJvPxPWmiElEitiQGKfGLATVThXno992ctCu5Bg6H6A [2606:4700:3033::681c:cf3]: "<html>\r\n<head><title>403 Forbidden</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>403 Forbidden</h1></center>\r\n<hr><center>" I tried adding path to the urls.py as such: path(r'^.well-known/', include('letsencrypt.urls')) Can someone please guide me? -
CSS disappear after I set my django project into the cloud server
Site administration Authentication and Authorization Groups Add Change Users Add Change Dataloginin Loginin_ tables Add Change Recent actions My actions None available become like this. -
How to authenticate django static file access?
I am developing a site that uses DJANGO basic auth: django.contrib.auth It works fine, and only logged in user can visit a page. However, I find that the auth cannot apply to static file. e.g. one page loads a static file video, the user needs to log in to view but I can use f12 to find the path. http://example.org/static/media/test.mp4 and after I log out the user, I can still use the above url to directly access the static file without auth. I tried several methods but they are not working. Is that possible to add auth to static file path? -
Is there a limit to how many Foreign Keys I can have in one entity?
I'm building my own e-commerce system from scratch using the django-rest-framework. Here is a description of my system architecture: Db format = PostgresSQL One Account has many LineItems (aka CartItems). One LineItem has one Account (FK), one Product (FK) One Account has many Orders LineItem Fields: Account FK Product FK Quantity Price (Serializer method field to factor in any discounts (range 0-1) specified the product model). My Issue lies with the account being able to create an order. I have identified two ways so far: 1) Modify the LineItem Model by adding the following fields: IsMountedForOrder (for buy now purposes) - BooleanField Order (Foreign Key) Constraint: The LineItems Model becomes overburdened with Foreign Keys and relationships - is it going to be a hindrance from a DB management standpoint? 2) Create an OrderItem Model (One Order has Many OrderItems) Fields: Order FK Product FK (Parsed from owned LineItems) Quantity (Parsed from owned LineItems) Price (Parsed from owned LineItems) and upon creation of a successful order, the lineItems will be deleted. Constraints: There is a duplication of Data for a short duration and seems like unnecessary computation - therefore adding latency to the service. I would appreciate any suggestions in how … -
I there a way of changing the text of "add child page" button wagtail
Is there a way of changing the text of the button "add child page" of default Page model of Wagtail? -
How to fetch live data from MySql database using PySpark?
I am using PySpark to fetch data from my MySql database, now I want to fetch real time live data from my database using PySpark and I am confused how to do it. Any Example, documentation, tutorials, or advice would be greatly appreciated. -
Django App Deployed in Azure not Displayed
We have a Django app which runs perfectly in our local environment and also is deployed in Heroku (run smoothly there too). However, when deployed in Azure we see this image from the Azure portal: python code up and running The wsgi file looks like this: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_gui.settings') application = get_wsgi_application() Referencing all the files in the settings.py which are all set up accordingly to the django checklist in manage.py check --deploy In Azure we have tried various ways of deploying it, from Azure Devops Repos, to pushing the file from Azure CLI. Any hint or input would be highly appreciated. -
Django form, how to set a cleaned data value from multi choices
I have a question for you. I'm trying to set a value of a my form's field directly from the Post request, in the following way: .... modCollaboratori_form.cleaned_data['status']= "VARIABILE" ... The field 'centro di costo' is a multi choices field: STATUS_CHOICES= [ ('VARIABILE', 'VARIABILE'), ('FISSO', 'FISSO'), ] status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="") I have tried the code above but django give me the following error: list indices must be integers or slices, not str Where is the problem? -
Required "owner_id" field is empty in the Database
I am trying to save the owner_id that is the same as the Logged In user/Authenticated user. But after I save the AddressBook form,the database saves the owner id with 'Null' value. Can someone help me knowing where am I going wrong. models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile") mobiles = models.ManyToManyField(Product, blank=True) class AddressBook(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True) Database -
Queryset for ManyToMany relation ordered by number of match from a list
I have two models, Entity and Tag with a ManyToMany relation : class Tag(models.Model): name = models.CharField(max_length=128) class Entity(models.Model): name = models.CharField(max_length=128) tags = models.ManyToManyField(Tag) In a view I have a list of Tag id and would like to get a top 10 of Entity with at least one Tag ordered by the number of Tags they have in common with my list. I am currently doing the "at least one" part through 'tags__in' and adding a '.distinct()' at the end of my queryset. Is it the proper way ? I can see that there is a 'Count' in annotate that can have some arguments, is there a way to specify only if id in my list ? If not do I need to go through an SQL query like this (from the documentation) ? I fear I am going to lose quite some perf. Blog.objects.extra( select={ 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id' }, ) -
Run multiple microservices in single tab
I have 10 microservices in django. I am running all microservices in different tab in terminal on localhost.So I want to run all microservices in single tab. I don't want to open multiple tab. Is there any way to do so? Thanks in Advance -
How do I show dynamic and dependable list of values of model field on Front End using Django Forms?
I have a Detail Model which has a ForeignKey() of User Model. I want to show the list of subject (which is a field of Detail Model) associated with a single user, at the Front End in Template. It should be a dropdown menu and user should be able to select the subject from the list and submit the form. How should I accomplish it? Below is my models.py class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50) skype_session_attendance = models.FloatField() internal_course_marks = models.FloatField() programming_lab_activity = models.FloatField() mid_term_marks = models.FloatField() final_term_marks = models.FloatField() def __str__(self): return f'{self.subject, (self.user.username)} Details' and below is my views.py: def performanceCalculator(request): if request.method == 'POST': performance_form = PerformanceCalculatorForm(request.POST) if performance_form.is_valid(): sub = performance_form.cleaned_data['subject'] detail = Detail.objects.all().filter(user=request.user, subject=sub).first() result = fuzz_algo(detail.skype_session_attendance, detail.internal_course_marks, detail.programming_lab_activity, detail.mid_term_marks, detail.final_term_marks) messages.success(request, result) return redirect('performance_calculator') else: performance_form = PerformanceCalculatorForm() context = { 'performance_form': performance_form, } return render(request, 'users/performance_calculator.html', context) and below is forms.py: class PerformanceCalculatorForm(forms.Form): subject = # what should I put here in order to make a dropdown list? class Meta: fields = ['subject'] Thanks in advanced -
Assign permissions that aren't model based
If I understand correctly, you can restrict access to certain webpages in Django by using the permission_required decorator. The permissions you check for, are defined at model level. For example: views.py: @permission_required('replacements.view_calendar') def calendar_entry(request, calendar_id): [...] This allows all users with permission to view objects from the Calendar type, to access the webpage on which one of these Calendar objects is shown. This is clear. The issue I'm struggling with, is that I fail to see how this is a clean way to implement permissions. I have three groups of users: Superusers who are able to see everything and access the Django Admin Interface Administrators who are able to see everything and edit the models that are available to them via the website interface. They cannot access the Django Admin Interface Users who can view some of the pages and cannot edit anything I could assign all relevant view, add, change and delete permissions for each model, to the administrator group. But this seems a bit unnecessary, either the user can view the webpage and edit everything that can be edited via this webpage, or the user just doesn't have access to this page. So I think it would be … -
How can I Use SMTP in Dockerized Django web app running on AWS
I have a Django web app running in a Docker container which in due course will run live in an AWS EC2 instance (but for development is running on my Windows 10 laptop). As the web app wants to send emails for various reasons, I would like to know the simplest approach for this, both for AWS operation, presumably using Amazon's Simple Email Service (SES), and for my development. Having read that the Docker container needed to include an SMTP relay, I spent some time setting up the neat looking relay at https://hub.docker.com/r/turgon37/smtp-relay But despite the claimed simplicity of the config setup, I had trouble with this (probably my fault, although the documentation was somewhat ambiguous in places as it was obviously written by someone whose native language is not English!). More to the point, it occurred to me that the claim an SMTP relay was needed in the container may have been nonsense, because surely one can just map container port 25 to the host's port 25 ?! So in summary, has anyone had this requirement, i.e. for using SMTP in a Docker container, and what is the simplest approach? TIA Regards John R -
Title: How to change the display of Django xadmin when use "fields"
At the beginning of learning "xadmin", I encountered a "fields "problem. For example, when using 'admin' : from django.contrib import admin from .models import Example @admin.register(Example) class ExampleAdmin(admin.ModelAdmin): ...... fields = ('field1','field2',('field3','field4')) # field3 and field4 will be in the same row Now, I want to do the same thing in" xadmin", if I write it exactly the same way, the page will report an error: from .models import Example import xadmin class ExampleAdmin(object): fields = ('field1','field2',('field3','field4')) # sequence item 0: expected str instance, tuple found xadmin.site.register(Example,ExampleAdmin) In 'xadmin', I want to have two fields on the same row,What should I do?Thanks for your help! -
Can not call django api after deploy on apache xampp
I follow this tutorial, but some trouble with apache xampp & django. book/models.py from django.db import models class Book(models.Model): name = models.CharField(max_length=255, blank=True, null=True) price = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'book' book/views.py from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import IsAuthenticated from .models import Book from .serializers import BookSerializer class ListAllBook(ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = [IsAuthenticated] book/urls.py from django.urls import path from .views import ListAllBook urlpatterns = [ path("all-book", ListAllBook.as_view(), name="all-book"), ] project/urls.py # from django.contrib import admin from django.urls import path, include urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path("api/book/", include("book.urls")) ] It's work on dev environment (eclipse), error after deploy. I use djoser for authentication. Djoser api work on eclipse, apache Book api error on apache Someone please help me. Thank you very much. -
Difference of running between local and aws EC2 server to deal with File Django object
I work on Django project that i deploy on aws server with elasticbeanstalk. I don't understand the difference of behavior between local and production mode. What i want is to retrieve text from a fix html document as you can simply understand below. The issue occurs on for statement and ONLY in production mode. I know it because I log each line in LogTable of my production database to control what it happens. Every time i log correctly the line just before the for statement. Originally, I have the following code: html_string = "" template = open(os.path.join(settings.MEDIA_ROOT,'synthesis/synthtemplate.html')) for line in template: html_string += line Then, i improve my code to work with File object wrapper from Django as follow: html_string = "" templatePath = open(os.path.join(settings.MEDIA_ROOT,'synthesis/synthtemplate.html')) template = File(templatePath) mylist = list(template) for l, line in enumerate(mylist): html_string += line I guess there is difference on my local machine and the aws server and maybe i need some minimum os on aws server that i haven't or somethings like pre-requirements system. If you want my hero please help me!:)