Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display model attributes in django on web app
I am creating a portfolio site with djnago. Now suppose i have a blog and i want to show the blog title,small summary and the link. I've created a model as below: class Blog(models.Model): blog_title=models.CharField(max_length=50) summary=models.TextField(blank=False) blogLink=models.URLField() def __str__(self): return self.blog_title def get_summary(self): return self.summary def get_link(self): return self.blogLink I can fill these values in the admin page but how can i show it in the web app so that other people can access the links. I also have a context processor to user details like first name etc. Should i have different context processors for different classes that I create. Just a beginner and trying out projects to skill myself I -
How can I make update form without modelForm?
I've made a Feedback form where people can share their views. Then I created an update form using the HTML. What will be the views for def UpdateFeedback()? I tried many ways but I couldn't perfectly. Please help me... Note: The feedBack form and UpdateFeedback will be on the same page. views.py: def feedBack(request,quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: try: ProductREVIEWS.objects.create( user=request.user, product=quick_view, feedBACK=request.POST.get('feedBACK'), ) return redirect('quick_view', quick_view_id) except: return redirect('quick_view', quick_view_id) else: return redirect('quick_view', quick_view_id) def UpdateFeedback(): What will be the relevant code here? models.py: class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) urls.py: path("feedBack/<int:quick_view_id>/", views.feedBack, name="feedBack"), Update feedback html form: <form action="{% url 'feedBack' quick_view_id=quick_view.id %}" method="POST" autocomplete="off"> {% csrf_token %} <select name="UpdateRating" style="font-size: 13px;" id="UpdateRating" class="form-control"> <option value="{{feedBack.rating}}" style="font-size: 13px;">{{feedBack.rating}}</option> <option value="1" style="font-size: 13px;">1</option> <option value="2" style="font-size: 13px;">2</option> </select> <textarea id="UpdateFeedBack" rows="6" style="font-size: 13px;" class="form-control" name="UpdateFeedBACK" value="" required>{{feedBack.feedBACK}} <button type="submit" class="btn ms-auto btn-success" style="font-size: 13px;">Update</button> </form> -
Django - AttributeError at / 'function' object has no attribute 'objects'
I been getting this error. I dont know why my view and model names are different still im getting that error in django. This is my models.py from django.db import models class data(models.Model): id = models.IntegerField(default=1, unique=True, primary_key=True) name = models.CharField(max_length=50) location = models.CharField(max_length=50) date = models.DateField() class Meta: verbose_name_plural = 'datas' def __str__(self): return self.name This is my views.py from appplus.models import data def dashboard(request): last_added = data.objects.order_by('date')[:5] context_dict = { 'last_added' : last_added } return render(request, 'appplus/home.html', context_dict) -
How do you implement input( or form) dependent on a select menu(drop down list)?
I'm working on grading system and I'm currently working on the form that's deals with the user entering the students results now the form I have, has 2 drop-down list(classroom, students) that are dependent. The issue and where I'm stuck is When the user select the classroom the second drop-down menu will only show the students in that class, I have already figure that out..the issue is I want the input fields for how much subject the student is doing to appear so that the user can enter the grades for each subject specific to that student in the class Eg if I select classroom 1b and selected student Mary.. if Mary is doing 5 subjects then 5 input field should appear so that I can enter the mark for the subjects Link with a video showing what I'm talking about video showing an examplehttps://drive.google.com/file/d/11FoCZyOBVdUhTcvCqA1Ke0fEgRmMVC-G/view?usp=drivesdk **Models.py** Class Classroom(models.Models): name = models.charfield() Class marks (models.Models): classroom = models.foreignkey(Classroom) Grade = models.Floatfield() **Html form** <div class="container-fluid"> <form id="result-form" method="post"> {% csrf_token %} <!-- Modal --> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row"> <div class="col-md-12" id="msg8" style="font-size: 2rem; … -
Create Alert Message Before Saving Page
I am trying to create a alert message before saving the page in django, how i can do it .I need to create a message that after saving the page you can not edit the page . -
installing mysqlclient locking failed
I am using python3.9 in django framework, for that I have to install mysqlclient. But error is coming when I try pipenv install mysqlclient output like this as error: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Adding mysqlclient to Pipfile's [packages]... Installation Succeeded Pipfile.lock (06f36b) out of date, updating to (f95eff)... Locking [dev-packages] dependencies... Locking [packages] dependencies... Resolving dependencies... Locking Failed! CRITICAL:pipenv.patched.notpip._internal.resolution.resolvelib.factory:Could not find a version that satisfies the requirement django (from versions: none) [ResolutionFailure]: File "C:\Users\meghd\anaconda3\lib\site-packages\pipenv\resolver.py", line 743, in _main [ResolutionFailure]: resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) [ResolutionFailure]: File "C:\Users\meghd\anaconda3\lib\site-packages\pipenv\resolver.py", line 704, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "C:\Users\meghd\anaconda3\lib\site-packages\pipenv\resolver.py", line 685, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "c:\users\meghd\anaconda3\lib\site-packages\pipenv\utils.py", line 1377, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "c:\users\meghd\anaconda3\lib\site-packages\pipenv\utils.py", line 1106, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "c:\users\meghd\anaconda3\lib\site-packages\pipenv\utils.py", line 884, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely … -
Referring foreign key in a FormModel query all model instances
I'm creating a registration system for programming classes, at some point I want people to choose which batch they want to enroll in, the Batch model is haveing a foreign key to Program model model.py class Program(models.Model): id = models.AutoField(primary_key=True) name_english = models.CharField(max_length=64, null=False) name_arabic = models.CharField(max_length=64, null = False) def __str__(self): return(self.name_arabic) class Batch(models.Model): id = models.AutoField(primary_key=True) program = models.ForeignKey(Program, on_delete=models.CASCADE) number = models.SmallIntegerField() starting_at = models.DateField() def __str__(self): return (f"{self.program}") Then I'm creating a formset from the Batch model form.py class new_program_formset(ModelForm): class Meta: model=Batch fields = "__all__" new_program_formset = modelformset_factory(model=Batch, fields="__all__") Then I'm passing it through the view to the template views.py return render(request, "registration/program_registration.html", { "forms": new_program_formset(), "progress": 40, "quote": quote, }) HTML template <div class="form-outline text-center"> {% for form in forms %} <label class="form-label">{{ form.program }}</label> <div> <p>{{form.starting_at}}</p> </div> {% endfor %} </div> The problem is when I'm referring form.program it queries all instances in the program model I want to get the one program associated with the selected Batch. -
Is it possible to fill out the fields of Django's UserCreationForm in python function?
I already have a Registration form on my ecommerce site. Now i would like to use Django's inbuilt validation system. Therefore, as far as i understood, i have to use a form that is provided by Django, e.g. UserCreationForm. But since i already have a form, i thought i could transfer the user information from my own form into some Django form in the backend. I have tried the following: forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60) class Meta: model = User fields = ("username", "email", "password1", "password2", "first_name", "last_name") utils.py, containing the function, that is going to be called in views.py: # does not return anything, since form.save() handles registration def signup(request): form = RegistrationForm() # transfer the data from my_custom_view to Django's UserCreationForm form.fields["username"].value = request.POST["username"] form.fields["first_name"].value = request.POST["firstname"] form.fields["last_name"].value = request.POST["lastname"] form.fields["email"].value = request.POST["email"] form.fields["password1"].value = request.POST["password"] form.fields["password2"].value = request.POST["password_val"] if form.is_valid(): # some message form.save() function above is called within views.py as follows: home_view(request): # some code if request.method == "POST" and "signupbtn" in request.POST: signup(request) register.html: <form class="px-4 py-3" method="POST"> {% csrf_token %} <div class="container"> <input required class="form-control" type="text" name="firstname" placeholder="First Name"> <input required … -
Stripe: Python You must update your Connect branding settings with icon
Currently integrating Stripe Connect and I keep getting the same error stripe.error.InvalidRequestError: Request ********541g: You must update your Connect branding settings with icon in order to create an account link. You can set the missing fields at https://dashboard.stripe.com/settings/connect I have completed everything on Stripe's Dashboard and updated all the branding requirements but I'm now getting this error on my test data. Here is the code below account = stripe.Account.create( country="US", type="express", capabilities={ "card_payments": {"requested": True}, "transfers": {"requested": True}, }, business_type="individual", ) return stripe.AccountLink.create( account=account['id'], refresh_url='https://localhost:3000/', return_url='https://localhost:3000/', type="account_onboarding", ) Is there anything else I need to add? -
converter text to hex and than to base64 using Django-python
I'm using Django I want to convert text to hex and than base64 I tried to do like this: # create text or number and convert them to integer # txt = "ABC" txt_to_int = int(txt,16) print(txt_to_int) >> 2748 # convert them to hex txt_to_hex = hex(txt_to_int) print(txt_to_hex) >> 0xabc # convert to base64 hex_encode = txt_to_hex.encode('utf-8') hex_to_base64 = base64.b64encode(hex_encode) base64_decode = hex_to_base64.decode("utf-8") print(base64_decode) >> MHhhYmM= I am using Online Text To Hex Converter Tool I want result as: https://string-functions.com/string-hex.aspx after Converter : text to hex: (ABC) to hex (414243) https://base64.guru/converter/encode/hex after Converter : Hex to Base64 (414243) to base64 (QUJD) I want to do them by django-python any help I will appreciate -
object has no attribute 'is_active' Django
AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'oauth2.auth.DiscordAuthenticationBackend', ] I have two backends, and when I try to go to localhost:8000/admin, 'oauth2.auth.DiscordAuthenticationBackend' backend works, not 'django.contrib.auth.backends.ModelBackend', how to fix this? -
How to apply select_related to the objects of a m2m relationship in Django?
Lets say there is a structure like this: class Aaaaa(models.Model): b = models.ManyToManyField('b') class Bbbbb(models.Model): c = models.ForeignKey('c') class Ccccc(models.Model): x = models.CharField(max_lenght="3") Now I'm in the DetailView of Aaaaa. I do prefetch_related('b'). But how can I let django know to get all the "Ccccc" as well? Sorry, I'm sure this has been asked a lot, but for some reason I just can't find it. -
Django Admin: Populate admin fields based on table row selection
I need some help to import values of items (saved on database from previous orders) based on client search by id. This must happen after the user click a button inside admin panel. So, when button 'Importar do histórico' is clicked Fields that need to be filled one window will open with all history of items of that client (presented as a table with django_tables2) Table with results of query based on client id So, when I click one of the rows of the table that values must fill the fields inside the admin panel. Below part of my 'admin.py'. The model 'pedido_item' is an inline of model 'pedido'. class itensInline(admin.StackedInline): form = pedidoItemForm model = pedido_item formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'10'})}, models.Choices: {'widget': Select(attrs={'size':'20'})}, } raw_id_fields = ('cd_pedido',) radio_fields = {'cd_tipo_fixacao_encosto': admin.HORIZONTAL, 'cd_tipo_fundo_encosto': admin.HORIZONTAL, 'cd_tipo_cor_fundo_encosto': admin.HORIZONTAL,'id_montagem': admin.HORIZONTAL} fieldsets = ( ('Dados Obrigatórios', { 'fields': (('quantidade'),('modelo_ar','modelo_a'),('modelo_er','modelo_e'),'tecido','cd_tipo_fundo_encosto','cd_tipo_cor_fundo_encosto','cd_tipo_costura','cd_tipo_fixacao_encosto','fixacao_encosto') } ), ('Tipo de Montagem',{ 'fields' : ('id_montagem',) } ), ('Montada em base',{ 'classes' : ('base','pretty'), 'fields' : ('base', 'opcao_braco','braco') } ), ('Somente Estofamento',{ 'classes' : ('est','pretty'), 'fields' : ('porca_garra',) } ), ) class Media: js = ('admin/js/vendor/jquery/jquery.js','admin/js/jquery.init.js','js/admin.js','js/importar.js','js/autorizarPedido.js','js/importarPopup.js') extra = 0 def has_edit_permission(self, request): return False class processoInline(admin.StackedInline): model = pedido_historico exclude = … -
Related field not populating in the response in Django rest framework
Have two models: class Topic(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) class SubTopic(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) and have two serializers: class SubTopicSerializer(serializers.ModelSerializer): class Meta: model = SubTopic fields = ('topic', 'name', 'display_name') class TopicSerializer(serializers.ModelSerializer): sub_topics = SubTopicSerializer(many=True, read_only=True) class Meta: model = Topic fields = ('id', 'display_name', 'sub_topics') the subtopics are not populating in the response of the Topic serializer. -
Django Channels - Get a list of all active sessions, or execute something when a session is "closed"
I'm using WebsocketConsumer, and storing data user-related on the cache, I'm tying this to both, user and session user = self.scope["user"] session = self.scope["session"] and when the WebsocketConsumer disconnected, I clean all the data related to this session and user from channels.generic.websocket import WebsocketConsumer class MyConsumer(WebsocketConsumer): def connect(self): self.store_session_data() def disconnect(self, _): self.clean_session_data() def websocket_disconnect(self, _): self.clean_session_data() I'm doing this because a user may have multiple tabs opened on the same application, and so have multiple sessions, and I don't want a tab to clean something that might be valuable for the second tab If the user disconnects as expected, everything goes right But if the browser is closed, neither the disconnect nor the websocket_disconnect are called. And the data related to the previous session remains untouched Questions A) Is there a way to execute something no matter how the WebsocketConsumer is closed? B) An alternative way would be to get all active sessions and clean anything related to a non-active session Is it feasible? I couldn't find how to do it either Any thought? -
How to create a new session for all new users in django
A few weeks ago i've started a project on django. Now i'm about to finish it, but while i'm testing it i've noticed that, when i've uploaded it on heroku it worked well, but only on one device a time, i don't know why but when there are more than one device connected, the app doesn't create a new session , but it refresh the existing one. So if i'm connected as user1 on my phone, and then i connect on the app but on another device, it show me the session of user1. I think the problem is because i've written most part of the code in the view section. how can i fix this? this is my app link: https://secure-password-manager.herokuapp.com -
Django Channels Websocket hanging - WebSocketProtocol took too long to shut down and was killed
Environment: Ubuntu 16.04.6 conda 4.12.0 Apache/2.4.18 (Ubuntu) python==3.8.1 Django==4.0.3 channels==3.0.5 asgi-redis==1.4.3 asgiref==3.4.1 daphne==3.0.2 I am attempting to create a websocket service that only relays messages from redis to an authenticated user. Users do not communicate with each other, therefore I don't need Channel layers and my understanding is that Channel layers are an entirely optional part of Channels. I'm simply trying to broadcast messages specific to a user that has been authenticated through custom middleware. I have custom auth middleware that takes an incoming session id and returns the authenticated user dictionary along with a user_id. I'm also attaching this user_id to the scope. I have elected to route all traffic through daphne via Apache2 using ProxyPass on port 8033. This is preferred since I'm using a single domain for this service. However, I'm really struggling to maintain a connection to the websocket server, particularly if I refresh the browser. It will work on the first request, and fail after with the following message in journalctl: Application instance <Task pending name='Task-22' coro=<ProtocolTypeRouter.__call__() running at /root/miniconda2/lib/python3.8/site-packages/channels/routing.py:71> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f658c03f670>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 46010] path=b'/ws/userupdates/'> took too long to shut down and was killed. After spending hours on … -
What's the best way to store time ranges with django and mySQL? Example - 8am to 12pm
I have a requirement for my project where a user can select either time slots such as 8am-9am, 10am-11am, etc. OR select a wide time range such as 8am to 12pm, 12pm to 3pm, 3pm to 6pm, etc. I am using django as the back end for this project and haven't found the exact field type I'm looking for my model other than possibly DurationField. Does anyone have ideas they could share? -
TypeError at /booking render() got an unexpected keyword argument 'renderer'
TypeError at /booking there is an error when i a clicked on booking page of my site , https://hostclinic.pythonanywhere.com/ [forms.py] from django import forms from .models import Booking class DateInput(forms.DateInput): input_type = 'date' class BookingForm(forms.ModelForm): class Meta: model = Booking fields = '__all__' widgets = { 'booking_date': DateInput(), 'dob': DateInput(), } labels = { 'p_name': 'Patient Name', 'dob': 'Date of Birth', 'phn': 'Phone', 'email': 'Email', 'gender': 'Gender', 'department':'Departments', 'doctor':'Doctors', 'blood_group': 'Blood Group', 'address': 'Address', 'district': 'District', 'sub_branch':'Sub Branch', 'booking_date': 'Appointment Date', } -
How to use prefetch_related on two M2M values?
I want to prefetch_related to two level of M2M values, models.py class A(models.Model): name = models.CharField(max_length=40) b = models.ManyToManyField('B') class B(models.Model): name = models.CharField(max_length=40) c = models.ManyToManyField('C') class C(models.Model): name = models.CharField(max_length=40) d = models.ManyToManyField('D') And my ORM is a_obj = A.objects.all().prefetch_related('a__b__c') And I am trying to access the values like below, Method A: for each_obj in a_obj: print(each_obj.a__b__c) Method B: for each_obj in a_obj: print(each_obj.a.all()) Method A throws an error saying No such value a__b__b for A found Method B doesn't throw any error, but the number of queries increases to the length of a_obj. How to access a__b__c in a single query? -
Django Filter and Sum Value depends on different model
_Hi, guys! I'm trying to sum times for users for each Month(Mission), like this: times = goal.time_set.filter(day__year=today.year, day__month=today.month) Then I will sum: for time in times: total_min[member_number] = total_min[member_number] + time.value But it calculates for current Month(Mission). I want to calculate time depends on object model Mission. Model Mission: class Mission(models.Model): name = models.CharField(max_length=200, default='') description = models.TextField(default='') add_info = models.TextField(default='', blank=True) theme = models.ImageField(upload_to='themes/', default='themes/default.png') date_created = models.DateTimeField(null=True) date_finished = models.DateTimeField(null=True, blank=True) Like this I think: times = goal.time_set.filter(day__year=mission.date_created.year, day__month=mission.month_created.month) How can I achieve it? -
django project before every web project
I learned html css javascript then i started learning django as backend bcoz i am very good in python so now i learned django but i have one question we only use django for website like django serves html css javascript by its own so whenever i need to create any website first i need to create django project and then integrate my html css in it and server it. so what i mean is we learn html css separately but when creating a website like with django we integrate or generate html dynamicaly on the server side and send it to the user -
UUIDField vs Charfield with a UUID in it?
So I've been using UUIDs in a CharField as PKs for a lot of things on a project I'm working on, works fine, no issues. If I use a UUIDField, certain things in the backend will have issues with a UUID field (usually functions that expect the UUIDs to be a string). Is there any advantage of using a UUIDField vs just having 'default=uuid.uuid4' in a CharField? -
Why we need to specify read_only=True when dealing with foreign key related field in a serializer in Django rest framework?
Why we need to specify read_only=True when dealing with foreign key related field in a serializer in Django rest framework? field_name = RelatedFieldSerializer(many=True, read_only=True) many = True is understood as the foreign key is on the related object. -
inefficient iterarion over Django queryset
I'm trying to speed up the response time of a get request from React to Django. The delay is due to the iteration over a filtered queryset. stop_time_next_hour = StopTime.objects.filter( stop_id=stop_id, # Get all arrival times in the next hour arrival_time__gte=current_time.time(), arrival_time__lte=(current_time + timedelta(hours=1)).time(), ) This is the queryset, which must be iterated over, and with each iteration, a request is sent to the DB leading to slow response times. for stop_time in stop_time_next_hour: if stop_time.trip.service_id == str(service_id): check_trip_for_update(gtfsDict,stop_time.trip.trip_id) The filter is dynamic and is dependent on user input, so the queryset cannot be loaded prior to the get request containing the user input. How can this performance be optimized?