Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django keep values after submit (input/select/checkbox):
I'm preparing a simple search/filter form for my django project and I would like to have all options kept after clicking 'submit' button. I'm using select options, inputs and checkboxes Is there any all-purpose solution for this? Here's the code: <form method = "GET" action = "."> <div class="form-row"> <div class="form-group col-8"> <label for="filter_by_name">Search by name</label> <div class="input-group"> <input class="form-control py2 border-right-0 border" type="search" name="filter_by_name" placeholder="Name contains.."/> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> <div class="form-group col-md-4"> <label for="filter_by_shop">Search by shop</label> <select id="filter_by_shop" class="form-control" name="filter_by_shop"> <option selected>All shops</option> <option>first shop</option> <option>second shop</option> </select> </div> </div> <div class="input-group col-md-8 checkboxes"> <span> <input type="checkbox" name="first" value="first"\> <label >first</label> <input type="checkbox" name="second" value="second"\> <label >second</label> <input type="checkbox" name="third" value="third"\> <label >third</label> </span> </div> <div class="form-group col-md-2"> </div> <button type="submit" class="btn btn-primary">Search</button> </div> </form> -
Accessing image files
I'm working in a project which I have a directory with 10k images, and I want display those images, with a search in my website. So, the user can choose the image he wants through the search, access the image, and download it. What is the best way to do that? -
Why email should always be verified in US-EAST-1 Region in AWS SES?
I am trying to send email using AWS SES with Django and I am getting following error - MessageRejected: An error occurred (MessageRejected) when calling the SendRawEmail operation: Email address is not verified. The following identities failed the check in region US-EAST-1: my-email@gmail.com Above error is not coming only if I verify emails in US-EAST-1 region. But I am using configurations like this - EMAIL_BACKEND = "django_amazon_ses.EmailBackend" AWS_SES_ACCESS_KEY_ID = 'AWS_SES_ACCESS_KEY_ID' AWS_SES_SECRET_ACCESS_KEY = 'AWS_SES_SECRET_ACCESS_KEY' AWS_SES_REGION = 'ap-south-1' AWS_SES_REGION_ENDPOINT = 'email.ap-south-1.amazonaws.com' As per my configurations if I verify my emails in ap-south-1 region then It should work. Please make me understand. I am new to AWS. -
I would like to make some changes to the rest_framework.urls login page
I am using rest_frameowork urls for login and logout. I would like to add a custom header to the login page. is there a way I can make changes to the pre-built login page? urlpatterns = [ path('', include('rest_framework.urls')), ..... ..... ] -
Using Vue.js to update game data from game state object
I am developing a card-based game with Django and using Channels to implement websocket communication between the client and server. I want to write the front-end using vue.js, which I'm just starting out with, and I want it to be entirely state-dependent, that is, with each action taken from a player, the Channel consumer will send a state object containing all the public information about the game, plus the bits of private information regarding the specific player receiving the message. This is what a state object looks like, seeing from the client: { current_card: 4, current_turn: 1, last_amount_played: 1, last_card: 0, last_turn: 2, my_cards: ["12C", "12S", "9C", "12C", "5D", "5H", "6H", "7S", "7H", "11S", "5C", "1H"], number_of_stacked_cards: 61, other_players_data: [ {number: 1, is_online: false, number_of_cards: 1}, {number: 2, is_online: true, number_of_cards: 10} ], won_by: -1, type: "new_state" } I want the corresponding DOM elements of the UI to get updated with the new data upon receiving a new state. For example, for each player, I'll have a div with id="player_i where i is the number attribute you have for each player; upon receiving the state the element number_of_cards_of_player_i will have to be updated so that it contains state.other_players_data[i].number_of_cards, so on … -
How to call instance methods on the nested Serializer with django rest?
I've got two models I'm trying to nest together. Timesheet and Invoice My InvoiceSerializer looks something like this: class InvoiceSerializer(serializers.ModelSerializer): billable_timesheets = serializers.SerializerMethodField() total_hours_and_cost = serializers.SerializerMethodField() class Meta: model = Invoice fields = ( "hours", "hour_cost", "billable_timesheets", "total_hours_and_cost", ... ) def get_total_hours_and_cost(self, obj): return obj.hours * obj.hour_cost def get_billable_timesheets(self, obj): """Getting all timesheets for selected billable period""" timesheets = obj.project.timesheets.filter(<queryset here>) return TimesheetSerializer(timesheets, many=True).data This works fine and all - I can define MethodFields and the correct JSON is returned, great. However, I got a method on my child model (in this case, the Timesheet model) that I need to access and run some calculations on. I'm getting the data necessary via get_billable_timesheets, and now I need to run a method on my Timesheet model called total_duration(). Whenever I try to do something along the lines of timesheets = self.get_billable_timesheets(obj) hours = 0 for timesheet in timesheets: hours += timesheet.total_duration() I get: AttributeError: 'collections.OrderedDict' object has no attribute 'total_duration' What I don't understand is that I'm actually serializing the data already through the get_billable_timesheets method - why am I still receiving this error? -
What I need to do for creating this trivia app?
APP NAME : Trivia App ( should show on the launch icon and splash page ) First page: What is your name? Answer : Text field ( capture the name of the user ) NEXT BUTTON to launch next page: Who is the best cricketer in the world? Options: A) Sachin Tendulkar B) Virat Kolli C) Adam Gilchirst D) Jacques Kallis Select any one. NEXT BUTTON to launch a new page: What are the colors in the Indian national flag? Select all: Options: A) White B) Yellow C) Orange D) Green Select more than 1 NEXT BUTTON: SUMMARY Hello “Name:” , Here are the answers selected: Who is the best cricketer in the world? Answer: “ “ What are the colors in the national flag? Answers : “Commo separated” -
How to replace foreign key by its associated value in django queryset
I'm fairly new to django and i would need your help! I wrote an api/route view that query the database and return a JSON to my fetch function in my javascript. Is there a way to query the database and got back a queryset with foreign key replaced by its associated value ? I though i could use ModelName.objects.select_related( 'field ') but i didn't understand how it works. If you have a solution or advices on better way to achieve the goal, Thanks in advance! Context in pseudo-code: // HTML // Button onclick function get_list_of_data // JS // function get_list_of_data: Fetch URL of route django Convert response to JSON iterating through JSON to fill HTLM div // Django // use ModelName.objects.filter( name = name ) to get list of data in Queryset use serializers.serialize(json, ...") to get JSON from Queryset return JsonResponse (json_query) -
Unused import gives me access to the stdout of a signal
I just ran into a strange interaction and I'm curious if one of you could explain what's happening: I'm writing a test, and to start I just created a simple print statement to check if the signal was going off. Here's the test located in notifications/tests/test_notifications.py: def test_like_post_save_signal(self): """ Testing the signal that is connected to the Like model's post_save. """ baker.make('core.Like') Here's the signal code I'm trying to test located in notifcations/notifications.py: @receiver(post_save, sender='core.Like') def like_signal_post_save(sender, **kwargs): """ Post save signal for Like model """ print("Something") There's a bit of magic happening behind the scenes, but the goal here is to print("Something") every time a Like object is saved. ... Now, here's what's confusing me. I was able to get it to work, but only after importing a separate function from notifications.py into my test_notifications.py file. Here's the import statement: from core.services.notifications.notifications import print_test Why does an import statement of a different function (print_test) give me access to the stdout? -
Stop fetch function from reloading console
I am trying to create a like/unlike button. I am sending a form using fetch to my /like url in python. To test the code I decided to simply return a JSONResponse . It is working but it seems that the page is being reloaded and thus the original state is being returned. That is: original state is 'Unlike', click makes it 'Like' for a small amount of time and then 'Unlike' comes back Here is my html {% if request.user not in post.like.all %} <a href="" class="card-link liked" data-id="{{post.id}}" data-is_liked="false" id="post-like-{{post.id}}"> <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-heart" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z" /> </svg> </a> {% else %} <a href="" class="card-link liked" data-id="{{post.id}}" data-is_liked="true" id="post-like-{{post.id}}"> <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-heart-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z" /> </svg> </a> {% endif %} here is my js script //this is the script for like edit and delete var like = document.querySelectorAll(".liked") like.forEach(element … -
Why in my custom form a placeholder is set for 2 out of 4 fields
I'm making custom form for registering: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.TextInput(attrs={'placeholder': 'username'}), 'email': forms.TextInput(attrs={'placeholder': 'email'}), 'password1': forms.TextInput(attrs={'placeholder': 'password'}), 'password2': forms.TextInput(attrs={'placeholder': 'repeat password'}), } but the problem is, that the only visible placeholders are the ones for username and email field. Does any one knows the anwser to why this is happening? -
Cron job Django Elastic Beanstalk
I am trying to set a cron job on my project to send a email after 15 minutes. This is in django.config 04_cronjb: command: "cat .ebextensions/cron-linux.config > /etc/cron.d/crontab && chmod 644 /etc/cron.d/crontab" leader_only: true This is my cron-linux.config file files: "/etc/cron.d/mycron": mode: "000644" owner: root group: root content: | * * * * * source /opt/python/current/env && python /opt/python/current/app/manage.py cronjb It all deploys successfully but i am not receiving any email. Cronjb script is working i have tested it. So the error is one these two files. Is there some mistake in it? -
Setup Apache Server With Django (hopefully also with git)
I've created a website and would now like to host it. I already have an apache server setup I literally have no clue what to do and how to go further, The tutorials online haven't been much help too, since I'm still utterly lost, I've figured out there is a command shell but don't really know how to use it even when the code is right in front of me. If someone could steer me in the right direction that would be a huge help. I have looked at multiple different tutorials, videos and articles, and still have no idea what to do. I'd also love if someone could show me how to use the server with git so when I want to update the server, I can simply by pushing (similar to Heroku I think) Thank you -
What is the difference between url name and view name in reverse() in django?
when I was reviewing django doc, I saw reverse() in urlresolvers, I saw this sentence at the beginning of it which is: viewname can be a URL pattern name or the callable view object., I want to know what is the difference or differences between these two options? Or do they have any differences at all? -
Django - change answer returned when a page doesn't exist or user is not authenticated
I use Django in production. I see that if an unauthenticated user accesses an exposed API - the server will return HTTP 401 Unauthorized. If the user will access an existing API that requires authentication - the server will return 404 Not found This seems to me like a bad security practice and allows an attacker to find the server's exposed APIs. Is there a way to change that so both will return the exact same result (I think 401 is the best practice, no?) -
Decorator for Queries
I have multiple pages where I pull three sets of data. One set of data is always different, while the other two sets are always the same. Is there a way to make the two constant data into a decorator so I don't have to keep keying them? Thank you. views.py @constants_decorator def page01_view(request): data01 = Data01.objects.all() constant01 = Constant01.objects.all() constant02 = Constant02.objects.all() context = { 'data01': data01, 'constant01': constant01, 'constant02': constant02, } return render(request, 'page01.html', context) @constants_decorator def page05_view(request): data05 = Data05.objects.all() constant01 = Constant01.objects.all() constant02 = Constant02.objects.all() context = { 'data05': data05, 'constant01': constant01, 'constant02': constant02, } return render(request, 'page05.html', context) I'm still trying to understand how Decorator works and all the examples i've watch and read thru are very simple and nothing with passing data. I've tried below, but my pages are coming up empty. decorator.py def constants_decorator (view_func): def wrapper_func(request, *args, **kwargs): constant01 = Constant01.objects.all() constant02 = Constant02.objects.all() context = { 'constant01': constant01, 'constant02': constant02, } return view_func(request, *args, **kwargs) return wrapper_func -
django 3, render two forms in template
I have two forms of two models, I need to send them in my template, previously in django 2 it worked fine, but now that I update to django it does not return well I get the source code, if I remove the dict and the RequestContext (request)) in views.py it redeems me the html but it does not show my forms, I show the following code forms.py class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = ('empresa', 'telefono', 'rfc', 'upload') urls.py urlpatterns = [ url(r'^registro$', views.registro, name='registro'), ] views.py def registro(request): if request.method == 'POST': uf = UserForm(request.POST, prefix='user') upf = UserProfileForm(request.POST, prefix='userprofile') if uf.is_valid() * upf.is_valid(): user = uf.save() userprofile = upf.save(commit=False) userprofile.user = user userprofile.save() name = 'Registro Pagina' email = 'main@example.com' fullemail = name + " " + "<" + email + ">" content = {"%s: %s" % (key, value) for (key, value) in list(request.POST.items())} content = "\n".join(content) message = str(upf) msg = EmailMessage('new register', content, fullemail, ['main@example.com', 'other@example.com']) #msg.content_subtype = "html" # Main content is now text/html msg.send() return HttpResponseRedirect('/') else: uf = UserForm(prefix='user') upf = UserProfileForm(prefix='userprofile') return render(request, 'cfdipanel/register.html', … -
Generate Private key for SSL Certificate to be used inside Docker Container
I'm working on a project that runs Docker and has 3 containers: Django PostgreSQL traefik Now I'm going to generate a private key to add an SSL certificate to my website, the question is where should I generate private key? Inside the main server that running the Docker? or inside the Django container? or inside Traefik container? I'm using trafik:alpine for trafik & python:3.6-alpine for Django if it is the container where I should generate a private key, What is the command line should I use inside container to generate a private key? Actually I have built private.key and certification.crt files referenced them inside traefik.toml file and i got this error: failed to load X509 key pair: tls: failed to find any PEM data in certificate input That's why I think the problem is with my private.key which I generated inside the main server not inside any container. Here is the configuration i use inside traefik.toml file if you want to know more information: logLevel = "INFO" defaultEntryPoints = ["http", "https"] # Entrypoints, http and https [entryPoints] # http should be redirected to https [entryPoints.http] address = ":80" [entryPoints.http.redirect] entryPoint = "https" # https is the default [entryPoints.https] address = … -
FullCalendar Django model
I am a newbie and don't know much about using Fullcalender. I am trying to show my saved Full Calender event from django model in full calender but it is not displaying the saved event. I just want to show event name on the date specified. I have tried multiple methods including these two options Please help -
Pass html dropdown option as api call Django
Attempting to construct a simple Django app where a user can enter text search criteria and select from a drop down list of providers then these are passed as an api call (news api) views.py def api_request(request): search_term = request.POST.get('textfield') source = request.POST.get('list_providers') url = 'https://newsapi.org/v2/everything?' parameters = { 'q': '%s' % search_term, 'sources': '%s' % source, } response = requests.get(url, params=parameters) response_json = response.json() articles = response_json['articles'] return render(request, 'news.html', context={"articles": articles, "search_term": search_term, "source": source}) home.html {% block content %} <form method="POST"> {% csrf_token %} <input type="text" name="textfield", placeholder="Enter search criteria"> <br/> <select name = "list_providers"> <option value = "option1">Option 1</option> <option value = "option2">Option 2</option> <option value = "option3">Option 3</option> </select> <br/> <button type="submit">Search</button> </form> {% if search_term & sources %} {% for title, author, date, des in mylist %} <h3>Title:</h3> {{title}} <h4>Published by:</h4> {{author}} <h4>Published at:</h4> {{date}} <h4>Summary:</h4> {{des}} {{value | linebreaks}} <br/> {% endfor %} {% endif %} {% endblock %} But the error given on page load is: KeyError at / 'articles' I have been able to pass multiple text input criteria without error so believe the issue is possibly in the default selection criteria for the dropdown. -
Djnago: Bootstrap3 form dropdown options display issue
I am using bootstrap3 in django template to display dropdown menu so that user can select the option they chooses. After selecting the option, selected option is not displaying clearly. See below images. While selecting the options After selecting the option its displays like below It's hard to see what option user selected. How to fix this issue so that user can see clearly see what option they chose? below is the html code I am using for this {% extends 'base.html' %} {% load bootstrap3 %} {% block content %} <body> <section class="hero p9"> <div class="explore-section"> <div class="container"> <form method="post" > {% csrf_token %} {% bootstrap_form form %} <button class='btn btn-default' type='submit'>Select</button> </form> </div> </div> </section> </body> {% endblock content %} FYI, this is the below is the form I am using for this. class selectPostTypeForm(forms.Form): STATUS_CHOICES = (('1', 'Text Post'),('2', 'Image Post'),('3', 'Video Post'),) post_type = forms.ChoiceField(choices=STATUS_CHOICES) -
How to create / use a custom backend for Django
I'm still learning to use the Django framework, so I might be in over my head here, but I'm trying to use a backend that is not officially supported by Django. I recently stumbled upon Deta and after messing around with it a bit I thought it would be an great to host my Django project on it, to support the developers of Deta and to familiarize myself with the service some more.. To keep things simple I thought of using the database service provided by Deta: Deta Base, for the backend of my Django project instead of a traditional SQL database that I would have to host somewhere else. I haven't found much information on using or creating a custom backend for Django although I assume it is probably complicated and not recommended because of Django's ORM. I would love to hear the opinion of more experienced Django developers on the subject to know if my idea is even possible and worth it (in terms of time/effort required). Thanks for reading this far ;-) -
Compare items from InlineFrom before saving Django
I have an InlineForm on my forms that I save a list of names, but I'd like to check if the names are different before saving it. When I try a FOR to save the names in a list, I get the individual letters instead. How can I solve this problem? Here's my form and validation code: forms.py class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(label="Colaborador do Projeto", widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) def clean(self): colaborador_projeto = self.cleaned_data.get('colaborador_projeto') lista_erros = {} verifica_nome(colaborador_projeto) if lista_erros is not None: for erro in lista_erros: mensagem_erro = lista_erros[erro] self.add_error(erro, mensagem_erro) return self.cleaned_data validation.py def verifica_nome(colaborador_projeto): lista_nomes = {} loop = 0 for nome in colaborador_projeto: lista_nomes[loop] = nome loop += 1 print(lista_nomes) Here's how the print shows: {0: 'V', 1: 'i', 2: 'c', 3: 't', 4: 'o', 5: 'r'} {0: 'J', 1: 'é', 2: 's', 3: 's', 4: 'i', 5: 'c', 6: 'a'} {0: 'L', 1: 'e', 2: 't', 3: 'i', 4: 'c', 5: 'i', 6: 'a'} P.S.: I know I'm not sending the errors list yet. I wanna solve the 'comparing names' problem first, before I send the error to my HTML page. -
Django Elastic Beanstalk Implementing Cron job
I am trying to set a cron job on my project to send a email after 15 minutes. 04_cronjb: command: "* * * * * source /opt/python/run/venv/bin/activate && python manage.py cronjb" leader_only: true This is what i am using in config file But when i try to deploy my project it shows a weird error Command failed on instance. Return code: 127 Output: /bin/sh: __init__.py: command not found. init.py is the file which is in root of my folder. When i try the simple command 04_cronjb: command: "source /opt/python/run/venv/bin/activate && python manage.py cronjb" leader_only: true It works fine. What am i doing wrong in this? -
convert django api to django-rest-framework api with 200 response code
Here is my code which sends 200 api response after doing some stuffs. It is working but, I wants to convert this as django-rest-framework way with DRF template. def refresh_dashboard(request): profile = request.session["profile"] refresh_profile_events(profile) # refresh_profile_events.apply_async(args=[profile]) return JsonResponse({"code": 200, "msg": "success"}) Below code i am using but it is giving below error. Please have a look how we can achive this class RefreshAPIView(RetrieveAPIView): permission_classes = (IsAuthenticated,) def get_object(self): user = self.request.user return type('DashboardData', (), {"code": 200})() Error: assert self.serializer_class is not None, ( AssertionError: 'RefreshAPIView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method.