Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get value from foreign kye in DJANGO?
Hey I have 2 models in my models.py: username = models.CharField(max_length=250, verbose_name='username', null=True) refresh_token = models.CharField(max_length=300, verbose_name='refresh_token', null=True) id = models.CharField(max_length=150 ,primary_key=True) login = models.CharField(max_length=250, null=True) avatar = models.CharField(max_length=400, verbose_name='avatar') params = models.ForeignKey('Parametrs', on_delete=models.CASCADE) class Parametrs(models.Model): cost_skip = models.IntegerField(null=True) chat_bot = models.BooleanField(default=False) and in views.py im need to get cost_skip of user. That is TwitchUser => username => cost_skip im tried to find something in docs, but it doesnt help -
why does my API crash without error message when calling cuda?
I built a django API which calls in some routes python functions which use GPU and cuda. When I call these routes the API always crash without an error message. I was thinking it was caused by a lack of RAM so I increased the memory on my server but it still doesn't work. Because there is no error message, I added a lot of print in my code until finding the problem always happend when the python code use cuda. Here is the code which make crash the API : from training.tacotron2_model import Tacotron2 model = Tacotron2().cuda() I tried different things and this one worked perfectly : model = Tacotron2() But it doesn't use GPU so that's not what I want, It just demonstrates the problem is only with cuda. What is the most interesting is that if I run both lines (using cuda) in a python terminal it perfectly works. So why doesn't it work when it's called by my django API ? I can't understand and have this problem with many routes since few days I specify that I use a Nvidia Tesla T4 and that cuda is right installed. I can see it by running nvcc … -
How to modify the request before View Class is invoked?
I already have a ModelViewSet. class ConfigManager(ModelViewSet): queryset = Configuration.objects.all() serializer_class = ConfigSerializer http_method_names = ["post", "get", "patch", "delete"] def perform_create(self, serializer): if Configuration.objects.count(): raise BadRequest( message="Only 1 Configuration is allowed. Try updating it." ) obj = serializer.save() tenant_id = self.request.META.get("HTTP_X_TENANT_ID") cache_config(obj, tenant_id) def perform_update(self, serializer): obj = serializer.save() tenant_id = self.request.META.get("HTTP_X_TENANT_ID") cache_config(obj, tenant_id) def perform_destroy(self, instance): if Configuration.objects.count() <= 1: raise BadRequest(message="One configuration object must exist.") instance.delete() obj = Configuration.objects.all().first() tenant_id = self.request.META.get("HTTP_X_TENANT_ID") cache_config(obj, tenant_id) Now I am trying to create a wrapper for this ViewSet Class, Where I want to perform some modifications to the request before serving it. How can I do this? class ConfigManagerWrapper(ConfigManager): pass -
Access a view which is for logged in users in django testing
Im trying to create some tests for my django project. I had no problem creating the models tests but i get multiple errors when trying to do the views tests. Most of my views depend on a user to be logged in and I cant find the way to log in . Im using the deafult django built-in AUTH system. VIEW : @login_required def fields(request): if request.user.profile.user_package == "Livestock": raise PermissionDenied() field_list = Field.objects.filter(user = request.user) context = { "title": "Fields", "field_list" : field_list, } template = 'agriculture/fields.html' return render(request, template, context) TetCase: class TestViews(TestCase): @classmethod @factory.django.mute_signals(signals.pre_save, signals.post_save, signals.pre_delete, signals.post_delete) def setUpTestData(cls): # Create new user test_user = User.objects.create(username='test_user',password='1XISRUkwtuK') test_user.save() c = Client() profile = Profile.objects.get_or_create(user = test_user, user_package = 'hybrid') c.login(username = test_user.username, password = test_user.password) Field.objects.create(user=test_user,friendly_name='Arnissa') def test_logged_in_user(self): login = self.client.login(username='test_user', password='1XISRUkwtuK') response = self.client.get(reverse('agriculture:fields')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'test_user') # Check that we got a response "success" self.assertEqual(response.status_code, 200) path:path('fields', views.fields, name='fields') and settings if they provide any help : LOGIN_REDIRECT_URL = 'dashboard:index' LOGOUT_REDIRECT_URL = 'login' LOGIN_URL = 'login' On my tests i get the error TypeError: 'NoneType' object is not subscriptable when im checking if user is logged in .If i try … -
Django allauth redirect to signup route for user that registered with password and login with social login
I used Django allauth for user authentication in my app. When a user registers with google account with email and manual password and then tries to login with google social login, Django allauth redirect user to accounts/social/signup/ route and asks user to enter email address and after entering email address, tells user that email address already exist! I read allauth documentation and configurations, but nothing works for me, here is my confirmation in settings.py: ACCOUNT_AUTHENTICATION_METHOD = ('username_email') ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' #### SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_VERIFICATION = "none" SOCIALACCOUNT_EMAIL_REQUIRED = True Any suggestion appreciated. -
django: how to pass .is_valid() condition without filling all parameters
with class TestQuestionList in the post function, I do not need to create a new object, so I do not need some fields, but django requires me to fill in these fields class TestQuestionList(APIView): def __init__(self): self.questions = [1] def get(self, request): romms = TestQuestionBlok.objects.filter(id__in=self.questions) serializer = TestQuestionSerializers(romms, many=True) return Response(serializer.data) def post(self, request, format=None): serializer1 = TestQuestionSerializers(data=request.data) if serializer1.is_valid() : self.questions = serializer1.data['questions'] return Response(serializer1.data, status=status.HTTP_200_OK) return Response(serializer1.errors, status=status.HTTP_400_BAD_REQUEST) How can I bypass these requirements? -
django channels test AsyncConsumer.__call__() missing 1 required positional argument: 'send'
I am using the code below in real environment. When I tried to write the test code, the following error occurred. It also works fine in my local environment. I tried to write the test code looking at channels test, but the error below occurred. What's wrong? routing.py from django.urls import path from .consumers import ExchangeRateConsumer websocket_urlpatterns = [ path("ws/exchange_rate/<str:currency>/", ExchangeRateConsumer.as_asgi()), ] asgi.py application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) tests.py class ChannelTest(TestCase): async def test_channel_connect(self): communicator = HttpCommunicator(ExchangeRateConsumer, "GET", "/exchange_rate/USD") response = await communicator.get_response() error TypeError: AsyncConsumer.call() missing 1 required positional argument: 'send' -
No module named django-admin C:\Program Files\Python39\python3.exe
I have 2 python installed in my system. 1 - python 3.7.x 2 - python 3.9.x I have these 2 versions because I simultaneously work on different Django versions on my laptop. NOTE: I have renamed python.exe to python3.exe for the version of 3.9.x and kept python.exe for 3.7.x as it is. To run my Django == 2.x.x project, I write python manage.py runserver To run my Django == 3.9.x project, I write python3 manage.py runserver But when I try to create a new project using python3 -m django-admin startproject my_project_name it gives me an error of No module name django-admin I don't know why it gives me this error. can anyone guide me? -
How to make reverse for temporary url?
I have source url domain.ex/dir/video.mp4 I have temporary url domain.ex/vlink/temp.mp4 which I need to "connect" to source domain.ex/dir/video.mp4 The same domain. I use nginx to serve source url location /dir/ { alias /media/videos/; } My current urls.py path('vlink/<str:temp>', views.vlink, name='vlink'), view.py def vlink(request, temp): # drop extension mp4 s = temp.split('.')[0] # I retrieve original file name vid = TmpUrl.objects.filter(tmp_url = s).values('orig').first() v = vid['orig'] the_url = '/dir/'+v+'.mp4' return redirect(the_url) template.html <video> <source src="/vlink/{{vid}}.mp4" type="video/mp4"> </video> I don't need simple redirect. I need to hide source url. What I need: when user click play, the browser shows tmp url and play vid without redirect to source. How to do this? -
How to move ListBox items to another ListBox in django using jQuery and insert, update into database?
How to move ListBox items to another ListBox in django using jQuery and insert, update into database? -
ValueError: The view selection.views.register didn't return an HttpResponse object. It returned None instead
I currently work with student management system by using django. in that I found some errors. Anybody can help me. view.py def register(request): try: if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.save() Student.objects.create(user=new_user) cd = form.cleaned_data user = authenticate(request,username=cd['username'],password=cd['password1']) if user is not None: if user.is_active: login(request, user) return redirect('login/edit/') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid Login') else: form = UserForm() args = {'form': form} return render(request, 'reg_form.html', args) except Exception as e: raise e forms.py class UserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] help_texts = { 'username': 'same as your roll no.', } The code doesn't have any errors. It works fine. After filling the form, I click register button. It will functioning and post request also done but returning null value. Anybody can fix this. -
django html regulate input value based on the select option
Here the scenario is that in the html select, there are two options "cube" or "cylinder". and there are three input fields: length, width, and height. what I am looking for is that when user select "cylinder" option from the dropdown menue, there must require user to input the same value for length and width input fields. if not, when click submitting form, there should be an alert to advise users to make sure both length and width value being the same. what is the easiest way to do such work? -
Simple Django Form with Ajax Submission Not Updating Model
I'm trying to write a simple form using Ajax. After multiple attempts, I keep getting "POST /app/emails/ HTTP/1.1" 200 13950 in Terminal, but the model doesn't update (even when I look in the shell). I really would like the abilityt to submit the form within the modal, and update the image behind it. However if that's not possible I can settle for an alternative. Really stuck here, would love any advice! emails.html <div class="modal fade" id="addEmailModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-sm"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Add New Email</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form method="POST" id='add-email'> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="form-group"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close </button> <button class="btn btn-primary" type="submit">Add</button> </div> </form> </div> </div> </div> Javascript $("#add-email").submit(function (e) { e.preventDefault(); alert('working'); $.ajax({ type: 'POST', url: "{% url 'add-emailname' %}", data: { email_name = $(this).email_name, cadence = $(this).cadence }, success: function (response) { alert("Email name successfully added!") $("#add-email").trigger('reset'); //clear the form }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) } views.py def emails(request): context = { 'emails': UserEmail.objects.all(), 'form': EmailCreateForm() } return render(request, 'app/emails.html', context) def addEmailName(request): … -
How to send values from Django views function to Django forms class during runtime?
My Django Template: {% extends 'main/base.html' %} {%block title%}Delete List{%endblock%} {%block content%} <form method="post" action="/delete/"> {%csrf_token%} {{form}} <button type="sumbit" name="Delete List">Delete List</button> </form> {%endblock%} my function inside view: def delete(response): if response.method=="POST": form1 = DeleteList(response.POST) print(f"delete button pressed: {form1.is_valid()}")#just checking if form1.is_valid(): "" print("valid form: {}".format(form1.cleaned_data))#just checking return HttpResponseRedirect("/display") else: #form1 = DeleteList(10) -- iam trying to make this style work...and use a integer value from my database to set maxVaue of a field #Example: form1 = DeleteList(name="test",data2="somedata"...) -- i want this style to work cause I would pass more values to my forms class in future form1 = DeleteList() return render(response,"main/deleteList.html",{"form":form1}) my django forms class: class DeleteList(forms.Form): #i was trying to make this __init__ work but seems to be buggy """def __init__(self,maxValue:int, *args, **kwargs): super(DeleteList, self).__init__(*args, **kwargs) self.fields['id'] = forms.IntegerField(label="Enter id",min_value=1,max_value=maxValue) id = forms.IntegerField()""" #below one is just static, iam trying to replace this with the above commented block of code id=forms.IntegerField(label="Enter id",min_value=1,max_value=10) #-- only this seems to work Now if do form1 = DeleteList(<int value here>) and receive it on __init__ of forms class, I am able to get the values into form and set my IntegerField's max_value, it only seems to work when the form loads the … -
Inventory project. How to total the value of same name objects in queryset in Django
I have multiple breweries with multiple beers. Some are the same. I need to give a company itemized total. This code iterates over the queryset, finds duplicate names, totals the quantity and then adds it to a dictionary. If no duplicate it goes straight to the dictionary. I'm new to Python and Django so the code is elementary and clunky. Please advise me on more elegant and concise methods to solve this problem. Thanks! def index_inventory(request): keg_totals = {} keg_data = Kegs.objects.all() counter = 0 for keg in keg_data: counter2 = counter + 1 while counter2 <= (len(keg_data)) -1: if (keg_data[counter].beer) == (keg_data[counter2].beer): (keg_data[counter2].quantity) =(keg_data[counter2].quantity)+ (keg_data[counter].quantity) counter2 += 1 else: keg_totals[keg.beer] = keg.quantity counter2 += 1 counter += 1 context = { 'keg_totals' : keg_totals, } return render(request, 'inventory/index_inventory.html', context) -
Django validate 2 forms based on each other
I am trying to build an update screen for a project where a user can hide images from their listing as well as adding more images (images are stored as objects in their own right). I therefore have an a form containing an imagefield to upload new images and a separate formset containing checkboxes for each of the existing images. A validation requirement for the site is that each listing must have at least 4 images displayed with it, thus I need a way of validating both the formset (to check how many pictures are checked) and the imagefield (to check how many images have been added) to ensure that these combine to reach at least 4. I have these checks able to work independently (i.e. 4 images uploaded or 4 images selected) but I was wondering if there was a way of combining the validation criteria into 1 clean (meaning I can either call combined_form.is_valid() in my view or alternatively have this integrated into an existing form's form.is_valid() call), or another way of checking this and raising an error if it fails? Sorry if I have completely butchered this explanation, I'm new here and technical terminology isn't my strong … -
How to set up Django for Fastpanel
I used .htaccess Options +ExecCGI AddHandler wsgi-script .py RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /wsgi.py/$1 [QSA,PT,L] for HestiaCP and wsgi.py import os import sys sys.path.append('PATH_TO_PROJECT') sys.path.append('PATH_TO_PACKAGES_PYTHON') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() and it worked but doesn't work in Fastpanel. How to be? -
Nginx Not Serving Image Files
I have set up a django website that would be served by Nginx, everything was working perfectly not until images stopped showing recently. I tried inspecting the possible cause of this strange development using curl and then realized that the Content-Type is not recognized as Content-Type: image/jpeg returns a Content-Type: text/html; charset=utf-8 This behavior looks strange as I have included mime.types in my nginx.conf file. Below is an example response from curl command user@server:~$ curl -I https://domain.name/media/upload/image.jpg HTTP/1.1 200 OK Server: nginx/1.18.0 (Ubuntu) Date: Sun, 29 May 2022 00:45:53 GMT Content-Type: text/html; charset=utf-8 Content-Length: 11392 Connection: keep-alive X-Frame-Options: DENY Vary: Cookie X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Set-Cookie: csrftoken=T9Z3jrp4dzOAINxo6JzOUyjIGwGYHoc37TZaYsIOmHHyrQUw30vI6ETIAcy66Wnr; expires=Sun, 28 May 2023 00:45:53 GMT; Max-Age=31449600; Path=/; SameSite=Lax Note: I am serving this website with gunicorn -
Django QuerySet calculate sum of values according to a another attribute
I need some help for the creation of 2 queryset . Calculates the total of amounts of the objects considering the user as a common attribute. Given a specific user, calculate considering the categories, ordering the result in "in" and "out". This is the information that already exists in my db (we can suppose that that's the serialized information of all the objects of my only Model: [ { "money": "-51.13", "type": "out", "category": "savings", "user": "jane-doe" }, { "money": "2500", "type": "in", "category": "salary", "user": "foo-bar" }, { "money": "-150.72", "type": "out", "category": "cellphone", "user": "foo-bar" }, { "money": "-560.00", "type": "out", "category": "rent", "user": "jane-doe" }, This should be the output, queryset 1: This consider all the data in the database. [ { "user": "jane-doe", "total_in": "0", "total_out": "-611.13" }, { "user": "foo-bar", "total_in": "2500", "total_out": "-150.72" } ] This should be the output, queryset 2: This must consider de information of a specific user. The next information is just an example of the expected output { "in": { "salary": "1600.51", "savings": "550.50" }, "out": { "groceries": "-41.23", "rent": "-1286.68", "transfer": "-605.15" } } -
Django: Translating words in URLs
I am trying to translate URLs in Django but I am a bit confused when looking at the documentation as well as other posts regarding the same topic. I want to translate: /abourh-su to /about-us. The current code I have tried only let me do: /en/abourh-su Main urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ from app import views urlpatterns = [ path('', include('start.urls')), ] urlpatterns += i18n_patterns( path(_('abourh-su/'), views.about, name='about'), ) I have tried adding {% trans " " %} to the different url files but it doesn't work that way as it does with templates. Anyone that knows how to do this? Thanks! -
How to get the username in django admin.py file
I trying to get the username in django admin.py file. I am working on a project purely modification of admin site. I dont have view.py and form.py file in it. I am trying to print the username in the shell so that I can do the necessary action based upon the user group type. Like, user = User.objects.get(username="demostaff") print('is_staff', user.is_staff) print('is_superuser', user.is_superuser) Could you please suggest how to get the username object. -
Django: filter groups in admin panel
I‘m pretty new to Django and I try to customize the admin panel. I want that some other staff members can only assign a specific list of groups. The reason is I manage some other apps with the same project and I don’t want them to manage groups of other apps. What is the best way to realize that? Greets Daniel -
Recover data from a Django Form
It's my first time doing a Django Form challenge. The challenge for now is just from a HTML Template get the last_name information and store into DB from views. So I have a scenario below: models.py: class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) an HTML template, I will put below only the form part: <form action="{% url 'store' %}" method="post"> {% csrf_token %} <div class="form-group row"> <label for="last_name" class="col-sm-2 col-form-label">Last Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="last_name" placeholder="Last Name"> </div> </div> <div class="form-group row"> <div class="col-sm-10"> <button type="submit" class="btn btn-primary">Send Last Name</button> </div> </div> </form> And the views.py itself... I created a InsertLastName ModelForm to store the data from the form, but didn't work. For some reason, when I tryed to call form.cleaned_data I reveived an error about the is_valid() verification. Seens like that I'm not getting the information from label. class InsertLastName(forms.ModelForm): class Meta: model = Person fields = ['last_name'] exclude = ['first_name'] def index(request): persons = Person.objects.all() context = {'persons': persons} return render(request, '/index.html', context) def store(request): form = InsertLastName(request.POST or None) print(form.cleaned_data['original_url']) return HttpResponse("Storing a new Last Name object into storage") What is the correct way to get the information from last_name label in my form? … -
How to create a new database for each user in a database using django and mongodb?
I'm creating a web app for my school to help manage and store student documents. I'm creating the app in such a way that each student in the school gets their own database to store documents (absent notes, doctor notes, etc.). I am creating this database webapp using Django and MongoDB. I'm having a hard time figuring out how to link MongoDB and Django in such a way that I can have an infinite number of databases. Ideally, I'd like to have it so that each student gets their own database filled with their own set of documents. I was just wondering how (or if it's even possible) to create an infinite number of databases and link it to Django from MongoDB? If so, how would I set up my settings.py file and my models.py file? As of now, I have used Pymongo as a simple way to create many databases on the original MongoDB server, but haven't found an "ORM" for MongoDB that works for Django and allows me to create many databases. If MongoDB doesn't work, could I try using something else like PostgreSQL? -
MIGRATION in mongoDB not processing, error concerning 'e'
-fit |_ bin |_ gadsonF | |__pycache | |_.. | - __init__.py, asgi.py, settings.py, urls.py, wsgi.py | |_rican | |_ migrations | |_ __init__.py | |_ admin.pu | |_ apps.py | |_ models.py | |_ tests.py | |_ views.py | manage.py | |_ lib |_ .gitignore |_ pyvenv.cfg |_ gadfitAA (webfiles ) ''' Traceback (most recent call last): File "/home/cameronnc/Desktop/fit/gadfitA/gadsonF/manage.py", line 22, in <module> main() File "/home/cameronnc/Desktop/fit/gadfitA/gadsonF/manage.py", line 11, in main from django.core.management import execute_from_command_line File "/home/cameronnc/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 52 except ImportError,e: ^ SyntaxError: invalid syntax I created a basic django app above is my file structure I have several models below: from django.db import models from django.db.models import Model class GadsonA(models.Model): """Alyssa Gadson of Puerto Rico""" Alyssa = { "race":"Caucasian", "llc":"Alyssa Gadson LLC", "height":[163, 1.63, "5ft 4 in"], "weight":[110, 130], "hair_color":"Brown", "DOB":"25 November 1989", "eye_color":"Dark Brown", "ethnicity":"Latin/Hispanic", "figure_size":"34D-25-42", "show_size":9, "home_town":"Miami, Flordia, United Stated of America", "gender":"female", "zodiac":"Sagittarius", "hobbiesInterest":['Traveling', 'Shopping', 'Selfie Lover', 'Dog Lover', 'Internet Surfing'], 'philosophy':['self help', 'spirituality', 'fitness', 'working out', 'teaching', 'blogging and acadamia'], "clothingBrands":{"Calvin Klein", "LOUIS VUITTON", "Tommy Hilfiger", "Levi Strauss & Co"}, "gadgets":["Smartphone", "DSLR Camera", "Smart Watch", "DJI Mavic Drone"], "dress_size":"38(EU)", "netWorth":200000, "profession":('fitness trainer', 'model', 'philosopher', 'teacher', 'intellectual', 'model', 'actress', 'buisness woman', 'blogger') } AmealPlan = [] …