Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: 'int' object has no attribute 'course'
i filter a course using id, i got the profile of the course creator and i want to add the user that purchsed the course the course_creator students, but i keep getting this error 'int' object has no attribute 'course' views.py @require_http_methods(['GET', 'POST']) def payment_response(request, user_course_id=None): status=request.GET.get('status', None) tx_ref=request.GET.get('tx_ref', None) if status == "successful": if user_course_id: user_course = UserCourse.objects.filter(id=user_course_id).update(paid=True) profile = Profile.objects.get(user=user_course.course.course_creator) profile.my_students.add(user_course.user) student_profile.my_courses.add(user_course.course) student_profile.save() profile.save() user_course.save() return render(request, "payment/payment-success.html") else: return render(request, "payment/payment-failed.html") if status == "cancelled": return render(request, "payment/payment-failed.html") -
Django Custom User Admin won't show Groups
I have created a custom user group. I have been looking online and the solutions that I see don't do the trick. I don't get any errors, but it is not working as expected. Can you help me out? Account App models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class Country(models.Model): country_name = models.CharField(max_length=150, unique=True, null=False) class Meta: verbose_name_plural = 'Countries' def __str__(self): return self.country_name class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, address, city, state, post_code, country, phone, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must provide a user name') if not first_name: raise ValueError('Users must provide a first name') if not last_name: raise ValueError('Users must provide a last_name') if not address: raise ValueError('Users must provide an address') if not city: raise ValueError('Users must provide a city') if not state: raise ValueError('Users must provide a state/province/region') if not post_code: raise ValueError('User must provide a postal code') if not country: raise ValueError('User must provide a country') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, address=address, city=city, state=state, post_code=post_code, country=Country(pk=country), phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, address, city, state, post_code, country, phone, password=None): user = self.create_user( … -
Django cannot access context variable in Jinja template
I am unable to access the context variable in the Jinja HTML template. The following is the code. view.py class Home(views.APIView): renderer_classes = [TemplateHTMLRenderer] def get(self,request): user, context = home(request) self.user = user return Response(context) def get_template_names(self): #code to return the correct HTML template return [template_name] The call "home(request)" in the "get" return a user object and dict. The following is the code def home(request): #user = get_user(name) #lines of code context={"form":form,'questions':get_questions(),'user_ques':user_questions,'dates':dates} Now, in the template I can access "questions" and dates variable. I cannot access the initial values of "form". The "form" is of type "forms.Form". When I debug, I can see the values are populated in the form variable, but when I check on the template side, they are "None". The same to "user_ques" is a dict of values, but on the template side its "{}". I am not sure what is happening. Any direction will help ! -
Setting Up Django. Stuck on Models. Going through the tutorial. Not Sure what to do
I am doing the tutorial on django for an assignment. I am doing it step by step. I got an issue when I copied and pasted the suggested code and am unable to do the last few steps on models. Please let me know how to move forward. It is really frustrating when the guide I am following is unable to offer assistance.image of VScode code editor for models -
Pass variable from template to view django
The main goal is to click a link then have a plot be generated based on the link clicked. I think if I am able to some how pass a variable(string needed for bar plot) from the link clicked on the template, to the views I can create the plot. In short, I would click the link this passes a variable to the views then the views would create a plot and pass it to a template. Any help is appreciated -
Storing password works but logging in doesn't
Trying to store the pw hashed works but trying to login with the first_name + last_name doesn't work. Etc if the combined pw is named ThisPw I should be able to store it hashed and then login with it. if add_form.is_valid(): post = request.POST print(post['email']) new_password = post['first_name']+post['last_name'] new_user = Profile.objects.create_user( email = post['email'], password=make_password(new_password), first_name=post['first_name'], last_name=post['last_name'], phone_number=post['phone_number'], ) print(new_password) new_user.save() print(add_form) return redirect('add') -
What is the proper syntax to call this Django view from another view?
I am trying to call the existing view below from a different view file in my Django project. I'm not fully understanding what the proper syntax would be to call this existing view to create a new folder. What would be the proper syntax to make a call to this view? What would I pass in to this function? def handle_folder_creation(request, conversation_id): """ Creates a folder POST parameters are: parent_uuid -> uuid of parent (if being created within some other folder) staff_only -> if staff_only shared -> if shared name -> folder name :param request: :param conversation_id: :return: """ folder_name = request.data.get('name') if not folder_name: return HttpResponse(status=422, content="No new name provided") staff_only = request.data.get('staff_only', False) shared = request.data.get('shared', False) parent_uuid = request.data.get('parent_uuid', None) parent_folder = None if parent_uuid: parent_folder = Folder.objects.get(uuid=parent_uuid) conversation = Conversation.objects.get(pk=conversation_id) folder = Folder( name=folder_name, parent=parent_folder, staff_only=staff_only, shared=shared, conversation=conversation, created_date=datetime.now(), modified_date=datetime.now() ) folder.save() return HttpResponse(status=200) -
No module named 'django' - uWSGI and python venv issue
I tried to use uWSGI with my django application for testing, but I got the error. Traceback (most recent call last): File "./sitefirst/wsgi.py", line 12, in from django.core.wsgi import get_wsgi_application ImportError: No module named 'django It seems uWSGi is not activating my Python venv, fisrtsite. I use the following command. uwsgi --http :8080 -H /home/mo/firstsite --chdir /home/mo/sitefirst -w sitefirst.wsgi My venv fisrtsite has python 3.7 and has Django. uWSGi comes with Python 3.5.2 and this version does not have have Django. I created venv called fisrtsite and install Django and created test Django project. I installed uWSGI globally to create less friction in handling multiple Django projects. sudo apt-get install python3-dev sudo -H pip3 install uwsgi I am sure that uwsgi installed successfully. I tested using a simple python file and it works. My linux server is Ubuntu with python 2 as default. Any help and thought would be appreciated. -
Django alert is not appearing
I need help with my Django app : I'm trying to use Django messages framework to display a message. And I don't know why my message is not showing up? views.py : from django.contrib import messages def login(request): return render(request, 'authorisation/login.html', {}) def register(request): if request.method == 'POST': email = request.POST['email'].replace('', '').lower() password1 = request.POST['password1'] password2 = request.POST['password2'] if not password1 == password2: messages.error(request, "Passwords do not match") return redirect('register') if User.objects.filter(email=email).exists(): messages.error( request, "A user with the email address : {} already exists, please use a different email".format(email)) return redirect('register') my settings.py : from pathlib import Path import os from django.contrib import messages # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent MESSAGE_TAGS = { messages.DEBUG: 'info', messages.INFO: 'info', messages.SUCCESS: 'success', messages.WARNING: 'warning', messages.ERROR: 'danger', } code in my template : {% for message in messages %} <div class="alert alert-{{ messsage.tags }} mb-4" role="alert"> {{ messsage }} </div> {% endfor %} {% block body %} {% endblock %} when I tried to check the page source I found : <div class="alert alert- mb-4" role="alert"> </div> -
Update a row in a Django data base based on a column value
I am new to Django and specifically Models and have been struggling to understand how to update data in the data base. Models.py: # Create your models here. class logTimes(models.Model): fast_finshed = models.BooleanField(default=False) start_date_time = models.DateTimeField('start fast') end_date_time = models.DateTimeField('end fast') In my View, I have a function to add a row of data when submitting one of two forms that will either add a new row of data or update an existing row of data. I cannot figure out how to make the update I have tried too many things to write here. I have been reviewing the Django docs and not making progress at all. Views.py: #function to add a fast to the data base or update the last fast with an end date and time def start_or_end_fast(request): #If starting fast, update the data base with fast_finished = False #A new fast start date and time using current date and time #A specific end date and time set in the future if request.method == 'POST' and 'start_fast' in request.POST: l = logTimes(fast_finshed=False,start_date_time=datetime.now(),end_date_time=datetime(year=2023, month=1, day=1, hour=12, minute=00, second=00)) l.save() print('fast started') return render(request,'startandstoptimes/index.html') #If ending a fast, find the last fast that has the specific end date and time … -
sort_order does not change from toogle sort button in Django Crispy forms
I am using django crispy forms and I have a toogle sort button to sort by asc or desc order. I have a SearchForm like this: class SearchForm(forms.Form): """Text-searching form.""" ... sort_order = forms.CharField(required=False, widget=forms.HiddenInput) .... def __init__(self, user, language=None, show_builder=True, **kwargs): """Generate choices for other components in the same project.""" self.user = user self.language = language super().__init__(**kwargs) self.helper = FormHelper(self) self.helper.disable_csrf = True self.helper.form_tag = False self.helper.layout = Layout( Div( .... Div( Field("sort_by", template="snippets/sort-field.html"), Field("sort_order", template="snippets/sort-order.html"), css_class="btn-group search-group sort-field", role="group", ), css_class="btn-toolbar", role="toolbar", ), .... ) I have the sort-header.html like this: <div class="btn-group sort-order" role="group"> <button type="button" class="btn btn-default search-field query-sort-toggle"> <span title="Ascending" class="search-icon active asc">{% icon "sort-ascending.svg" %}</span> <span title="Descending" class="search-icon desc">{% icon "sort-descending.svg" %}</span> </button> <input type="hidden" id="id_sort_order" name="sort_order" value="{{ sort_order|default:'asc' }}" aria-label="{% trans "Sort Order" %}" /> </div> and jquery for handling click event on sort order button: $(".query-sort-toggle").click(function () { var $this = $(this); var $label = $this.find("span.search-icon"); $label.toggle(); var sort_order = $label.attr('class').replace('search-icon active', '') var $toggleInput = $this.closest(".sort-order").find("input[name=sort_order]"); $toggleInput.val(sort_order) .... if ($this.closest(".result-page-form").length) { $this.closest("form").submit(); } }); When the button is clicked, the inactive span gets hidden by this css: .query-sort-toggle span:not(.active) { display: none; } I have this toggle button and form gets … -
how can i iterate through a Json response and save the data in a database in python (Django)
def lipa(request): response = requests.get('https://9b4b-154-159-237-44.in.ngrok.io/others/callback/') data = response.json() if response and response.status_code == 200 else None # for d in data: # print(data) for d in data.values(): id = d['ID'] requestID = d['CheckoutRequestID'] resultCode = d['ResultCode'] receiptNumber = d['MpesaReceiptNumber'] phoneNumber = d['PhoneNumber'] amount = d['amount'] # checking if the transaction exists in the database if Payment.objects.filter(secondary_key_id = id, tiny_pesa_id = requestID, code = resultCode, msisdn = phoneNumber, amount= amount).exists(): return JsonResponse({ "id": id}) else: e = Payment.objects.create(secondary_key_id = id, code=resultCode, amount = amount, msisdn = phoneNumber, tiny_pesa_id = requestID, mpesa_transaction_id = receiptNumber) e.save() d = TinyPesaPayment.objects.create(status=resultCode,msisdn=phoneNumber,amount=amount,mpesa_transaction_id=receiptNumber, tiny_pesa_id=requestID) d.save() return JsonResponse({ "amount": amount}) -
Why does django-filter uses None value from choices defined for model field
Why does django-filter uses None value from choices defined for model field along with it's empty value label used for not filtering by certain field? Let's say, we have the following field in some model: FRUIT_CHOICES = [ (None, 'Choose one fruit'), ('AP', 'Apple'), ('BA', 'Banana'), ('KI', 'Kiwi'), ] SomeModel(models.Model): fruit = models.CharField(max_length=2, choices=FRUIT_CHOICES) And a filter defined for this model: class FruitFilter(django_filters.FilterSet): class Meta: model = SomeModel fields = ['fruit'] And this is the HTML we get: <select name="fruit" id="id_fruit"> <option value="" selected="">---------</option> <option value="">Choose one fruit</option> <option value="AP">Apple</option> <option value="BA">Banana</option> <option value="KI">Kiwi</option> </select> Basically, I can fix this by specifying choices for field in my filter form one more time but I feel like this would be dirty since I have a lot of choice fields in my model. I have been really struggling trying to fix this but it seems like either there is no information about this or I can't find right words to google it. Any help is greatly appreciated! -
sort products by rating high-low low-high
Am trying to setup so my products on the products site can be sorted by the rating high-low and low-high and show the none rated behind them. I cant seem to figure it out so any help would be appreciated. I added the code ithink is needed if you need anything more i will add it. Thanks in advance. views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.db.models.functions import Lower from .models import Product, Category, Review from .forms import ProductForm, ReviewForm # Create your views here. def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You … -
HttpResponse + x and Y 'not acccesed Pylance'
I've been searching online for information here but not getting anything specific. Because of this error I can not use the Debug in VS (no variables appear) Although the server works fine (granted, I'm not calling the variables to be seen via the webpage) from django.shortcuts import render from django.http import HttpResponse # Create your views here. def say_hello(request): x = 1 y = 2 return render(request, 'hello.html', {'name': 'Sir Pickles'}) -
How to fetch events from Google Calendar API in Django?
Hey I am beginner in working with API's, I am trying to make a webapp which basically begins with Oauth login, and then fetches the events from Calendar. I made a basic login page with the help of this blog. Now I am not sure how do I begin with? How do I use Google Calendar API's to fetch events. If someone could guide or provide some resources for beginners it would be great. Thanks! -
PHP REST API Server send multiple data to client
I have PHP REST API Server. My client is written in python, client only sends request to my server and sometimes uploading file etc. My php script calling 9 functions. Each function changes string. I want to send this changed string to my client (python) after each function. Like in php file; $result = func1(); // it takes 5 seconds for example echo $result; $result = func2(); // it takes 5 seconds for example echo $result; ... But it only shows result when php script finished. I want to show it when each function returned data. I tried flush, ob_flush but it didn't work I think because of has not GUI (REST API). Maybe should I use django? Or better ways? I hope it was understandable, Thanks! -
Overloading and strategy pattern Python
I'm trying to write an email delivery system. I have this enum, for all users, users that were logged in the last 3 months and 6 months: class Receiver(enum.Enum): ALL = "ALL" THREE_MONTHS = "THREE_MONTHS" SIX_MONTHS = "SIX_MONTHS" The problem is, I'm trying to implement a Strategy pattern, so I need to enforce type checking. I know it is impossible by default, but ... any idea would be appreciated. I need it to look like: def send_to(Receiver.ALL): pass def send_to(Receiver.THREE_MONTHS): pass def send_to(Receiver.SIX_MONTHS): pass Yeah, I have Java background, so I'm trying to do method overloading here. And the general sender would pass the value accordingly: @api_view(["POST"]) def send_email(request): email_to = request.data["emailTo"] send_to(email_to) Note: I do not want to write multiple if checks or switch cases. It totally contradicts with Open Closed principle of Uncle Bob, since if there is gonna be additional case, then the method must be modified. Absolutely unacceptable. -
dockerized django build : how to run only once createsuperuser
I have a django docker container for the backend on my website. There is a volume for the database so i can save the database even if i change the backend configuration. I have tried to put the createsuperuser in my Dockerfile and in a script launched with "command" in docker-compose. But it seems the command is re-run each time the container starts or is rebuilt. I would like this command to be run only once, but i dont know how to proceed. The problem is the container is rebuilt in my ci/cd pipeline if i change the configuration files, and so the command is re-run in the Dockerfile in that case. I have seen this post Run command in Docker Container only on the first start but that also works only if the container is not rebuilt. A workaround with a createsuperuser command that would fail would work and that seemed to be the case with django previous versions (before version 4) but i now have "django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username" error which tells me the command seems to be run multiple times and gives me errors in the database... -
I want to make my own Gmail using Django, how can I?
My question is about creating my own Gmail using Django. I have no idea about that and need your suggestions and advices. -
Django Framework "User has no userprofile." Error
Was trying to replicate the code of this lesson https://jnpnote.com/following-django-tutorial-crm-part11/ Here is the text of the error: RelatedObjectDoesNotExist at /agents/create/ User has no userprofile. Got error while replicating the following code. Could you please help me to avoid the error class AgentCreateView(LoginRequiredMixin, generic.CreateView): template_name = "agent_create.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent-list") def form_valid(self, form): agent = form.save(commit=False) agent.organisation = self.request.user.userprofile agent.save() return super(AgentCreateView, self).form_valid(form) As i guess i can't get the userprofile parameters properly. -
How can I remove a many to many relashionship from javascript?
If I need to add a reference between two objects I can do post.likes.add(user) but what shoudl I do if I wanted to remove it? -
How to add custom CSS for form labels to dynamically built Django forms?
I have a django form for which I need to increase the font size of the labels. Based on this StackOverflow discussion, what I need to do is add a CSS class and apply it to the control-label. How do I actually go about doing that? My form is populated like so: class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) fields_to_add = { # many fields here, but all in this format. Removed for brevity. 'purchase_order_number': forms.ChoiceField( label="Purchase Order", choices=purchase_order_numbers), } self.fields.update(fields_to_add) self = add_classes(self) The add_classes code is as follows: def add_classes(self): """Add styling to form inputs.""" for key, value in self.fields.items(): self.fields[key].widget.attrs.update( {'class': 'form-control', # <- this is what I expect to change 'style': 'font-size: large',} ) return(self) I assume I need to modify add_classes to add some form of label-control or a custom class, but I don't really know how to actually make that change. -
Respuesta de Django se pierde y no llega la promesa al fetch
Tengo un formulario el cual recibe js para realizar una serie de validaciones y enseguida por fetch envió la información al servidor (una api sencilla). La verdad no tengo muy entendido en sí por qué se da el error, cabe recalcar que en desarrollo funcionaba perfecto pero ahora que está en producción alojado en heroku se produce dicho problema, el código fetch es el siguiente. formulario.addEventListener('submit', (e) => { e.preventDefault(); fetch('https://portafolioadrian.herokuapp.com/contacto', { method: 'POST', body: JSON.stringify({ nombre: document.querySelector('#nombre').value, correo: document.querySelector('#correo').value, telefono: document.querySelector('#telefono').value, mensaje: document.querySelector('#form__message').value, terminos : document.getElementById('terminos').checked, }), headers: { 'X-CSRFToken': getCookie('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json'} }) .then(res => res.json()) .then(res => { if (res.success) { formulario.reset(); document.getElementById('form__message-success').classList.add('form__message-success-active'); setTimeout(() => { document.getElementById('form__message-success').classList.remove('form__message-success-active'); }, 5000); document.querySelectorAll('.form__group-correct').forEach((icono) => { icono.classList.remove('form__group-correct'); }); }else{ document.getElementById('form__message').classList.add('form__message-active'); } }) }); Al momento de enviarlo, por consola me sale el siguiente error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Y en la sección de network el estatus al momento de realizar el POST es 301 Moved Permanently, he investigado algo y trata hacerca de redirecciones pero no encontré solución. El urls.py de la app es esta: urlpatterns = [ path('', views.contacto, name='contacto'), path('mensajes/', views.mensajes, name='mensajes'), ] Y la view es la siguiente: … -
How can I get my html page to refresh upon completion of a django function?
I keep getting an error related to the csrf token when I try to employ consecutive submissions, and refreshing the page seems to work. The purpose of the program is to create zip files, so I figured the easiest solution would be to have the web page automatically reloaded once the zip file is done being created from the function in the views.py file and available for the user to open. The main issue I'm having is how to actually do that. Here is the code for my HTML file: {% load static %} <html> <head> <link rel="stylesheet" href="{% static '/styleSheet.css' %}"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edstore"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--BOOTSTRAP ASSETS--> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <div class="main_Body"> <div class="section"> <h1>Fileconverter</h1> <br> <label for="file_field" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i>Updload File(s)</label> <input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple> <label id="file_name"></label> <br> <br><br><br> <br> <input type="submit" class="file-submit__button" id="submitButton"> <!--onclick="formDisableButton"--> </div> </form> </body> <footer> <p>Click "Choose File(s)" and select the files you want to convert.</p> <p>Once you click "Submit" the job will start.</p> <p>Upon completion, a zip folder will be downloaded in your browser.</p> <p>Do not click the submit buttons multiple times. If the …