Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save items from Form in a list in Django
I'm trying to compare names inserted in an InlineForm before saving them. But I'm having some issues trying to save the names into a list and then compare them. Here is what I've tried to do. form.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 = colaborador_projeto.split() nomes = ''.join(lista) lista_nome = [] nome = '' for i in range(len(nomes)): nome += nomes[i] if i == (len(nomes)-1): lista_nome.append(str(nome)) Instead of getting a list with the names in different possitions, all the names are saved on list[0]. How can I fix it? -
Getting Error: Unsupported lookup 'id' for DecimalField or join on the field not permitted
I'm trying to get a DecimalField in Django from the database by using the ORM, so I can populate a field on my form. I'd like to do something like this: SELECT trainer_price FROM Trainer WHERE id=3). I'm getting this error: Unsupported lookup 'id' for DecimalField or join on the field not permitted. and can't figure out why my query is not working. This is what I've tried: price = Trainer.objects.filter(trainer_price__id=3) price = Trainer.objects.filter(trainer_price__pk=3) I've also referenced this StackOverflow article: How to filter GTE, LTE on Float or Decimal via Django ORM But am still getting the error mentioned above. Here's my full code for my views.py: def train(request): trainer_form = Trainer(request.POST) price = Trainer.objects.filter(trainer_price__id=3) context = {'trainer_form':trainer_form, 'price':price} return render(request, "register/trainer_form.html", context) Any ideas on what I'm doing wrong? Any help would be great! -
BS4 returning AttributeError: 'NoneType' object has no attribute 'text' sometimes, how to solve this?
I wrote a piece that tries to get some data from yahoo finance. However, first attempt it failed somewhere at the start after being able to retrieve stock data (price and change in price). It gave the NoneType error. Then I ran it again, and it actually was able to retrieve suddenly that data and continued to retrieve more and failed somewhere halfway with the same error. I find it weird, since that attribute text is present in the html. Especially weird that it is able to find it in the second attempt without adjustments. Also, it is all on the same page, so it is not that I need to wait for some. This is the error: price = soup_ticker.find('span', class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)').text AttributeError: 'NoneType' object has no attribute 'text' This is the specific html: <span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="32">22.12</span> This is my Code. Mind that im a beginner and this is all for educational purposes. I know there are probably a million ways to do things better than I have done below to achieve the same. Thank you for your help in advance and for your knowledge! from django.core.management.base import BaseCommand from urllib.request import … -
Image will not upload from a form in django. Image will upload if entered from admin panel but not from form
the image will not upload if done thru the form. if the image is uploaded thru the admin interface it works properly.. after several hours of researching the docs and google I cannot figure out whats wrong if anyone has any clue I would be greatly appreciative model class Event(models.Model): TYPE = [ ('CYCLING','cycling'), ('STAIR CLIMB','stair climb'), ('RUNNING','running'), ] id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) event_name = models.CharField('Event Name', max_length=100) event_location = models.CharField('Event Location', max_length=100) event_date = models.DateField('Event Date') event_description = models.TextField('Event Description') event_type = models.CharField('Event Type', max_length=30, choices=TYPE, default='CYCLING') event_img = models.ImageField( upload_to="eventImg/", blank=True, null=True ) def __str__(self): return self.event_name def get_absolute_url(self): return reverse('event-detail',args=[str(self.id)]) form.py class AddEventForm(forms.ModelForm): class Meta: model = Event fields = ('event_name','event_date','event_location','event_type','event_description','event_img') template {% extends '_base.html' %} {% load materializecss %} {% block title %} Add Event{% endblock title %} {% block content %} <div class="container" > <h1>Add Event </h1><i class = 'material-icons large'>pedal_bike</i><i class = 'material-icons large blue-text'>directions_walking</i><i class = 'material-icons small green-text'> directions_running</i> </i> <form method = 'POST' enctype="multipart/form-data"> {% csrf_token %} {{form|materializecss}} <button type = 'submit' class = 'btn waves-effect waves-light amber lighten-2 black-text hoverable'>Add Event <i class = 'material-icons right'>send</i></button> </form> </div> {% endblock content %} urls.py from django.contrib import admin … -
RadioSelect() get values of inputs
I want to pass RadioSelect() label, help text, name, choices and values through JSON. I managed to pass every of them but not values. How can I get values of each input field? I've read the Django docs and did research on google but didn't find any answer. Views.py: class ArticleUpdateView(UpdateView): model = User1 template_name = None def post(self, request, *args, **kwargs): ... def get(self, request, *args, **kwargs): form = BotForm(request.POST or None) self.object = self.get_object() for field in form.fields: # Delete HTML tags radio_inputs = [ strip_tags(html_inputs).replace('\n ', '') for html_inputs in form[field] ] # return unique id for each input and label id_for_label = [ form[field].auto_id + '_' + str(id) for id in range(len(radio_inputs)) ] # Make a dictionary from two above choices = [ {'id': id_for_label[i], 'label': radio_inputs[i]} for i in range(len(radio_inputs)) ] data = { 'label': form[field].label, 'help_text': form[field].help_text, 'name': form[field].name, 'choices': choices, } return JsonResponse(data, safe=False) Models.py: class User1(models.Model): types1 = ( ('a', 'some text'), ('b', 'some text1'), ('c', 'some text2'), ('d', 'some text3'), ) types2 = ( ('a', 'some text'), ('b', 'some text1'), ('c', 'some text2'), ('d', 'some text3'), ) types3 = ( ('a', 'some text'), ('b', 'some text1'), ('c', 'some text2'), ('d', 'some … -
Django : How to extend page slug with keep data model working? .../slug/ and .../slug/review/
I was wondering is there is a way extend page slug with keep data model working? .../slug/ and .../slug/review/ Assume I got a model called: Group(model.Model): creator = ... invitee = ... is_active = ... is_delivered = ... Rating(models.model): relatedto = models.ForeignKey(Group...) I create a group with a slug. This group is dedicated to 2 users only. Users can chat on the main page. I've created some UpdateView (is_active or is_delivered) with different form to complete some part of the main model. .../slug/activation/ Question: I want to create another model Rating related to Group. The goal is: to give a review to user of Group with a form (using ex. form.instance.creator = ...) to get the data easily) to keep the access only to creator and invitee. What kind of class I can use in my views.py? I've tried with UpdateView but with a form which is not the main model that's does not work. -
Output in JSON Format Django Model
I have 2 Django Models :- Userprofile model which has the user's name and timezone and Activity period which has its time of activity class UserProfile(models.Model): real_name = models.CharField(max_length=100) timezone = models.CharField(max_length=100) class ActivityPeriod(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() I have to return the data from the database in this format { "ok": true, "members": [{ "id": "W012A3CDE", "real_name": "Egon Spengler", "tz": "America/Los_Angeles", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] }, { "id": "W07QCRPA4", "real_name": "Glinda Southgood", "tz": "Asia/Kolkata", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] } ] } But I am getting like this , The two models dont have the desired realtion I want [ { "model": "myapp.userprofile", "pk": 10, "fields": { "real_name": "Brittney Moore", "timezone": "Africa/Kampala" } }, { "model": "myapp.userprofile", "pk": 11, "fields": { "real_name": "Brett Jones", "timezone": "Atlantic/Reykjavik" } }, { "model": … -
Django admin site cannot login
I followed this this tutorial and everything worked fine, until I created a superuser and tried to enter the admin site. I used the correct username and password but cannot enter. I searched around and found old answers, saying you need to adjust the authentication_backends, e.g: AUTHENTICATION_BACKENDS = ('project.apps.account.backend.EmailAuthenticationBackend', ) But I dont have this line of code in my settings.py. This is my settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # … -
Django ManyToManyField showing empty list in form template?
i am using two form for update book title and lesson name too. the {{book_update}} is work fine but {{lesson_form_list}} it's getting empty list. how to use {{lesson_form_list}}as input field, when i try to use as form {{ lesson_form_list }} i am getting empty list[]` in html form.. models.py class Book(models.Model): title = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) lesson = models.ManyToManyField(Lesson) views.py def book_update_form(request, pk): book = get_object_or_404(Book, pk=pk) b_form = BookForm(request.POST or None, instance=book) l_form = [LessonForm(request.POST or None, prefix=str( lesson.pk), instance=lesson) for lesson in book.lesson.all()] if request.POST and b_form.is_valid() and all([lf.is_valid() for lf in l_form]): b_form.save() for lf in l_form: lesson_form = lf.save() return redirect('dashboard') context = { 'book_update': b_form, 'lesson_form_list': l_form } return render(request, 'patient/report.html', context) update_form.html <div class=" form-group"> <label for="id_lesson">Lessons</label> {{book_update}} </div> <div class=" form-group"> <label for="id_lesson">Lessons</label> {{lesson_form_list}} </div> -
DJANGO SUBSCRIPTION APPLICATION + SALEO INTEGRATION
I want to build a django subscription app that uses stripe billing. Later on, I want to integrate my saleor application with the django API. Can someone tell me the sequence of steps I need to do? I am new to this and would appreciate the help! -
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?)