Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Physical printing with printer
Is there a framework that Django has (or is compatible with) that can print stuff from its web-based app to physical printers that are connected to the client side. Let's assume one printer per client, and the more simple case: the printing is triggered by human user doing something in the app (though if possible, automatic printing would be cool) . I found an old post with a suggestion here but I don't quite understand it (particularly the manual settings of the browser (Notes, Firefox, Chrome, how and where is this done, what programming language are those code lines written in?). The post also mentioned "connect the printer to the server"? If the app is hosted on a server such as Heroku, or Amazon, etc., how is this possible? -
changing cart items quantity in shopping cart using vanilla javascript
I am building an eCommerce website with Django and I am trying to change the quantity items in my shopping cart using pure javascript. I have been able to select and click on the increase and decrease buttons using a query selector but when I click on any of those buttons only the first item in the cart updates the remaining buttons do not increase the quantity of the items associated with it what should I do? This is the javascript code var minusButton = document.getElementsByClassName("btn minus1") for (var i = 0; i < minusButton.length; i++) { minusButton[i].addEventListener("click", function(event){ var quantity = document.getElementsByClassName("cart-quantity-input") for (var i = 0; i < quantity.length; i++) { var quantity = quantity[i].value-- //console.log(quantity) } })} this is the HTML code <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cart</title> <link rel="stylesheet" type="text/css" href="{% static 'css/cart.css' %}"> </head> <body> <!-- navigation menu --> {% include "topnav.html" %} <div class="maincontent"> <h1 class="hhh1" style="font-size:50px; margin:0px; margin-bottom:30px">Your Cart</h1> <div class="centerblock"> <!-- DYNAMIC CONTENT GOES HERE --> <div class="cart-row"> <span class="cart-item cart-header cart-column">ITEM</span> <span class="cart-price cart-header cart-column">PRICE</span> <span class="cart-quantity cart-header cart-column">QUANTITY</span> </div> <div class="cart-items"> {% for item in items %} <div> <div class="cart-item cart-column"> <img class="cart-item-image" src="{{item.product.imageURL}}" width="100" … -
How to solve 403 forbidden error in django?
Well I am trying delete comment. only the author of comment can delete the comment or remove the comment but on every comment it showing me 403 forbidden. and not removing the comment. views.py def comment_remove(self,request,pk): comment = self.get_object() if self.request.user == comment.author.user: comment = get_object_or_404(Comment,pk=pk) post_pk = comment.post.pk comment.delete() return redirect('posts:post_detail',pk=post_pk) urls.py app_name = 'posts' urlpatterns = [ path('<int:pk>/remove/',views.comment_remove,name='comment_remove'), ] If more detail is require than tell me. I will update my question with that information. -
websocket failed with 'Invalid frame header'
I created a simple chat app and deployed it to AWS EC2. I built the frontend with Vue.js and use javascript's WebSocket. In the backend, I used Django, channels, and Postgres. It works fine on local but WebSocket is disconnected after some time on the server. I used Nginx for deployment. I also set proxy_read_timeout to 600s for the Nginx WebSocket configuration. this.chatSocket = new WebSocket(GlobalConstants.WEBSOCKET_URL + '/ws/chat/' + id + '/') this.chatSocket.onmessage = (m) => { let data = JSON.parse(m.data) let messageData = {} messageData[data.type] = data.message let message = { author: data.sender == this.currentUser ? 'me' : data.sender, type: data.type, data: messageData } this.receiveMessage(message) if (data.sender != this.currentUser) { this.addParticipant(data.sender) } } This is nginx configuration. server { listen 80; server_name x.x.x.x; location / { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_pass "http://127.0.0.1:8000"; } location /ws/ { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_read_timeout 600s; } } Please help me. -
Django login using social account with custom adapter
I am trying to implementing logging in with Google on my django app. However, if a user with the same email as my google account exists it prompts me to a signup page, I would like to create an adapter that if user exists with the social account email, it will show a message that user exists, and if it does exists but it is inactive, it will remove it and login the new user instead. So far I have implemented this: class SocialAccountAdapter(DefaultSocialAccountAdapter): def clean_email(self, email): if Profile.objects.filter(email=email).exists(): if Profile.objects.filter(email=email, is_active=False).exists(): p = Profile.objects.filter(email=email, is_active=False).delete() elif Profile.objects.filter(email=email, is_active=True).exists(): raise forms.ValidationError("A user with this email already exists.") return email def clean_username(self, username): if Profile.objects.filter(username=username).exists(): if Profile.objects.filter(username=username, is_active=False).exists(): p = Profile.objects.filter(username=username, is_active=False).delete() elif Profile.objects.filter(username=username, is_active=True).exists(): raise forms.ValidationError("A user with this username already exists.") return username My intention is that if a user for instance with a gmail is logged in and tries to login but an inactive user with their gmail already exists it will remove the inactive user and login the new user instead. -
Django Sum in Annotate
Good afternoon, I am really struggling with getting a sum using Annotate in DJango. I am using User object and the following models: class Depts(models.Model): dept_name = models.CharField(max_length=55) dept_description = models.CharField(max_length=255) isBranch = models.BooleanField(default=False) def __str__(self): return "{}".format(self.dept_name) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') title = models.CharField(max_length=75) dept = models.ForeignKey(Depts, on_delete=models.CASCADE, related_name="dept", null=True) class ActivityLog(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='activity_user') activity_category = models.ForeignKey(ActivityCategory, on_delete=models.CASCADE, null=True, related_name='activity_cat') activity_description = models.CharField(max_length=100, default="Misc Activity") class ActivityCategory(models.Model): activity_name = models.CharField(max_length=40) activity_description = models.CharField(max_length=150) pts = models.IntegerField() def __str__(self): return '%s' % (self.activity_name) What I need to do is get a group of departments with aggregating the sum of the pts earned by all the users activitylogs. So a user is part of department, they do activities, each activity is of a type activity_category and has associated points. How can I query using the ORM to get a sum of points for everyone in each department? Thank you, I cannot seem to wrap my mind around it. -
Django Compare Foreign Key Value to Attribute of another Model
I'm still relatively new to Django, but I decided to try to build a personal portfolio of personal projects I've worked on. I've set it up so that you land on the home page. From there, you can click on a language. Then if I've used a framework for that language, I want to display it to the screen or if I have a project I did not using a framework in that language, it would be displayed here as well. To do this, I've set up a foreign key from frameworks to languages and from JobNoFramework to Language. I have put in a framework object for Django to test it. If I change the comparison operator to !=, it displays, but as soon as I make it == it doesn't work, even though if I say {{frameworks.language}} - {{languages.language}} I get Python - Python. I'd really appreciate any help. Here's the relevant code: Models: from django.db import models from datetime import date # Create your models here. class Language(models.Model): language = models.CharField(max_length = 30) image = models.ImageField(upload_to='images/') def __str__(self): return self.language class Framework(models.Model): framework = models.CharField(max_length = 30) language = models.ForeignKey(Language, on_delete=models.CASCADE) def __str__(self): return self.framework class JobNoFramework(models.Model): job … -
Make User Profile Visible to All Users Include AnonyMouseUser() on Django
I'm trying to create UserProfileView with user's username in the url. Actually, it works somehow with the actual settings. The issue is, any username extension in the url redirects to the logged in user's profile. And, no info comes to the template when I try to go to profile without signing in. Here's my code, any help is appreciated. models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) email = models.EmailField(max_length=150) bio = models.TextField(max_length=280, blank=True) avatar = models.ImageField(default='default.jpg', upload_to='avatars/') def __str__(self): return '@{}'.format(self.user.username) def save(self): super().save() img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size, Image.BICUBIC) img.save(self.avatar.path) views.py class UserProfileView(SelectRelatedMixin, TemplateView): model = Profile template_name = 'accounts/profile.html' select_related = ('user',) def get_context_data(self, *args): context = super().get_context_data(*args) profile = Profile.objects.filter(user=self.kwargs) context['profile'] = profile return context def get_success_url(self): return reverse('accounts:profile', kwargs={'username': self.object.user.user.username}) urls.py urlpatterns = [ path('<str:username>/', views.UserProfileView.as_view(), name='profile') ] profile.html (how I call the related data in the template) <h3>{{ user.profile }}</h3> <p>{{ user.profile.email }}</p> <p>{{ user.profile.bio }}</p> <h3>{{ profile }}</h3> -
writing data from parent model to another database with django routers
I have models, for example ParentModel and ChildModel where ParentModel is a parent to a child model and those models belong to different apps, for example pm_app and c_app: #pm_app class ParentModel(model.Model): #some fields #c_app class ChildModel(ParentModel): #some other fields and I have django routers in my project. class ParentModel: def db_for_write(self, model, **hints): # some options return 'default' class ChildModel: def db_for_write(self, model, **hints): # some options return 'other_db' When ChildModel is filled with some data so does the ParentModel, but router doesn't work at that moment, default db stays empty, the entry appears in the 'other_db'. So is there a way to resolve this issue? I didn't add the code from the actual project, because I think it is unnecessarily complicated. -
Defining custom signup for django-allauth
I have been trying to user a custom signup form in django-allauth. However, I get the error: django.core.exceptions.ImproperlyConfigured: Module "main.forms" does not define a "SocialAccountSignupForm" class Below is my custom social account form: from allauth.account.forms import SignupForm class SocialAccountSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(SocialAccountSignupForm, self).__init__(*args, **kwargs) def clean(self): email = self.cleaned_data.get("email") username = self.cleaned_data.get("username") if Profile.objects.filter(email=email).exists(): if Profile.objects.filter(email=email, is_active=False).exists(): p = Profile.objects.filter(email=email, is_active=False).delete() elif Profile.objects.filter(email=email, is_active=True).exists(): raise forms.ValidationError("A user with this email already exists.") if Profile.objects.filter(username=username).exists(): if Profile.objects.filter(username=username, is_active=False).exists(): p = Profile.objects.filter(username=username, is_active=False).delete() elif Profile.objects.filter(username=username, is_active=True).exists(): raise forms.ValidationError("A user with this username already exists.") super(SocialAccountSignupForm, self).clean() return self.cleaned_data And in my settings file I have: ACCOUNT_SIGNUP_FORM_CLASS = 'main.forms.SocialAccountSignupForm' I do not understand why this is causing me this error as the class is inside my main/forms.py file. -
Django POST save and delete
I'm attempting to save records into a model using the modelform (this part is working as intended) and delete records from the same model using a checkbox (can't figure this piece out). I am creating a comprehensive view so I'm not creating using a def variable(reqeust, id) function and my intention is to have both POST methods redirect back to the same page. How would I go about deleting a model record using a checkbox and POST? I will add an @login_required decorator later. Here is my code: models.py: class ReportDirectory(models.Model): report_name = models.CharField(max_length=300, unique=True, blank=False) report_desc = models.TextField() report_type = models.CharField(max_length=300) report_loc = models.TextField() slug = models.SlugField(unique=True, max_length=300) last_update = models.DateTimeField(null=True) main_tags = models.CharField(max_length=300) # Renames the item in the admin folder def __str__(self): return self.report_name class Favorite(models.Model): directory_user = models.ForeignKey(User, on_delete=models.CASCADE) user_report = models.ForeignKey(ReportDirectory, on_delete=models.CASCADE) favorited = models.BooleanField() def __str__(self): return str(self.directory_user)+" - "+str(self.user_report) views.py: from django.shortcuts import render,redirect from django.views import generic from .models import ReportDirectory, Favorite from django.contrib.auth.models import User from .forms import FavoriteForm def report_directory(request): favorite = Favorite.objects.filter(directory_user=request.user.id, favorited=True) reports = ReportDirectory.objects.exclude(favorite__directory_user=request.user.id, favorite__favorited=True) favform = FavoriteForm(initial={'directory_user':request.user,},) context = { 'reports':reports, 'favorite':favorite, 'favform':favform } if request.method =='POST' and 'favorited' in request.POST: form = FavoriteForm(request.POST) if form.is_valid(): … -
IntegrityError at /posts/12/new-comment/ NOT NULL constraint failed: posts_comment.author_id
Well i am adding commenting system in my project but got an integrity error. I dont know how to solve this. I have already asked this question one time but now one answer it. But now i am asking it again i hope someone will answer it with brief detail. I shall be very thankful to you. view.py class CommentCreateView(CreateView): redirect_field_name='posts/post_detail.html' model = Comment form_class = CommentForm template_name = "posts/snippets/comment_form.html" def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post,related_name='comments', on_delete=models.CASCADE) body = models.TextField() create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username def get_absolute_url(self): return reverse("posts:post_detail", kwargs={"pk": self.pk}) traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/posts/12/new-comment/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: posts_comment.author_id) was the direct cause of the following exception: File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File … -
Heroku Django Admin returns 'FileNotFoundError at /admin/projects/project/add/'?
I am trying to setup a Django admin page to be able to update my project portfolio directly. Everything works fine until I click on the 'add project' button. Then I'm hit with an error: I do not understand what it is looking for. Any insight would be helpful as I've tried searching google/stack and haven't found a similar issue with a solution. If you need more information, let me know and I'll update my question. -
Django-channels Is it possible to send a message and wait for a response?
There is a very handy way to send a message and wait for a backward message in django-channels testing module: from channels.testing import WebsocketCommunicator communicator = WebsocketCommunicator(app, url) connected, subprotocol = await communicator.connect() await communicator.send_json_to(data=my_data) resp = await communicator.receive_json_from(timeout=my_timeout) Is it possible to write code of real consumer in same style? I mean something like that: class MyConsumer(AsyncJsonWebsocketConsumer): async def some_method(): await self.send_json(some_json) response = await self.receive_json(timeout=some_timeout) # do something with response -
TypeError: 'module' object is not iterable errors occurs when I create my first Django apps
During creating my first apps in Django named 'main' but it gives an error provides below. I check all of the previous answers but not capable to solve my problems. Can anyone help me to solve the issue? Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I create my views … -
Incompatible foreign key when attempting to link tables in Django?
I am trying to make a couple basic models, and link them together with a foreign key. First tool class tool1(models.Model): tool_id = models.CharField( max_length=100, primary_key=True, verbose_name="Tool", ) description = models.CharField( default="", max_length=100, verbose_name="Description", help_text="Describe tool here", ) dateOfAdd = models.DateField( default=datetime.today, verbose_name="Date" ) Referencing tool class Tool2(models.Model): tool1 = models.ForeignKey( Tool, default=None, on_delete=models.PROTECT blank=True ) For some reason the other tools I reference work, but this one will not. I get the following error: django.db.utils.OperationalError: (3780, "Referencing column 'tool1' and referenced column 'tool_id' in foreign key constraint [FK Name] are incompatible.") I cannot figure out why this is happening because the referencing tool is successfully referencing multiple other tools, but it will not link to this one. What is the reason for this error? And how can I fix it so that I can link the tables? -
When running my docker image for my Django project I'm getting a "ModuleNotFoundError: No module named 'try_django'" error
So long story short, I'm trying to use docker to take my Django project to production through Heroku. This is my first ever Django project, first time using Docker as well. Currently I'm getting an error when I try to run my image, this is my first attempt at testing that it runs just fine. I did check that it would run with gunicorn before I put it into the docker image. That worked just fine, although my website didn't look like what it was supposed to, but that's the whole point of docker right? As of right now my website looks just fine with the classic: (try_django) bash-3.2$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2020 - 18:31:48 Django version 2.2, using settings 'try_django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Now I'm just trying to get this project deployed. I can see that the image is created just fine: simple-dj-docker latest 11554361b373 17 minutes ago 1.24GB My next step is to run: docker run -it -p 80:8888 simple-dj-docker In return I get: [2020-10-15 18:13:15 +0000] [6] [INFO] Starting gunicorn 20.0.4 [2020-10-15 … -
How to make my admin_order_pdf function better
I have this function to have a pdf file with orders details but it is not showing all details required in template so I am trying to write the admin_order_pdf function in a better way as it is not generating the full context of the order context. I am not sure whether converting it to a class based view will make it better and even how to do that. Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing----------------> <<-------------------------From here nothing is showing--------------------------> {% for order_item in order.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td> {{ order_item.item.title }}</td> <td> {% if order_item.item.discount_price %} <del>${{ order_item.item.price }}</del> {{ order_item.item.discount_price }} {% else %} ${{ order_item.item.price }} {% endif %} </td> <td>{{ order_item.quantity }}</td> <td>{% if order_item.variation.all %} {% for variation in order_item.variation.all %} {{ variation.title|capfirst }} {% endfor %} … -
__str__ returned non-string (type Product)
I'm getting __ str __ returned non-string (type Product) when I try to add OrderItem in my Django project models.py: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date_ordered = models.DateField(auto_now_add=True, blank=True, null=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return self.transaction_id class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return self.product class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() image = models.ImageField(null=True, blank=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.name) @property def imageUrl(self): try: url = self.image.url except: url ='' return url admin.py: admin.site.register(Customer) admin.site.register(Product) admin.site.register(Order) admin.site.register(Tag) admin.site.register(OrderItem) I get the same error when I try this: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() image = models.ImageField(null=True, blank=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return 'test' Sometimes I get this error when I try to add/delete items (in Orders, OrderItems, Products) -
Django F Date Expresion generated from static field
I am trying to get a series of ages from a persons list, but the age generated change with each query because is the age in a specific event so i can accomplish this with a simple loop, extracting the timedelta from the diference: [ (event_date - user.birth_date).days/365.25 for user in User.objects.all() ] event_date is always a datatime.date object anr user.birth_date too. I consider it a "Static" field or constant because it is outside the database. This gives me the correct results, but since I am doing this many times and i have other calculations to do I wanted to generate the ages from the database using the F() expresion. ``from django.db.models import ExpressionWrapper, fields diference = ExpressionWrapper( event_date- F('birth_date'), output_field=fields.DurationField()) qs_ages= self.annotate(age_dist=diference) this should give me a field named age_dist that will be a timedelta contains the total days between the two dates, so now I should do this and should give me the same result as above. [ user.age_dist.days/365.25 for user in User.objects.all() ] But this does not work, the result is a time delta of microseconds What i am doing wrong? and how should I include the static value of event_date to the expression? And... going beyond. … -
How to filter and get an "object" instead of a "quesryset" in Django Rest Framework
I am trying to filter the users by passing the email_id through URL by passing email_id and getting that particular user. I tried doing this using django-filters but I got a queryset with one object inside it but instead I need the object itself. here's the model - class User(models.Model): """This is the Users model where all users data will be saved""" first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_id = models.EmailField(max_length=100, default="") city = models.CharField(max_length=20, blank=True) state = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=20, blank=True) zip_code = models.CharField(max_length=6, blank=True) mobile_number = models.CharField(max_length=10, blank=True) birthdate = models.DateField(blank=True, null=True) photo_url = models.URLField(max_length=255, blank=True) gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, related_name='user_gender') joined = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.first_name + ' ' + self.last_name I tried using this viewset but it gives me a queryset instead of an object and I coudn't put my mind around on it. class UserFilter(filters.FilterSet): class Meta: model = User fields = { 'email_id': ['iexact'] } class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [DjangoFilterBackend] filterset_class = UserFilter This is the url I am currently passing - http://127.0.0.1:8000/api/v1/users/?email_id__iexact=somemail@gmail.com -
How best to store predictions from machine learning model in Django?
I know Django is well suited for deploying a machine learning model. But all of the tutorials on deploying a machine learning model do not use the standard Django models. When we need to get a prediction, we simply refer to the model as if it were a function, and then we pass the data to the client as a json file. I am satisfied with this option for providing data, if not for a few shortcomings. I will list them below. Let's say that I want to provide the user with filtering data by some parameter. Django provides a model-based filtering mechanism only (tell me if it doesn't). I have no idea how I can filter out a json response that doesn't use serializers and models. My site page should display 200 predictions. These predictions must change every day, but during the day they are unchanged (they depend on today's date). How good is it for performance if every user GET request to that page leads to the machine learning model algorithm being called 200 times? Is there some kind of solution that will allow me to solve these two problems? -
In a Django Rest Framework APIView, using nested serializers for grouping, how can I get only the results that meet all filter criteria?
I have a model of Documents, a model of Authors and a model of Groups. A document must belong to an author and also to a group. So the document model has foreign key constraints to the other two tables. Document model class Document(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='documents') group = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=240, unique=True) description = models.TextField(max_length=999, blank=True) body = models.TextField() active = models.BooleanField(default=True) publication_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Author Model class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=60, unique=True) description = models.TextField(max_length=999, blank=True) Group Model class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=60, unique=True) description = models.CharField(max_length=240, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Then I have my serializers: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = "__all__" read_only_fields = ['user'] def create(self, validated_data): author = Author.objects.create(user=self.context['request'].user, **validated_data) return author class DocumentSerializer(serializers.ModelSerializer): active = serializers.BooleanField(initial=True) author_name = serializers.StringRelatedField(read_only=True, source='author') class Meta: model = Document fields = "__all__" And of course DocumentsByAuthorSerializer which groups Documents by Authors: class DocumentsByAuthorSerializer(serializers.ModelSerializer): documents = DocumentSerializer(many=True, read_only=True) class Meta: model = Author fields = ['id','name', 'documents'] read_only_fields = ['user'] def create(self, validated_data): author = Author.objects.create(user=self.context['request'].user, **validated_data) return author Finally, I have my view … -
Django checkbox for filter
Im having some problem when I want to keep a checkbox checked. When I send the form all the checkbox are checked. so idk how to change the if statement for that :( <div class="form-group"> <label >Marca</label> {% for brand in q %} <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="{{brand.brand}}" name="test" value="{{brand.brand}}" {% if marca %} checked="checked" {%endif%}> <label class="custom-control-label" for="{{brand.brand}}" style="cursor: pointer;">{{brand.brand}}</label> </div> {% endfor %} </div> And here is the view: marca = request.GET.get('test') if marca : products = products.filter(brand__name__in=request.GET.getlist('test')) All the other things are fine. It shows me the brands that I choose. So I just want to keep the checkbox that I checked :( and I think the problem is that If statement in the template -
Uploading image in Django returns error "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte"
So I have a nested serializer and I'm trying to upload an image, the image there but when I try to set it to use it on the serializer I'm getting the error. My code: models.py class Pet(models.Model): pet_id = models.UUIDField('pet uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) name = models.CharField('Pet name', max_length=255, null=False, blank=False) class Attachment(models.Model): attachment_id = models.UUIDField('attachment uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) pet_id = models.ForeignKey(Pet, on_delete=models.CASCADE) name = models.FileField(upload_to='photos/', null=False, blank=False) upload_at = models.DateTimeField('Time it was uploaded', max_length=50, null=False, blank=False ) serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = ('name','upload_at') class PetSerializer(serializers.ModelSerializer): attachments = AttachmentSerializer(many=True) class Meta: model = Pet fields = ('pet_id','name', 'attachments') def create(self, validated_data): attachments = validated_data.pop('attachments') pet = Pet.objects.create(**validated_data) for att in attachments: Attachment.objects.create(pet_id=pet, **att) return pet views.py parser_classes = (MultiPartParser, FormParser) def create_pet(self, request): img = BytesIO(request.FILES.get('file_1').read()) img.seek(0) data = Image.open(img) new_data = request.data.copy() new_data['attachments'] = [{'name':data, 'upload_at':datetime.now()}] serializer = self.get_serializer(data=new_data) if not serializer.is_valid(): return Response({'error':serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response({'data':serializer.validated_data}, status=status.HTTP_201_CREATED) but I'm getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Any thoughts about this? Thanks in advance.