Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Encrypt FileField with Fernet object has no attribute '_committed' occurred
I am passing multiple pdf uploads into the view from a form. (using Uppy.XHRUpload) I want to encrypt them before saving them in the model. When i test the files they can be encrypted and saved to a file and then read and decrptyped just fine. But when I try to add to the model I get: 'bytes' object has no attribute '_committed' occurred. I can download enctryped file, re-read and then save but that would be a waste. I thought it would be as simple as: if request.method == 'POST' and request.FILES: files = request.FILES.getlist('files[]') for index, file in enumerate(files): f = Fernet(settings.F_KEY) pdf = file.read() encrypted = f.encrypt(pdf) PDF_File.objects.create( acct = a, pdf = encrypted ) The Model. class PDF_File(models.Model): acct = models.ForeignKey(Acct, on_delete=models.CASCADE) pdf = models.FileField(upload_to='_temp/pdf/') Thanks for your help. -
Cannot access or find django many to many object after creating
I have had to merge two functions in my Django app due to an API upgrade. Formerly had one function create all of the objects, and the second function access said objects via .get() and .filter() etc. Now, I've had to merge the two, and I've run into issues accessing those created objects. order = Order.objects.create( user=user, date_created=datetime.datetime.now(), ) item = Item.objects.create( info=info, order=order, ) item.save() print(order.item_set.all()) #this is a blank array, where it used to be an array of items print(Items.objects.filter(order=order)) #this is a blank queryset, where I would expect it to be full of created items Any idea what I can do to make the print statement have items in it once again? I have tried to do order.item_set.add(item) but it did not work. -
Django ORM filter by lowercase only
How do I use Django ORM to filter objects that only show the lowercase only? For example in my case, I want to update all emails that has "non-lowercase" objects to "lowercase". from django.db.models.functions import Lower User.objects.exclude(email__islower=True).update(email=Lower("email")) /|\ | -
how to replace gunicorn with Nginx
I have an existing project that use G-unicorn because its deployed on lynx . but when I install on my windows local machine some of the API calls doesn't work due to Cors_allowedstrong text not allowed which I assume is caused because there is no G-unicorn any suggestion how to fix this on windows ? -
django channels , rejected request from client when added new header to the request
I need to add new header to the websocket request, but it get rejected and disconnect before even execute the connect method in the WebSocketConsumer class : class RecordConsumer(WebsocketConsumer): def connect(self): user = self.scope["user"] print(user.is_authenticated) header_name, header_value = self.scope["headers"][-1] print(header_name, header_value) print(header_name.decode("utf-8") == "issurvey" and header_value.decode("utf-8") == "true") if user.is_authenticated: self.room_group_name = "test" async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() elif header_name.decode() == "issurvey" and header_value.decode() == "true": self.room_group_name = "test" async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() else: self.close() I have custom middleware for authenticating using token to be able to connect from mobile device : from channels.auth import AuthMiddlewareStack from channels.db import database_sync_to_async from django.contrib.auth.models import AnonymousUser from rest_framework.authtoken.models import Token from urllib.parse import parse_qs @database_sync_to_async def get_user(token_key): try: token = Token.objects.get(key=token_key) return token.user except Token.DoesNotExist: return AnonymousUser() except KeyError: return AnonymousUser() class TokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): return TokenAuthMiddlewareInstance(scope, self) class TokenAuthMiddlewareInstance: """ Yeah, this is black magic: https://github.com/django/channels/issues/1399 """ def __init__(self, scope, middleware): self.middleware = middleware self.scope = dict(scope) self.inner = self.middleware.inner async def __call__(self, receive, send): decoded_qs = parse_qs(self.scope["query_string"]) if b'token' in decoded_qs: token = decoded_qs.get(b'token').pop().decode() self.scope['user'] = await get_user(token) return await self.inner(self.scope, receive, send) def TokenAuthMiddlewareStack(inner): return TokenAuthMiddleware( AuthMiddlewareStack(inner)) I added this middleware … -
Python Deployment in google cloud platform
My django app using sendgrid for sending mail. Its work locally fine. After deploy it in cloud. It shows import error sendgrid -
Django Operational Error : No Such Column
I have a test case using Django MigratorTestCase. Previously the test case was working fine but then I had to add a column called updated and I made migrations to the project but ever since then the unit test case has been failing and I am not sure why. When ddebugging the code I have realized that the error is from the line assign_perm("delete_dataset", self.user1, self.d1) in Unit Test Case I apologize if I posted a bunch of unnecessary info. Thanks in advance guys. Unit Test Case: class DatasetPermissiontestCase(MigratorTestCase): migrate_from = [ ("guardian", "0002_generic_permissions_index"), ("project", "0037_dataset_public"), ] migrate_to = ("project", "0038_update_dataset_permission") def prepare(self): Dataset = self.old_state.apps.get_model("project", "Dataset") ctype = get_content_type(Dataset) ctype.save() Permission.objects.bulk_create( [ Permission(codename="change_dataset", content_type=ctype), Permission(codename="delete_dataset", content_type=ctype), Permission(codename="view_dataset", content_type=ctype), ] ) self.user1 = User.objects.create_user(username="a") self.d1 = Dataset.objects.create(name="d1") assign_perm("delete_dataset", self.user1, self.d1) def test_permission_updated(self): self.assertSetEqual( set(["delete_dataset"]), set(get_perms(self.user1, self.d1)), "permission should get updated after migration", ) Exception Stack Trace: E ====================================================================== ERROR: test_permission_updated (project.tests.DatasetPermissiontestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Anaconda3\envs\project\lib\site-packages\django\db\models\query.py", line 573, in get_or_create return self.get(**kwargs), False File "C:\Users\admin\Anaconda3\envs\project\lib\site-packages\django\db\models\query.py", line 431, in get self.model._meta.object_name guardian.models.models.UserObjectPermission.DoesNotExist: UserObjectPermission matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\admin\Anaconda3\envs\project\lib\site-packages\django\db\backends\utils.py", line 84, in _execute … -
Using annotated value again in a Django queryset
In this annotation, I'm creating a value ever_error that is 1 if for any unique 'image__image_category__label', 'image__subject', 'image__event' combination and 0 otherwise d = ImageAcquisitionJob.active_objects.values('image__image_category__label', 'image__subject', 'image__event')\ .annotate( ever_error=( Max( Case(When(has_error=True, then=Value(1)), default=Value(0), output_field=IntegerField()) ) ) ) Now, my objective is to make a new annotation that sums up the ever_error attribute for each 'image__image_category__label' d = d.values('image__image_category__label').annotate(has_error=Sum('ever_error')) This is not possible however because I get the error: Cannot compute Sum('ever_error'): 'ever_error' is an aggregate The core of my problem is that I need to use the first annotation again as a regular field but this isn't permitted. Is there a way to save the annotated field so that I can use it again? -
Using non-AWS S3 storage with Django?
I have an S3 storage which is not hosted by AWS. I tried my AWS account as a file-storage, which worked fine, however, when I switch the credentials to the non-AWS provider I get: botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden in the django logs, and ClientError at /admin/api/metabolomicsmzxml/add/ An error occurred (403) when calling the HeadObject operation: Forbidden displayed in the browser. I use django-storages with the following configuration:q : AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWSS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = 'ca-central-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_VERIFY = True AWS_ENDPOINT_URL = 'example.com:443' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Is it possible to use django-storages and boto3 with a non-AWS provider? Are there other packages that I should try? -
Var inside of object attribute [duplicate]
i got these code `{%for number in List %} <div class="top"> <h3> <a href="/my-blog-post">{{songs.history.0.Song}}</a> </h3> <section> <p>{{number}}Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec viverra nec nulla vitae mollis.</p> </section> <footer> <small> Posted on <time datetime="2017-04-29T19:00">Apr 29</time> in <a href="/category/code">Code</a> </small> </footer> </div> i want that the number of the {{songs.history.0.Song}} change with the var of the loop but when i change it to {{songs.history.number.Song}} the element a dont appear the thing is that i want that the number change automatic -
Update databate when user click at a checkbox
I made a model to control the existence of a specific list of customer documents. models.py class PersonalDocumentation(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='Project') cnd = models.BooleanField(default=False, verbose_name='CND proponente') producer_registration = models.BooleanField(default=False, verbose_name='Inscrição de produtor rural') sales_invoices_agriculture = models.BooleanField(default=False, verbose_name='Notas de comercialização agrícolas (3 anos)') sales_invoices_livestock = models.BooleanField(default=False, verbose_name='Notas de comercialização pecuária (5 anos)') rg = models.BooleanField(default=False,verbose_name="RG") cpf = models.BooleanField(default=False, verbose_name='CPF') wedding_certificate = models.BooleanField(default=False, verbose_name='Certidão de casamento') rg_spouse = models.BooleanField(default=False, verbose_name='RG conjuge') cpf_spouse = models.BooleanField(default=False, verbose_name='CPF conjuge') I would like to show this data in checkbox format and for the database to be updated when user check/uncheck some item. The only way I encontered to do this is making one url for each document I started to think that maybe the model I created is not the best option. And maybe making just one field with a list of documents owned by the client is better. -
What is MyModel.objects in Django?
I am following a beginner's Django course in which I am up to the level of creating models and inserting data into the tables. I have created the following model: from django.db import models # Create your models here. class Names(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) In the shell I do: elvis = Names.objects.create(first_name="elvis", last_name="prestley") This successfully creates a database record. I want to know the logic behind Names.object.create() - "Names" is a class I have created which inherits the Models class but I am not sure where the ".object.create()" part comes from? -
How to solve "'int' object is not subscriptable" in Django from a Kraken API
I was wondering what the correct way is to save a number in Django SQLite coming from a Kraken API, when there is an Array of Array of strings or integers (https://docs.kraken.com/rest/#operation/getOHLCData). my views.py from rest_framework import generics from .serializers import KrakenSerializer from krakenohlc.models import Krak import requests class KrakenList(generics.RetrieveAPIView): serializer_class = KrakenSerializer queryset = Krak.objects.all() def get_object(request): url = 'https://api.kraken.com/0/public/OHLC?pair=XBTEUR' response = requests.get(url) data = response.json() for i in data['result'].values(): kraken_data = Krak( time_0=(i[0][0]), ) kraken_data.save() my models.py from django.db import models class Krak(models.Model): time_0 = models.IntegerField(blank=True, null=True) def __str__(self): return self.time_0 This is the error that i get in the browser: The SQLite response is actually saving the API number in the database: I researched and tried thoroughly many similar cases here, but none had the example of an API response with this error message. -
Adding external javascript snippet to a Wagtail page field
My current Wagtail project has a very simple structure with some generic pages that have just a body RichTextField. These are just basic CMS type pages where an editor will edit some content in the rich text editor and publish. One of the pages (and probably more in time) is a "Help Wanted" page and uses an external javascript snippet from a third-party service that lists current job openings with links to the applications that are hosted by them. Since adding a <script> tag to the rich text editor simply escapes it and displays only the text value, I added an additional extra_scripts = models.TextField() to my page model along with a corresponding FieldPanel('extra_scripts') to the content panels. This lets a user paste in some arbitrary javascript snippets. If I include this field value in my template with {{page.extra_scripts}} it just displays the content and does not execute the javascript. Looking through the available wagtailcore_tags I'm not seeing a filter that I should use to execute the content, and when it's used with a {{}} tag, I presume the template engine handles it so that it doesn't execute. How can I include this field in a template so that the … -
WebSocket like grouping for SSE in Django
I have a Django website and I have a real-time "game" on it. Multiple people connect and play it. Every x seconds the users in the specific game will be getting updates. I have done this using WebSockets and it works, I would say, pretty good. The things I think that using WebSocket-s is an overkill, plus I'm not utilising the Bi-directional part of it, rather using it to get the updates from the server and using AJAX to send the data. I'm considering switching over to Server Sent Events. I've used it a bit and read about it online and have decided that it would be a good fit for my project (using it instead of WS). The "problem" that I have is that I'm not sure how to (I assume its possible) to use something like a groups in ws. I've searched online and the best solution that I could find is doing the client side filtering, which although its totally fine, I do not prefer as I think it's a waste of resources. The way that I have it set up is that based on the url for the game, the users that are connecting would be … -
Django-allauth - is there a way to automatically send an email after account is verified
We recently took over a project that was developed in Django, which uses allauth. We are hoping to send out some additional information to users once they have signed up and confirmed their email address, is there a default/native way to do this in django-allauth? At the moment the system uses email_confirmation_message.txt to configure the email for users to confirm their email address, but we couldn't find something similar once the account is confirmed. -
How to effectively count multiple nested children in a Django model?
I have the following data model (the database backend is PostGres): class User(models.Model): ... teams = models.ManyToManyField('Team', blank=True, related_name='all_users') ... class Team(models.Model): ... parent_team = models.ForeignKey('self', blank=True, null=True, related_name='child_teams') ... So a User can belong to multiple Teams, and the Teams can be nested in each other to varying degrees of depth. I'd like to count all Users within a given team and all its children, including nested children. Right now, I am doing it recursively, which doesn't seem like the most efficient way to go. Is there a better way to go about it? -
Cant login to created user after using custom model
from django.db import models from django.contrib.auth.models import AbstractUser,User from django.utils.html import escape,mark_safe # Create your models here. class user(AbstractUser): is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) def login_view(request): form = AuthenticationForm() if request.method=='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username,password=password) if user.is_admin==True: login(request,user) return HttpResponse(f"Welcome {username}") else: return HttpResponse('failled') return render(request, 'login.html', {'form': form}) cant login using the user created by superuser. the user is creating but while calling it or using it shows created a user with staff and superuser authorization still cant login -
How can I get Followed/unfollowed count of a user last 24 hours from Twitter using Tweepy with python
How can I get user followed/unfollowed count of last 24 hours from Twitter using Tweepy with python. I have essential access of twitter api v2. I have read the tweepy documentation but there is no query of filter follow/unfollow count from last 24 hours. -
How can I create a user in Django?
I am trying to create a user in my Django and React application (full-stack), but my views.py fails to save the form I give it. Below the code. # Form folder def Registration(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] User.objects.create( email = email , username = username, password = password, ) user = form.save() login(request,user) return redirect('/profile/') else: context = {"Error" : "Error during form loading"} return render(request,'accounts/registration.html',context=context) return render(request,'accounts/registration.html',context=context) And that's my Forms.py class UserForm(UserCreationForm): username = forms.TextInput() email = forms.EmailField() password = forms.TextInput() password2 = forms.TextInput() class Meta: model = User fields = ("username", "email", "password", "password2") def save(self, commit=True): user = super(UserForm, self).save(commit=False) if self.password != self.password2: raise forms.ValidationError('Input unvalid') elif commit: user.save() return user -
Django NameError: name ' ' is not defined
I am trying to create a view that filters blog posts by topic, to I added a field in my post form called "topic" and, I created a view: And I defined the path in urls.py: I get this error in Terminal: model = Post template_name = 'blog/political_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(topic=Political).order_by('date_posted') ``` ``` path('politics/', PoliticalPostListView.as_view(), name='political-posts'), ``` I used a template from a working user_posts.html to test: ``` {% extends "blog/base.html" %} {% block content %} <h1 class="md-3"> Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> <small class="text-muted">{{ post.topic }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} ``` File "/Users/leaghbranner/Desktop/django_project/blog/urls.py", line 21, in <module> path('politics/', PoliticalPostListView.as_view(), name='political-posts'), NameError: name 'PoliticalPostListView' is not defined And "This Site Cannot Be Reached." pagein my browser. Any thoughts? -
How to create a super user in Django using react signup application
I am trying to create a superuser or regular user by creating react signup application and I want to know the correct way to do this. -
How to prevent different user types to view each other dashboard in django
I have a website with 3 user types, admin, instructor and students, I used login mixing to redirect each of them to their respective dashboard but if the student modify their url to /instructor or /admin ; it will give them access to the page; I want to restrict student to only student page and admin to only admin page. I tried writing the function If user.student.is_authenticated: class Student_dashboard(): ...... However it's not restricting them -
Using Ajax to update a table on a page in django
I am trying to the table in my all-reviews whenever someone checks one of the filters at the top using ajax. However, when a filter is checked it is getting the entire page back including things like the navbar and then updating the table with the entire page data instead of just the filtered reviews. The issue I believe is with my view since its rendering the all-reviews.html page but I cannot figure out how to do it properly where the returned data doesn't include the navbar and other unneeded information that is imported into my base.html. Lastly, I am trying to make it so that if they click a filter, it loads the new data, but then if they uncheck the filter, or check a different one the data is refreshed again. Currently after the first time a filter is checked nothing happens if subsequent filters are checked or unchecked. base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{% endblock %}</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static "app.css" %}" /> {% block … -
Use login tables created by Django from NestJS/NodeJS service
We have the secrets and the source code from Django project (this is not a hack topic) this is a topic about the posibility of use Django generated tables for Users Login BUT from NodeJS/NestJS service. The goal is kickout Django, and keep existing users to generate same JWT tokens from encrypted password coming from users table generated by Django.