Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How should I store encrypted files in Django?
I have a program that encrypts user uploaded files and I want to know where is the most secure place to store the encrypted file. After the file has been uploaded I encrypt the bytes which means that I can't use the default File upload system Django uses. The options I have thought of are: As a .txt file in the server (connected to Django by using the default File upload system) Save as a text input in the database (this will be completely encrypted) Which one of these are more secure and best for use, I also would like to know if there are any more ways of storing this encrypted file. Thank you -
Django dynamic template
is it possible to make a dynamic tag inside a if tag my view is this {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Leitung_der_Klasse}}</td> <td>{{Ansicht.Funktion}}</td> <td>{{Ansicht.Nname}}</td> <td>{{Ansicht.Vname}}</td> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK.{{DYNAMIC}} %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} I want filter this by date. Like an input for date and it would show my <td> like I have it in my template possible? -
Problems with edit button in Django
i'm novice and just trying Django functionality. I create button to edit value in db in Django, but it doesn't work write. Problem in that: when i press the button (from notes.html), it's redirect to page edit_note.html, but values in fields is empty. When i manually press adress in browser, it work's normally. I don't understand where i maked mistake. in views.py: class EditNoteView(UpdateView): model = Notes form_class = NotesForm template_name = 'notes/edit_notes.html' context_object_name = 'note' def get_success_url(self): return reverse_lazy('edit_note', kwargs={'pk': self.object.pk}) in urls.py: urlpatterns = [ path('', home, name='home'), path('notes/', NoteView.as_view(), name='notes'), path('<int:pk>/edit', EditNoteView.as_view(), name='edit_note'), in notes.html: {% for i in all_notes %} <tr> <td>{{ i.notes_category }}</td> <td>{{ i.title }}</td> <td>{{ i.text }}</td> <td>{{ i.reminder_data_time }}</td> <td> <form action="{% url 'edit_note' i.id %}" method="post"> {% csrf_token %} <div class="btn-small-group"> <button type="submit">Edit</button> </div> </form> </td> <td> <div class="btn-small-group"> <button type="submit">Delete</button> </div> </td> {% endfor %} in edit_notes.html: <form action="{% url 'edit_note' note.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <div class="btn-small-group"> <button type="submit">Edit</button> </div> </form> enter image description here enter image description here -
How can I place something at the top of a queryset in Django Rest Framework?
I have a model Post with field pinned_until = models.DateTimeField(blank=True, null=True). Let's say pinned_until has any value that is before the current time (timezone.now()), I want it to go at the top of the queryset, so it is first in the list of serialized response data. How can I accomplish that? I know it has something to do with annotate, but I haven't been able to figure it out so far. -
From API to Django template to show different data while iterating
***This is view function*** def home_view(request): url = "https://random-recipes.p.rapidapi.com/ai-quotes/50" headers = { "X-RapidAPI-Key": "`enter code here`", "X-RapidAPI-Host": "random-recipes.p.rapidapi.com" } response = requests.request("GET", url, headers=headers).json() res = response context = {'res' : change_recipe(), 'iterator':range(0,11)} return render(request,'home.html', context=context) This is django template <div class="container" id="card" > {% for i in iterator %} <div class="card1"> <div class="card-header1"> <img src="{{res.image}}" alt="rover" /> </div> <div class="card-body1"> <h4> <a href="/article/" style="text-decoration: none; color: inherit; " >{{res.title}}</a> </h4> <p> An exploration into the truck's polarising design </p> <div class="user1"> <div class="user-info1"> <strong>By</strong> <a href="">Rachel Lucas</a> </div> </div> </div> </div> {% endfor %} </div> I want to show different data when iterating for loop in django template using api when I replace res with res[0] it show only one data in all card1/div after iterating for loop in django template, i want to show different data in different cards. -
JavaScript setting multiple choice input field on Leaflet marker click
I have an embedded Leaflet map in a Django app with markers that are identifying different sampling locations for a study. These locations each have a unique location ID. When any of these markers are clicked, a popup appears with a form. The form has a few fields, one of them being that unique location ID for the user to select (in a multiple choice, drop-down style field). What I want to happen is when a user clicks on a marker, the location ID field in that multiple choice field in the popup is set to the unique ID of that marker. I have tried setting the field like this in a marker.on('click') function document.getElementById('location').value = marker.feature.properties.Location_Identifier ,but when you view the value after this it is still blank. I think part of the problem may be the feature.properties.Location_Identifier is the actual location ID whereas in the form Django makes the multiple choice fields be enumerated so the value there may just be an integer so there is a mismatch happening for setting the value. If anyone has any insight I would be grateful. -
Serializing two CharFields into one object
I have serializer like this below. Now I have separated fields for store_photo and store_name. class ProductSerializer(serializers.ModelSerializer): store_photo = serializers.CharField(source='store.photo', read_only=True) store_name = serializers.CharField(source='store.name', read_only=True) class Meta: model = Product fields = ['store_photo', 'store_name', ...] Can I somehow serialize it together in one object? I mean something like this: store = {store_photo, store_name} class Meta: model = Product fields = ['store', ...] -
Where do I store the encryption key when encrypting in Django?
I am creating a website using Django, my website will encrypt uploaded files and another user can then download the files unencrypted. It's pretty straightforward encrypting in python, but where do I store the encryption key? I encrypt the files in case the database or source code has been compromised. Then I can't store the encryption key as a file or in the database. Where can I store the encryption key? Thank you -
Django Framework or Not
Hello guys I'm working on a survey form website with DJango And I want user to generate a code to embed on their website Examples <!-- Start of HubSpot Embed Code --> <script type="text/javascript" id="hs-script-loader" async defer src="//js-na1.hs-scripts.com/22614219.js"></script> <!-- End of HubSpot Embed Co <script src="//code.tidio.co/uqkwgjeoo7leire6zsukpluyum8zqmme.js" async></script> And I don't know how to do it Will I use The Django Framework If yes drop resources to help me work it out (Without Framework) And still if no I don't still know how to do it DJango Drop resources to help me do it normal way in Django with framework -
Access static method variable in Generic APIView Post method
I have a custom static method in my GenericAPIView previously the calls create and complete() were in try and except for each task it tries and except logger.error(called) in post method instead i removed try and except from each task and created new method and catching the exception while calling the method but its not working how can i access task used in my_static_method in my post method in exception class MyAPIView(GenericAPIView): @staticmethod def my_static_method(arg1, arg2, arg3): if arg3 and not arg2.value: task = task1(arg1) task.create() task = task2(arg1) task.complete_task() if arg1.somevalue() or arg1.someotherValue(): task = task3(arg1=arg1) task.complete_task() def post(self, request, *args, **kwargs): try: self.my_static_method(self.arg1, arg2, self.arg3) except Exception: logger.error(f"Error executing the {task.__class__.__name__}", exc_info=True) -
How to get last created item's id by django restframwork in react
def create(self, request): serializer = TodoItemSerializer(data=request.data) if serializer.is_valid(): device = serializer.save() device = device.id return Response(device, status=status.HTTP_201_CREATED) it is working. How can i get this device item in react i have a api call like this, i tried console.log(response.device) but returned "undefined". How can i access the device item ? const response = await fetch("http://localhost:8000/api/todoitems/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: this.state.title, description: this.state.description, due_date: this.state.date, creator: this.state.userId }) }); if (response.status === 201) { console.log(response) toast.success('Success', { toastId: 'success1', position: toast.POSITION.TOP_CENTER }) } else { alert("Something went wrong!"); } -
Django Forms translate standard error message
All my translations work except the error messages generated by forms. This is the start of my form: class MyForm(forms.Form): first_name = forms.CharField(label=_("First name"), min_length=3, required=True) Now the label "First name" translates fine to "Vorname" because I made a .po file and compiled etc.. However when entering only 2 characters the resulting error is in English and not in (this case) German, see screen print below. I have looked in Github Django repository django/conf/locale/de etc. but could not find the string "Please lengthen etc." there. So my question is: how do I get this error message to translate? I assume Django has a standard method and that this string is already in some .po file somewhere within the Django project? -
Why queryset returns value instead of instance in Django Views?
My Problem I have a queryset in Django View. That queryset should return an instance. But instead of that it returns a value Models.py class Author(models.Model): name = models.CharField(max_length=250, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('authors:author_detail', args=[str(self.id)]) class Meta: verbose_name = 'Author' verbose_name_plural = 'Authors' Projects URLS.py urlpatterns = [ path('admin/', admin.site.urls), path('author/', include('authors_app.urls', namespace='authors')), ] authors_app ULRS.py from .views import * app_name = 'authors' urlpatterns = [ path('<int:pk>/', AuthorDetail.as_view(), name='author_detail'), ] Views.py class AuthorDetail(ListView): model = Book context_object_name = 'author_books' template_name = 'author-detail.html' queryset = Book.objects.all().order_by('bookinfo__bestseller') paginate_by = 36 def get_queryset(self, **kwargs): author_id = Author.objects.get(pk = self.kwargs['pk']) print(author_id) qs = super().get_queryset(**kwargs) return qs.filter(author = author_id) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet context['author'] = Author.objects.get(pk = self.kwargs['pk']) # context['image'] = f"/mnt/HDD/wiki/parser/images/photos/10.png" return context When I open authors page - mysite.com/author/51/ I've got an Error: Cannot query "Lawrence Gilman": Must be "Author" instance. Question How can I get an instance in that queryset? -
How edit products without forms.py Django?
I need create and edit products witout forms.py. How i can do this. If u can with example <form method="post"> {% csrf_token %} <input type="text" placeholder="Название"><br> <textarea placeholder="Текст статьи" rows="8" cols="80"></textarea><br> <input type="date"><br> <button type="submit">Добавить статью</button> </form> -
How to create private endpoint for postgres server using azure python sdk
I want to create private endpoint for postgres server using azure python sdk. I need some sample code that i can refer. explored documentation but didn't get relevant information. -
Git repository corrupted and changed files are empty after PC crash
I was working with git bash, rebasing and stashing my changes when suddenly my PC crashed. After the restart, the disk was repairing, but when it loaded the repository no longer worked, git commands returned: fatal: not a git repository (or any of the parent directories): .git All the files that I have not committed are now blank, the changes are gone. HEAD files and stash are also corrupted. I am in a panic mode. What can I do in this situation to recover lost files and restore the repository to the previous state? -
Having issues implementing Stripe in my Django Code
I am implementing a stripe charge in my django ecommerce project. So In my views, I am trying to get the data from an input element in a form, then pass into a variable in the views. Here is the Javascript that creates the input element var form = document.getElementById('stripe-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit() So in the views.py, I have this: token = form.cleaned_data.get('stripeToken') save = form.cleaned_data.get('save') use_default = form.cleaned_data.get('use_default') print(form.cleaned_data) the print(form.cleaned_data) returned a dictionary {'stripetoken':'', 'save': False, 'as_default': False} stripetoken maps to the token variable, and as you can see its value is empty. The last two variables that maps to the last two keys in the dictionary returned values. The token = form.cleaned_data.get('stripeToken') is supposed to get this hiddenInput.setAttribute('value', token.id); right? When I tried getting the value of token.id, I got a response. I used Javascript alert(token.id) to do that, and I got a value displayed in my browser. So I don't know what exactly is wrong. Can someone help me out on this one? -
Django filter_horizontal - how to connect more fields together
I need to connect more fields to one filter_horizontal parameter in Django Admin. I have three many-to-many variables: class EducationTypeAdmin(admin.ModelAdmin): ... list_filter = ("qualifications", "school_levels", "subject_groups") filter_horizontal = ["qualifications", "subject_groups", "school_levels"] This code will make 3 seperate many-to-many horizontal filters. I need them to be in one. Ex in admin: AS, English, High School --> -
Run python script in Django and produce live output buffer on the web
I am a beginner to Django web framework. I have a bunch of python scripts which runs and produce output on cli at present but I want the same scripts to run from django web and display live buffer output Can anyone shed some light on how to achieve it -
Tried inheriting dispatch in django
Hi I was trying to inherit the dispatch using super store it in a variable and then log the errors: my code looks like def dispatch(self, request, *args, **kwargs): response = super().dispatch(request, *args, **kwargs) if response.status_code == 400: logger.error(response.json) logger.error(request.payload) return super().dispatch(request, *args, **kwargs) and the error is : Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/src/app/api/views/researcher_dashboard/cv.py", line 54, in dispatch logger.error(response.json) and for request.headers it is : Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/src/app/api/views/researcher_dashboard/cv.py", line 54, in dispatch logger.error(response.json) -
Admin administration without ForeignKey
i need to put 2 models in one page on Admin administration without ForeignKey admin.py class MobileAppInline(admin.StackedInline): model = MobileApp class HomeAdmin(admin.ModelAdmin): inlines = [MobileAppInline,] admin.site.register(Home, HomeAdmin) -
Cannot unpack non-iterable SerializerMethodField object in Django DRF
I'm trying to assign the list from SerializerMethodField() return to a set of two fields, as: class PostSerializer(serializers.ModelSerializer): postvotes, postvote = serializers.SerializerMethodField() def get_postvotes(self, obj): qset = PostVote.objects.filter(Q(post=obj)) votes = [PostVoteSerializer(m).data for m in qset] vote = sum(vote['vote'] for vote in votes) return [votes, vote] # votes[], vote: Integer However, this fails with the title-metioned error. How can I solve this? Thanks. -
I am getting an error in the second line of the code showing unexpected token... I have also added bootstrap4 in installed apps
enter image description here {% load bootstrap4 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Learning Log</title> {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} </head> I have aslo added bootstrap4 in installed apps in settings .py INSTALLED_APPS = [ # My apps "learning_logs", "users", # Third party apps. "bootstrap4", -
My Django website is not working with Https on AWS [closed]
Recently i have deployed my django website on Amazon web services Ec2 instance and i am using window Free Tier where i have copied my code and then run on that Remote Desktop that is working fine on my instance ipv4 adress http://3.131.202.237/ but problem is that this is not secure.My website is working as expected.But i want to work it with https ssl certificate.but when i try to open https://fableey.com ,chrome shows me error site cannot be reached.Whats the problem there. Allowed Hosts is set to ['*']. Now i also had installed SSL certificate on Amazon certificate manager and that is active & in use now but still my website is not opening on https://fableey.com ,rather it is opening on http:fableey.com. Now what i want ? I just want to work my website on https also.Please help me !!! Thanks!!! -
Using the http.HTTPStatus class in Python to return the meaning of a HTTP status code
I'm trying to write a block of code to return the meaning (description) of an HTTP status code using the http.HTTPStatus Python class. I read the docs, but it seems I can only do the reverse. Is there way I can do this? try: if resp.status != 200: message =