Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mobile app from website is a good option?
I am developing a website and I have plans to convert to a mobile app. The technologies used to build the website are: Frontend: HTML, CSS, JavaScript Backend: Python (Django) DataBase: SQLite I wonder if converting from site to mobile app is a good option? -
How do I run a function in the background so that it doesnt stop the other pages django
I have a script which is starting a download of a sound file when the user clicks a button on the website, but when one user starts the download the whole backend stops and waits for it to finish before any other user can use the website. songList = await self.getSongs() await self.downloadSongs(songList) async def downloadSongs(self, songList): dirList = os.listdir("Directory") await self.channel_layer.group_send( self.room_group_name, { 'type': 'loadingGameGroup', }) downloadThread = threading.Thread(target=self.download, args=(songList, dirList)) downloadThread.start() downloadThread.join() def download(self, songList, dirList): for song in songList: try: self.downloadSong(song, dirList) except: self.downloaded = False return def downloadSong(self, song, dirList): songId = song["song_id"] if songId + ".mp3" in dirList: return video_url = "https://www.youtube.com/watch?v="+ songId video_info = youtube_dl.YoutubeDL().extract_info( url = video_url,download=False ) filename = "Directory" + songId + ".mp3" options={ 'format':'bestaudio/best', 'keepvideo':False, 'outtmpl':filename, } with youtube_dl.YoutubeDL(options) as ydl: ydl.download([video_info['webpage_url']]) How do I make it so it downloads the songs, waits for one group of songs to finish so I then can send a websocket message back to the client so that one can proceed. While the other groups doesnt have to wait for it to finish to do something -
Django {{data|escapejs}} from a js static file
I use {{data|escapejs}} django banner to import some data in my the javascript of my page. Simple example : <script> console.log({{data|escapejs}}) </script> But it doesn't work if I place this line in a .js static file <script src = "{% static 'mycode.js' %}> In mycode.js : console.log({{data|escapejs}}) How to make it work ? -
Cant include navbar.html in other modules
I'm quite a beginner in web development I've encountered some problems using Django this is my projects modules code. {% include 'navbar.html' %} <h1>projects template</h1> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> {% endblock content %} and this is my navbar.html: <h1>Logo</h1> <hr> when I run this, it is expected to return something like this: enter image description here but it instead outputs this: enter image description here as you can see it doesn't wrap the navbar text correctly. I would really appreciate it if someone helps me with this issue. -
Always get None from Django api request as result
I am going to get whitebg_url result from sqlite database according to matched items and made the api request using django like this. @api_view(['POST']) def getUrlFromAttributes(request): try: print('>>>>>>>>>>>>>>>>>>>>>', request) hairstyle = request.data.get("hairstyle") haircolor = request.data.get("haircolor") skincolor = request.data.get("skincolor") print("error>>1", str(hairstyle), str(haircolor), str(skincolor)) basic_query = BasicSetup.objects.all().filter(skin_color=skincolor, hair_color=haircolor, hair_style=hairstyle, isDeleted= 0) print('returned basic queyr : ', basic_query) lists_basicSetup = list(basic_query.values( 'whitebg_url')) print('returned lists_basicSetup : ', lists_basicSetup) return JsonResponse({'result': lists_basicSetup}) except Exception as error: print("error", str(error)) return JsonResponse({'result': str(error)}) But as you can see the result at the below image, response is always None. I tried to find the solution from google, but can't do it. I already add rest_framework at INSTALLED_APPS in settings.py file. and path is like defined. path('getUrlFromAttributes', views.getUrlFromAttributes, name='getUrlFromAttributes'), I tried to do this using Postman, but the result was same. Anyone knows why I was getting None as result? -
Temporary data storage in django which is persistent across browser
I'm building a Django where the admin will create a user and then one mail will be sent to the user. In the mail, I'm also sending one token with the URL on clicking which the user will get verified by checking the correctness of the token. But the problem is I'm storing the token in Django session and when I open the link on the same browser it works but on a different machine user is not getting verified as session data becomes unavailable. Someone suggest me the best way to store the token. I didn't want to use the database as it doesn't make sense. -
How to solve urls not found issue in django
I am building an app using django and notice that some new urls that i have created, the list is provided below are not being found. I read somewhere that the slug might be the reason django cannot found the urls but i am not sure main urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path(config("ADMIN_URL"), admin.site.urls), path("", include("core.urls", namespace="core")), ] application urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('index/', views.index, name='index'), path('home/', views.home, name='home'), path('home/<str:slug>/', views.user_lessons_details, name='user-lessons-details'), path('home/join-transaction/', views.user_lessons_join_transaction, name='user-lessons-join-transaction'), path('home/start-transaction/', views.new_test_epoint, name='new-test-epoint'), path('home/draft/<str:slug>/', views.user_lessons_core_action, name='user-lessons-draft'), path('teachers/lessons/create/', views.merchant_lessons_create, name='teachers-lessons-create'), path('teachers/lessons/list/', views.teachers_lessons_list, name='teachers-lessons-list'), path('teachers/lessons/<str:slug>/', views.teachers_lessons_details, name='teachers-lessons-details'), path('teachers/lessons/<str:slug>/update/', views.teachers_lessons_update, name='teachers-lessons-update'), path('teachers/lessons/<str:slug>/delete/', views.teachers_lessons_delete, name='teachers-lessons-delete'), path('teachers/drafts/create/', views.teachers_core_actions_create, name='teachers-drafts-create'), path('teachers/drafts/list/', views.teachers_core_actions_list, name='teachers-drafts-list'), path('teachers/drafts/<str:slug>/', views.teachers_core_actions_details, name='teachers-drafts-details'), path('teachers/drafts/<str:slug>/update/', views.teachers_core_actions_update, name='teachers-drafts-update'), path('teachers/drafts/<str:slug>/delete/', views.teachers_core_actions_delete, name='teachers-drafts-delete'), path('teachers/home/list/', views.teachers_home_list, name='teachers-home-list'), path('teachers/home/<str:slug>/', views.teachers_home_details, name='teachers-home-details'), path('teachers/home/create/course/', views.teachers_home_transaction_quote, name='teachers-home-create-course'), path('teachers/home/create/something/', views.teachers_home_create_transaction, name='teachers-home-create-something'), path('teachers/home/create/fields-selection/', views.teachers_home_fields_selection, name='teachers-home-fields-selection'), # ALL THE NEW URLS BELOW return NOT FOUND in django no matter what i do path('teachers/home/account/settings/', views.teachers_settings, name='teachers-settings'), path('teachers/account/settings/update-password/', views.teachers_settings_update_password, name='teachers-settings-update-password'), path('teachers/account/payments/', views.teachers_payments, name='teachers-payments'), path('teachers/account/payments/update/', views.teachers_payments_update, name='teachers-payments-update'), path('teachers/account/analytics', views.teachers_analytics_stuff, name='teachers-analytics-stuff') ] How can i possibly solve this urls not found issue in django? -
Should i use django or no?
I should implement a deep learning face recognition model that should use photos from a database should i build the model using tensorflow and python first then deploy it on a backend done with nodejs or I should start the project with using tool like django? -
Django Media Files Not Showing
My Django files are loading after upload and are shown in the media folder, however I cannot access them at localhost:<PORT>/media/<FILENAME._EXT>. I've looked at several other answers on stackoverflow and they haven't worked. For example adding the urlpatterns += static(...), having DEBUG=True in settings.py. When accessing: http://localhost:8000/media/controller.gif: Error: lightchan-backend-1 | Not Found: /media/controller.gif lightchan-backend-1 | 2022-03-06 16:37:34,875 WARNING Not Found: /media/controller.gif In settings.py: DEBUG = True MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') In my urls.py: from django.urls import path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ path('', views.index, name='index'), path('comment/<int:comment_id>/', views.comment, name='comment'), path('comments/', views.comments, name='comments'), path('reply/<int:incoming_id>/', views.reply, name='reply') ] # if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Why ModelForm in my forms.py showing error?
I have made the simple form using django, i am new to django,yesterday, i have wrote some code to practice,from today it is not working,but it is working yesterday. template file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" novalidate> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> </body> </html> from django.http import HttpResponse from django.shortcuts import render from .forms import FeedBackFormCustom from .models import FeedBack # Create your views here. def home(req): if req.method == "POST": form = FeedBackFormCustom(req.POST) if form.is_valid(): nm = form.cleaned_data['name'] ag = form.cleaned_data['age'] em = form.cleaned_data['email'] st = form.cleaned_data['state'] inst = FeedBack(name=nm, age=ag, email=em, state=st) inst.save() return HttpResponse('<h2>Form successfully submitted.</h2>') else: form = FeedBackFormCustom() context = {'form': form} return render(req, 'home/index.html', context) Models.py from pyexpat import model from django.db import models # Create your models here. class FeedBack(models.Model): STATES_AVAILABLE = ( ('ap', 'Andhra Pradesh'), ('mp', 'Madhya Pradesh'), ('kn', 'kutub nagar'), ('mu', 'Mumbai'), ('de', 'Delhi'), ('ch', 'Chennai'), ) name = models.CharField(max_length=30) age = models.PositiveIntegerField() email = models.EmailField(max_length=200) state = models.CharField(max_length=3, choices=STATES_AVAILABLE) def __str__(self): return self.name ModelForm.py from django import forms from .models import FeedBack from django.contrib.auth.forms import UserChangeForm, UserCreationForm, PasswordChangeForm, SetPasswordForm class FeedBackFormCustom(forms.ModelForm): class Meta: … -
Django allowed hosts in Elastic Beanstalk
I have built a Django app that is hosted on Elastic Beanstalk. Everything is fine when I directly leave in my settings ALLOWED_HOSTS = ["nameofmysite.com"] but when I replace this by an env. variable (a classical "os.environ.get" that works fine with all other env variable in the project) and that I fill this env. variable in my Beanstalk configuration, I get a 500 error. I've looked into tutorials and actually all of these do not put ALLOWED_HOST as an env. variable, they just leave it in the project. https://testdriven.io/blog/django-elastic-beanstalk/ for example. Just wondering if this is normal and if there is a fix. The second problem that I encounter is that when I remove ALLOWED_HOSTS = ["*"] for ALLOWED_HOSTS = ["nameofmysite.com"], I manage to access https://nameofmysite.com/ but cannot access https://WWW.nameofmysite.com/. Wondering if it isn't a problem related to my Route 53 config rather than ALLOWED_HOSTS configuration. Thanks a lot -
Django: get random object from database by id, but if id doesn't exist try again
Trying to get a random object from the database with an id. Some ids in the database table are missing, for example, 1, 2, 4, 5, 6, 19, 20... so I need to make sure I don't get an error when I try to get an object. This seems to be working. Is there a better way. def get_random_title(): title_count = OriginalTitle.objects.count() random_id = random.randrange(1, title_count) random_title_obj = None while random_title_obj is None: try: random_title_obj = OriginalTitle.objects.get(id=random_id) except ObjectDoesNotExist: continue return random_title_obj.title def play(request): random_title = get_random_title() context = { 'original_title': random_title } return render(request, 'game/game.html', context) -
Best way to raise validation error before save at model level in Django
I have a background job wherein I am creating MyModel using get_or_create method from a data in dictionary. I have a condition to check and if not satisfied just log the error. Basically I am looping through a list of dict of data and calling the get_or_create. If it is at the form level, then I am using clean method but since this is being done in the backend what would be the best way to validate before save and log if validation fails? I would like to know how to validate on both - before create or update. Should I use pre_save signal or just clean_field_name or clean method? -
How do I stop people from getting a direct url to a media file
I need a way to send music to a client without them getting a direct link to the file. I know this can be done using blob. How would I go about doing this? -
Is there a way to integrate NLP and prolog to backend?
basically, I have a frontend where a user can write his/her queries and I want to fetch the queries and perform NLP on it then send it to my knowledge base which is SWI prolog (prolog is where I have defined rules for the text that is obtained from the user) then sent the response to the frontend. Is there a way to perform NLP on the received text at the backend end before sending it to the database or knowledge? I want to know how can I integrate both SWI prolog and NLP together on the backend. Please Help. -
what is unresolved reference error in pycharm
I am using pycharm and in view.py I face this issue. I don't know what type of error is this. Here is the code def recruiter_signup(request): error = "" if request.method == 'POST': f = request.POST['fname'] l = request.POST['lname'] con = request.POST['contact'] e = request.POST['email'] p = request.POST['pwd'] gen = request.POST['gender'] i = request.FILES['image'] company = request.POST['company'] try: user = User.objects.create_user(first_name=f, last_name=l, username=e, password=p) Recruiter.objects.create(user=user, mobile=con, image=i, gender=gen, company=company, type="recruiter", status="pending") #unresolved reference here error = "no" except: error = "yes" d = {'error': error} return render(request,'recruiter_signup.html',d) -
How to check type of reverse_lazy() object in django
I want to do following: u=reverse_lazy('xyz') isinstance(u,str) # this is false since u is an object. type(u) # <class 'django.utils.functional.lazy.<locals>.__proxy__'> isinstance(u,<class 'django.utils.functional.lazy.<locals>.__proxy__'>) # doesnt work -
How to post the model with foeign key
I have model like this one has foreign key of the other. class MyCategory(models.Model): name = models.CharField(max_length=30) description = models.TextField(verbose_name='description') class MyItem(models.Model): file = models.FileField(upload_to='uploaded/') category = models.ForeignKey(MyCategory, on_delete=models.CASCADE) @property def category_name(self): return self.category.name Now I want to upload the file to MyItem and set category at the same time. At first I try this. ( I have one category data which has id = 1) curl -X POST -F file=@mypng.jpg -F 'category=1' http://localhost/items/ it shows Exception Value: (1048, my_category_id cannot be null) category=1 dosen't accepted as foreign key. SO,,, is it possible to use curl command to set the ForeignKey? -
Why Google-Auth(Google Identity) Blank popup in Django?
My Google Auth is Stuck in the popup auth flow. The one-tap authentication works just fine but not the button<div id="g_id_signin"></div>. I click on it, the popup opens but it remains there blank with no progress. <script> function handleCredentialResponse(response) { console.log("Encoded JWT ID token: " + response.credential); ... } window.onload = function () { google.accounts.id.initialize({ client_id: "531144-------", callback: handleCredentialResponse }); google.accounts.id.renderButton( document.getElementById("g_id_signin"), { theme: "outline", size: "large" } // customization attributes ); google.accounts.id.prompt(); // also display the One Tap dialog } </script> <div id="g_id_signin"></div> I have all the domains, localhost added in Authorized redirect URIs and Redirects. But I still can't get the popup to populate and complete the authentication flow. Any help is appreciated. -
Reference a confirmation window from forloop
i've been trying to create a popup delete confirmation overlay, from a forloop, I cant make it work, or define which ids or how to pass identifiers for the overlay I got this, but it only refers the first element of the loop {% for ref in perf_bim.referenciapredio_set.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <th>{{ref.rol_fk.rol}}</th> <th>{{ref.rol_fk.dir}}</th> <td><a href="{% url 'det_ref_pr' ref.pk %}"><img src="{% static 'arrow.png' %}" height=20 alt=""></a></td> <td><button onclick="openNavRef()" type="button" class="btn btn-outline-dark btn-sm"><img src="{% static 'trash.svg' %}" alt="" height=15 ></button><br></td> </tr> <div id="myNavRef" class="overlay"> <div class="fontformat"style="padding-top:250px;width:40%;margin:auto;"> <div class="overlay-content"> <a href="{% url 'borrar_ref' ref.pk %}"type="button "class="btn btn-warning btn-sm"style="color:black;">Eliminar Referncia de Predio Rol: {{ref.rol_fk.rol}}</a> <br> <a href="javascript:void(0)" type="button "class="btn btn-bright btn-sm" onclick="closeNavRef()">Cancelar</a> </div> </div> </div> {% endfor %} <script> function openNavRef() { document.getElementById("myNavRef").style.display = "block"; } function closeNavRef() { document.getElementById("myNavRef").style.display = "none"; } </script> thanks!! -
Extract related fields or Keys instead of value using request.POST.get method in Django
I have 2 tables in Django db.sqlite3 database both having state_id as a common field on the basis of which I had to map the districts for respective states in dropdown using Jquery state_database id state_id state_name 3 3 Uttarakhand 2 2 Punjab 1 1 Haryana district_database id state_id district_id district_name 1 1 1 Sonipat 2 1 2 Rohtak 3 1 3 Amabala 4 1 4 Sirsa 5 2 5 Amritsar 6 2 6 Ludhiana 7 3 7 Pantnagar 8 3 8 Almora For Doing so, I had to assign the common field / state_id as value in HTML like value= '{{state.state_id}}' <select class="form-control" id="state_from_dropdown" name="state_from_dropdown" aria-label="..."> <option selected disabled="true"> --- Select State --- </option> {% for state in StatesInDropdown %} <option value= '{{state.state_id}}'> {{state.state_name}} </option> {% endfor %} </select> <select class="form-control" id="district_from_dropdown" name="district_from_dropdown" aria-label="..."> <option selected disabled="true"> --- Select District --- </option> {% for disitrict in DistrictsInDropdown %} <option value= '{{disitrict.state_id}}'> {{disitrict.district_name}} </option> {% endfor %} </select> Views.py def inputconfiguration(request): if request.method == "POST": StateName=request.POST.get('state_from_dropdown') DistrictName=request.POST.get('district_from_dropdown','') print(StateName, DistrictName) return render(request, 'configure_inputs.html') Instead of Getting Actual Fields/Names which appears in the dropdown, I get the values of ID's, but I want the names of states and districts instead of their … -
How to Save form Data to Database in Django?
I am trying to save form data from Django template to Django Model. Its not throwing any error but its not saving the data as well Could you please let me know what could be the problem and how should I solve? Here is my Django form template: <form method="POST" class="review-form" autocomplete="on"> {% csrf_token %} <div class="rating-form"> <label for="rating">Your Overall Rating Of This Product :</label> <span class="rating-stars"> <a class="star-1" href="#">1</a> <a class="star-2" href="#">2</a> <a class="star-3" href="#">3</a> </span> <select name="rating" id="rating" required="" style="display: none;"> <option value="">Rate…</option> <option value="3">Average</option> <option value="2">Not that bad</option> <option value="1">Very poor</option> </select> </div> <textarea cols="30" rows="6" placeholder="What did you like or dislike? What did you use this product for?" class="form-control" id="review" name="description"></textarea> <div class="row gutter-md"> <div class="col-md-12"> <input type="text" class="form-control" placeholder="Your Name - This is how you'll appear to other customers*" id="author" name ="name"> </div> </div> <button type="submit" class="btn btn-dark">Submit Review</button> </form> My Forms.py class ReviewForm(forms.ModelForm): class Meta: model = Reviews fields = ('rating', 'description', 'display_name') My Views: def reviews(request, slug): if request.method == "POST": if request.user.is_authenticated: form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.product = Products.objects.get(slug=slug) review.user = request.user review.display_name = request.name review.description = request.description review.rating = request.rating print(review) review.save() messages.success(request, "Review saved, Thank you … -
unresolved reference 'Recruiter'
I'm using PyCharm I don't know what type of error is this here is the model.py class Recruiter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=15, null=True) image = models.FileField(null=True) gender = models.CharField(max_length=10, null=True) company = models.CharField(max_length=100, null=True) type = models.CharField(max_length=15, null=True) status = models.CharField(max_length=20, null=True) def _str_(self): return self.user.username -
I want to POST data and add it to JSON
jsonData = { "2022":{ "03":{ "5":"로제파스타" ,"17":"테스트" } ,"08":{ "7":"칠석" ,"15":"광복절" ,"23":"처서" } ,"09":{ "13":"추석" ,"23":"추분" } } } } function drawSche(){ setData(); var dateMatch = null; for(var i=firstDay.getDay();i<firstDay.getDay()+lastDay.getDate();i++){ var txt = ""; txt =jsonData[year]; if(txt){ txt = jsonData[year][month]; if(txt){ txt = jsonData[year][month][i]; dateMatch = firstDay.getDay() + i -1; $tdSche.eq(dateMatch).text(txt); } } } } I'm a Korean developer. Please understand that I'm not good at English. Javascript is also inexperienced and is preparing for a small project.😅 It's my first time writing stackoverflow, so I don't know if I'm writing well.🤔 Anyway, I want to add it to jsondata using the previous input tag. I'm using Django, too. If it helps, I want to use Django, too. It's a question that I desperately want to solve. Please help me😭 -
django: how to save ModelForm data with foregin key?
I'm face an issue while saving data to database! let me explain..... I'm trying to make a app like blog... & there is a comment section. There have three fields for submit comment.... name, email & message. but when someone submit an comment it should save into database for a specific blog post, so I've defined a foreign key on comment model. but its not work! whenever I submit it show NOT NULL constraint failed error! even if I change this table null=True then it doesn't show any error but it don't save any foregin key! please help me! models.py from django.db import models from ckeditor.fields import RichTextField class Event(models.Model): title = models.CharField(max_length=255) description = RichTextField() thumb = models.ImageField(upload_to="events") amount = models.IntegerField() location = models.CharField(max_length=255) calender = models.DateField() def __str__(self): return self.title class Comment(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) username = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) message = models.TextField(null=False, blank=False) date = models.DateField(auto_now_add=True) def __str__(self): return self.username forms.py from django.forms import ModelForm, TextInput, EmailInput, Textarea from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ["username", "email", "message"] widgets = { "username": TextInput(attrs={"placeholder":"Name *"}), "email": EmailInput(attrs={"placeholder":"Email *"}), "message": Textarea(attrs={"placeholder":"Message"}) } views.py from django.shortcuts import redirect …