Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make messages showed up in the template
i have a login django app where i am trying to inform user in if they have wrong credentials or if they are successfully login. the problem is that i used the message framework in django but it did not showed up in the template. views.py from django.contrib import messages def login_request(request): if request.method == "POST": username = request.POST['lognName'] password = request.POST['lognCode'] user = authenticate(username = username,password = password) if user is not None: login(request,user) messages.info(request,f"You are now logged in as {username}") return redirect("main") else: messages.error(request,"invalid username or password") return render(request,'login.html') login.html {% if messages %} {% for message in messages %} <script>M.toast({html:"{{message}}",classes:'blue rounded',displaylength:2000});</script> {% endfor %} {% endif %} even if i tried to used outside the if statement the toast doesn't work -
How to get app name in Django within its api file?
Without any hard coding, I want to derive my django app name within its apis. for eg: mysite_apiV1_someapi.py or mysite.apiV1.someapi.py. Here mysite is my app name in the django project. It is not the django project name. apiV1 is the folder, made by me, containing all apis like ApiOne.py,ApiTwo.py, someapi.py and so on. someapi.py is my api file which contains logic and I have to get here my django app name,api folder name and api file name in the above mentioned format. -
Django annotate returns result in memory
I've the following call in Django: Activity.objects.values('user_field__username').annotate(Sum('reward')) Given below is the schema of my "Activity" table: User (foreign key to user model) Reward Each user can have around dozen entries in this table. There can be 10 million users. I want to get the total reward of each user and send notification to all such users at one time. The above query satisfied my requirement but i was told that its suboptimal and would have huge space complexity. What's the right thing to do in principle. -
Why QuesrySet return TypeError
When I makemigration/migate/get from shell - except in my API queryset: models.py class NewsManager(models.Manager): def get_queryset(self): locale = get_language() return super().get_queryset().annotate(title=F('title_' + locale), body=F('body_' + locale), short_description=F('short_description_' + locale), seo_title=F('seo_title_' + locale)) class News (models.Model): class Meta: verbose_name = _('Новини') ordering = ("-created_at",) title_uk = models.CharField(max_length=255, blank=False) title_en = models.CharField(max_length=255, blank=True) seo_title_uk = models.CharField(max_length=255, blank=True) seo_title_en = models.CharField(max_length=255, blank=True) short_description_uk = RichTextField(blank=False) short_description_en = RichTextField(blank=True) body_uk = RichTextField(blank=False) body_en = RichTextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) published = models.BooleanField(default=False) objects = NewsManager() api/views.py class NewsAPIView(generics.ListAPIView): """ list: Return a list of all news """ serializer_class = NewsPreviewSerializer def get_queryset(self): return News.objects.all().exclude(published=False) class NewsDetailAPIView(generics.RetrieveAPIView): """ get: Return one News obj by id """ serializer_class = NewsSerializer queryset = News.objects.all() lookup_field = 'id' TypeError: must be str, not NoneType return super().get_queryset().annotate(title=F('title_' + locale), body=F('body_' + locale), -
Django AES Encryption : how to decrypt files when they are sent to the user?
I want to decrypt files in django when sending them, but keep only the encrypted version on the server. How can I decrypt the files when sending them ? I currently use pyAesCrypt to decrypt files but it replaces the file or create a new one that I have to delete after, and as I think I have to send the response with the file I don t see when I can delete de decrypted version of the file on the server (except deleting it at a later time) This is what I do for a request for the file : import pyAesCrypt from os import stat with open("*FilePath*", "rb") as InputFile: with open("*OutputFilePath*", "wb+") as OutputFile: pyAesCrypt.decryptStream(InputFile, OutputFile, Password, BufferSize, stat(InputFile).st_size) response = HttpResponse(Model.File, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
Django & React: How to censor columns when user is not logged in
I am using Django as my CMS and React for my Frontend. For the API I am using Django REST framework. In Django I have a model like this: class person(models.Model): number = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) I would like to censor some columns depending on if the user sent me the correct Authentification Token or not. So in result I would like to have something like { "number": 1, "name": "johnny", "last_name": "miagi"} when the user is authentificated, and { "number": 1, "name": "johnny", "last_name": "########"} when not. Is this possible? I am, unfortunately, a beginner in Django. I know about the user privileges system, but as far as I know this is meant to be used on complete tables, not columns. -
How to find nearby machines from a given coordinate while all the machine coordinates are in the database?
I am creating a website where a specific machine owner can upload the machine for renting or selling. In the process I am also saving his shop's coordinates in the database. Now if any costumer wants to by the machine, I want to take his coordinates and classify the nearest shops with the machine available. Also please tell me the resources I need to use. Currently I am using Django for backend development. -
Django AES Encryption : how encrypt user-uploaded files before they are saved?
I want to encrypt user uploaded files in django before saving them. When user send files through POST requests, I get a "InMemoryUploadedFile" type object. How can I encrypt the files before saving them ? I currently use pyAesCrypt to encrypt files but I can't manage to pass in it the "InMemoryUploadedFile" objects. I manage to only encrypt them after they are saved with : import pyAesCrypt with open("*FileName*", "rb") as InputFile: with open("*OutputFileName*", "wb+") as OutputFile: pyAesCrypt.encryptStream(InputFile, OutputFile, Password, BufferSize) -
How to handle field-level permissions and return only allowed fields from serializer?
Ok, first off, I've read the docs on DRF permissions, all hits I've found here in SO, and in Google-land. I'm trying to return only the fields a user can view based on field-level permissions. I've seen examples of how to dynamically modify the "fields" attribute of a serializer in the __init__ method, and that seems like the best place to do what I need to do. But during the process of getting the current user's permissions, I need to raise an exception if the user is invalid or has no permissions at all. The problem is that __init__ seems to be executing during a request even if the request is not the endpoint that __init__ code is for. Here's my serializer: class ClientSerializer(AddressPhoneSerializerMixin, serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="clients:client-detail") contacts = ClientContactsSerializer(many=True, read_only=True) projects = ClientProjectsSerializer(many=True, read_only=True) project_users = ClientProjectUsersSerializer(many=True, read_only=True) class Meta: model = Client fields = ( 'url', 'id', 'name', 'slug', 'status', 'address', 'country', 'phone_number', 'mobile_number', 'fax_number', 'created', 'updated', 'deleted', 'contacts', 'projects', 'project_users', ) def __init__(self, *args, **kwargs): super(ClientSerializer, self).__init__(*args, **kwargs) self.check_permissions() def check_permissions(self): permissions = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user permissions = UserPermissionsList(user.id) if not permissions or permissions is None: raise … -
What is the recommended way to break long if statement? (W504 line break after binary operator)
What is currently the recommended way to break long line of if statement with "and" and "or" operators? 1st option With the style below (which is from PEP8) with flake8 I'm getting warnings: W504 line break after binary operator: if (this_is_one_thing and that_is_another_thing): do_something() 2nd option if (this_is_one_thing and that_is_another_thing): do_something() Now I'm getting the warning W503 line break before binary operator. The second seems to be in line with this recommendation from PEP8 I tried to find answer but I'm still unsure. I think maybe using 2nd option and disabling W503 warning will be a way to deal with this problem? -
safe template tag in django admin
I am using django-grappelli as django admin template. But I want to use {{foo|safe}} for a particular entry from my database which I made using CKeditor, which is being displayed in admin template. I know how to use safe tag in templates but I don't to how to use them in admin site.I apply safe tag to field .Thanks. -
Django polls app is not working as expctected in the tutorial for me
I am getting this error every time restart my server Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. I have tried restarting the server but the same error is popping up every time. polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), ] mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls) ] views.py/polls from django.http import HttpResponse def index(request): return HttpResponse("Hello world. You're at the polls index.") The expected result as per the Django tutorial is the text "Hello world. You're at the polls index." after you start your server -
Emulate Oracle primary key in Django's unmanaged model
I am working on a legacy project (Django 1.7, DRF 2.0 and Oracle 11.2) I would like REST API to retrieve and populate a pre-existing Oracle table, which I have defined as this Model: class ParametriZgodovina(models.Model): amp_sif = models.CharField(max_length=5, blank=True) kolicina = models.CharField(max_length=20, blank=True) datum_od = models.DateField(blank=True, null=True) id_np = models.FloatField(blank=True, null=True) opomba = models.CharField(max_length=1000, blank=True) opomba_user_id = models.FloatField(blank=True, null=True) opomba_datetime = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'parametri_zgodovina' As I was getting DatabaseError: ORA-00904: "PARAMETRI_ZGODOVINA"."ID" invalid identifier, I inserted another field into my model definition: rowid = models.CharField(max_length=20, primary_key=True) This allowed me to retrieve and even modify data, but inserting new instances via .restore_object() fails with DatabaseError: ORA-01733: virtual column not allowed here. What's more, when trying to explicitly print model instances in View's get() method by using print(instance.values()), I got the DatabaseError: ORA-01446: cannot select ROWID from, or sample, a view with DISTINCT, GROUP BY, etc. My view looks like this: class ParametriZgodovinaView(APIView): def get(self, request): events = ParametriZgodovina.objects.all().order_by('amp_sif', 'kolicina','datum_od') serializer = ParametriZgodovinaSerializer(events, many=True) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def post(self, request): serializer = ParametriZgodovinaSerializer(data=request.DATA, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And my Serializer is: class … -
Efficient storage of Json in Django with postgres
I need to store json files with models in my django app and I'm wondering whether JSONField is my best choice or not. All I need is to store it for later, no searching or other querying is needed other than when I eventually need to retrieve it again. I'm using postgresql if that matters. -
Django user form with google maps location picker
I am hoping for some guidance as I am new to both django and coding. I want to create a front-end django form that will allow the user to select a location on a map, along with other fields and save it directly to a model. All recourse i have found are for the admin not the user input. A tutorial or some reading material would be great -
Make readable the post only if the user is staff
I'm developing the backend of my blog and I need to make a difference between the typology of posts: published, future post, draft. For do this I'm started with the indications comes inside my past request: Create a restricted area Django: put offline a post after an event After I've realise that all the typology of posts are always online thanks this solution I can put online only the published posts. In my blog there are two typology of users: is_staff(the default Django typology), is_user(it is inside my registration model). There is another typology that is the anonymous user, the users without any type of registration that arrive on my blog using Google or another solution. Therefore I've developed a view that show the draft and the future posts only if the user is is_staff but I see the Forbidden error. def singlePost(request, slug_post, slug_category): post_category = get_object_or_404(BlogCategory, slug_category=slug_category) post_filter = BlogPost.objects.filter(draft=False, publishing_date__lt=datetime.datetime.now()) if not request.user.is_authenticated: post_filter = BlogPost.objects.filter(draft=False, publishing_date__lt=datetime.datetime.now()) raise PermissionDenied elif request.user.is_user: post_filter = BlogPost.objects.filter(draft=False, publishing_date__lt=datetime.datetime.now()) raise PermissionDenied else: post_filter = BlogPost.objects.all() post_details = get_object_or_404(post_filter, slug_post=slug_post) category_post_details = BlogPost.objects.filter(post_category=post_category) context = { "post_category": post_category, "post_details": post_details, "category_post_details": category_post_details, } template = 'blog/reading/single_post.html' return render(request, template, context) How I … -
Why do I get a Reference Error: 'next()' is not defined, even though next is defined in my Javascript?
I have a javascript function named next() and it's meant to process information. Also, I call the function from the HTML. However, my firefox console returns a ReferenceError: 'next' is not defined. I know I'm doing something wrong, but I don't know what it is. I'm also taking suggestions about how to better write the code. I'll be happy to incorporate your ideas. Also for clarification, I want the button to make an ajax call to the Django backend and change the text on the screen. I have tried setting the form action to javascript: next(), but no avail also. <form> <input class='btn btn-primary ml-auto' onclick="next()" id="next_button" type="button" role='button' value='Next'> </form> count = '{{ question.id }}'; function next() { count++; $.ajax({ url: '{% url "next_question" %}', type: 'GET', dataType: 'json', data: { 'question_id': count }, success: function(data) { document.getElementbyId('question').innerText = data.fields.question; console.log(count); } error: function() { $('#next_button').disabled = true; alert("Either that's the last question or an error occured!"); } }); }; if (confirm('Are you ready to start the test?')) { timer(10); } else { window.location = '{% url "Home" %}' }; I expect the text to some text to change or at least not to get the ReferenceError: next() is … -
Django-Tables2: Is there a possibility to access from one table from one model to another related?
I have two models, described below, related to each other, I would like to show the different occurrences of one of the models in the table of the other model. This is for Django#2.2 with djanto-tables2 plugin. # models.py class Example1(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=250, blank=False) class Example2(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=250, blank=False) example1 = models.ForeignKey(Example1, on_delete=models.CASCADE) #tables.py class Example1Table(tables.Table): title = tables.Column(verbose_name=_('Título')) # I want here a column to show all Example2 related with this Example1 object class Meta: model = Example1 exclude = [] -
Where should I store Email templates
When a particular event occurs, I send an email to the client. There are multiple events and each event has a different email-template. I don't want to store the template in my code, as I want to avoid code release every time I add a new template. Where and how do I store the templates? I currently am considering storing them in the database. But if I want to change the template format, it will be difficult. Is there a better way to do it? I am using django1.9 and python3 . -
Django registration with groups: Group matching query does not exist
I'm trying to allocate groups permissions in my register form, but I get this error: Group matching query does not exist. forms.py: class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', ) views.py: def registerView(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name='group_name') user.groups.add(group) return redirect('accounts:users') else: form = RegisterForm() return render(request, 'accounts/register.html', {'form': form}) The error occurs at group = Group.objects.get(name='group_name'). No idea how to fix it -
Django user serializer with one-to-one related object
I would like to serialize User object with model related to that, I would like to make a list where I can see the users and also want to be able to create new users and get urls for these apis. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) UP_Unit_ID = models.BigIntegerField(blank=True, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() serlializers.py class UserProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') class Meta: model = UserProfile fields = [ 'username', 'language', ] views.py class UserProfileCreateAPIView(CreateAPIView): model = UserProfile serializer_class = UserProfileSerializer urls.py urlpatterns = [ url(r'^$', UserProfileCreateAPIView.as_view(), name='post-listcreate'), ] -
LInk ManyToManyFiled with the corresponding Model API
I am having two models "Book" and "Authors". I am having Author details in "Author" model. I am creating "Books" by using API. I want to link the "Author" with "Book" using "Author_id". I have tried following code. models.py: class Author(models.Model): name = models.CharField(max_length=64) class Book(models.Model): name = models.CharField(max_length=64) author = models.ManyToManyField(Author,related_name='author') views.py class BookListView(APIView): def post(self, request, format=None): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('name', ) class BookSerializer(serializers.ModelSerializer): assessments = AuthorSerializer(many=True, required=False) class Meta: model = Book fields = ('name', 'authors') def create(self, validated_data): print(validated_data) authors = validated_data.pop('authors') book = Book(**validated_data) book.save() return book I am having following Authors in "Authors" table. id name 1 Alex 2 John 3 Bob Sample JSON FIle for creating Book: { "name":"Product 002", "authors": [ { "author_id":2 }, { "author_id":1 } ] } The following error will comes while saving book. { "authors": [ { "name": [ "This field is required." ] }, { "name": [ "This field is required." ] } ] } Please Help me to solve the problem. Thanks in Advance -
How to fill nested dictionary with values of a Queryset in Django
I have a a dictionary like this: result = { 'year' : {} } and I have a queryset like this: <QuerySet [{'building_id': 1, 'year': 2019, 'demand': 123.34}, {'building_id': 1, 'year': 2019, 'demand': 345.0}, {'building_id': 1, 'year': 2019, 'demand': 12345.0}, {'building_id': 2, 'year': 2019, 'demand': 345.0}]> Now I would like to transform the values of the queryset into the nested dictionary so that it looks like so: result = { 'year' : {'1' : [123.34, 345.0, ...], 2 : [345, ...] } I get my queryset like this, so it is currently within a loop: for item in buildings: demand_cool_item = item.demandcool_set.filter(year=passed_year).values('building_id', 'year', 'demand') For starters I was trying to loop through the queryset push it to an array and then update the dict within the dict like so: demand_cool_list = [] for item in buildings: demand_cool_item = item.demandcool_set.filter(year=passed_year).values('building_id', 'year', 'demand') demand_cool_list.append(demand_cool_item) for item in demand_cool_list: result.update(item) tried also ``` result.update(item['building_id']['demand'])```` That said that dictionary update sequence element #0 has length 3; 2 is required or that I have a Type Error. ! Can someone land me a hand on this? Highly appreciated! Thanks in advance -
"No module named <module name>" Error on django
I'm working on a project and I'm facing this issue. i wanted to make an import from some folder but it always throws an exception. here is my files structure: \myWebsite \childWebsite \importedClass \myWebsite(same name as the parent) \classThatCallsTheImportedClass so my call is as following: from myWebsite.childWebsite.importedClass import someFunction However, it always throws an error: "No module named 'myWebsite.childWebsite'" I discovered that when executing the call line, django checks the files inside the child "myWebsite" folder and hence it can't find the "importedClass". So, how i make it checks the parent "myWebsite"? -
why is this code not working--django paginate
I'm trying to paginate a page in order to display 1 status per page...it fails to paginate and it doesn't display the link to the next pages views.py def post_list(request): posts= Post.objects.all() paginator = Paginator(post_list, 1) page = request.GET.get('page') return render(request, 'news.html', {'posts':posts}) templates {% for num in posts.paginator.page_range %} {% if posts.number == num %} <strong>{{ num }}</strong> {% else %} {{ num }} {% endif %} {% endfor %}