Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to include JavaScript class name in django html tag
i want to show slider images in the Django template page using javascript. i tried to adding java script code and html code in django template page Javascript code: var slideIndex = 1; showDivs(slideIndex); function plusDivs(n) { showDivs(slideIndex += n); } function showDivs(n) { var i; var x = document.getElementsByClassName("mySlides"); if (n > x.length) {slideIndex = 1} if (n < 1) {slideIndex = x.length} for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } x[slideIndex-1].style.display = "block"; } HTML Code <img class="mySlides" src="{% static "images/cropped-foodimage3.jpe" %}" style="width:100%"> <img class="mySlides" src="{% static "images/cropped-foodimage3.jpe" %}" style="width:100%"> <img class="mySlides" src="{% static "images/cropped-foodimage3.jpe" %}" style="width:100%"> <button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">&#10094;</button> <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#10095;</button> </div> -
How to check if items in cart exists or not
I have a Cart model like this class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='items', null=True) quantity = models.PositiveIntegerField(default=1) serializers.py class CartSerializer(serializers.ModelSerializer): image = serializers.ImageField(source='product.image', read_only=True) name = serializers.CharField(source='product.name', read_only=True) price = serializers.DecimalField(source='product.price', read_only=True, max_digits=10, decimal_places=2) class Meta: model = Cart fields = ['id', 'user', 'product', 'image', 'name', 'price', 'quantity'] views.py class CartApiView(generics.ListCreateAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer I have used a number of methods that check whether product in cart exists or not, but Any of them did not work in my case. Can you suggest any methods please that check product in cart? Here in the Cart model quantity is default if user does not want to add quantity it should take 1 automatically. Thanks in advance! -
Maintain the media files after build with Docker Container - Django
I am using Django as a Web Framework. Azure NGINEX as WebServer. My Project is deployed with Docker Containers. In my Django project root structure will be as follows: root: - app1 - app2 - media whenever saving images, it will correctly save under media folder. But whenever doing "docker-compose up" it will replaces the source code, so that my media folder will be cleaned up everytime. In my settings.py file, I have added as follows: MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = 'media/' Kindly help me to maintain the media files with Docker based Environment -
Extracting a Outer Join from Django ORM
I have the following two models in my Project. class Blog(models.Model): title=models.CharField(max_length=20, blank=False, default='') content=models.CharField(max_length=2000, blank=False, default='') class UserLikedBlogs(models.Model): blog=models.ForeignKey(TTSServiceModel.TTSService, on_delete=models.CASCADE, blank=True, null=True) user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) All Users who login are able to see blogs of other users. The current logged in user can "like" a certain blog, which adds an entry in the UserLikedBlogs table. I wish to now display all the blogs present in the system to a logged in User, but I also wish to show blogs that the User has liked. I understand that this should get all entries from the Blog table, with additional columns from the UserLikedBlogs table, where the data is present only for blogs liked by the user, not otherwise. This is a classic case of a Outer Join where, common elements between two sets are associated with all elements from one of the tables participating in the join. I have been reading documentation from django and on SO, but i cant seem to find the right syntax to do this. My current hacky way of doing this is to user Pandas and join the two data sets in Python, rather than a query. I am certain there is a better way, but … -
How to calculate video length and Thumbnail of video in django
I doing django project. I'm trying to calculate length of upload video and tring to create Thumbnail of the video. How to do this. models.py class Video(models.Model): video_format = models.CharField(max_length=15, blank=True, null=True) video_name = models.CharField(max_length=15, blank=True, null=True) video_size = models.CharField(max_length=15, blank=True, null=True) video_duration = models.IntegerField(blank=True, null=True) created_date = models.DateTimeField(default= datetime.now(), blank=True, null=True) status = models.CharField(max_length=15, blank=True, null=True) thumbline = models.CharField(max_length=15, blank=True, null=True) views.py def home(request): if request.method == 'POST': video = request.FILES.get('video') video_file = FileSystemStorage() file_upload = Video(video_file= video_file.save(video.name, video)) file_upload.save() return render(request, 'home.html', {}) -
Cannot see 'self' reference options for some of my model fields in Admin backend
I have an application that holds a number of posts/documents. I have a model class of Document and this document has multiple self-reference fields such as parent_document, related_checklist and explanatory_material which are a ManyToMany. When accessing the model from the backend to do edits on documents, I found that I cannot select a 'self' field anymore, the options have disappeared! I had not touched related_name and they definitely used to work and show up, I am unsure what have happened to cause this. I tried changing related_name afterwards, but that still did not work. To make matters stranger, when I added a test_fieldthat also has a 'self' reference, it worked just fine, as shown in the attached screenshot. Additionally, documents that had documents referenced to those fields remain added to the list (check Explanatory Material in screenshot) but I cannot select anymore values, because they are not there! I have tested that when I uncheck anything and save, that option disappears from the list. Also, if I added a document using the "+", it adds the new document to that list just fine, too. One thing to note is that I have a different application attached to that Django app … -
How to design data-model for dynamic user structure in Django?
I have a client who wants a dynamic data-model structure in their web-application and I would like to know how to design the data-model structure for this, or if I am doing it correctly. This was actually pretty well built out but they changed their mind and wanted to add dynamic employee types (employee types which can be added/removed by the company admin). They would like for a casino to register for their site and have one casino admin that can create unlimited employee types. For this I am restricting the Admin page so they can edit certain attributes. Each employee type will be assigned one of two Groups: Supervisor or Non-Supervisor. From there I will handle authentication and permissions. class Casino(models.Model): """ Store casinos, casino info and meta-data, related to: :model: 'casino.CasinoStyle' """ name = models.CharField( max_length=128 ) employee_type = models.ManyToManyField( EmployeeType, blank=True ) class EmployeeType(models.Model): """ Stores user employee type. """ employee_type = models.CharField( max_length=32, default='Dealer' ) group = models.ForeignKey( Group, on_delete=models.CASCADE ) class User(AbstractUser): """ Store users, user-settings and meta-data, related to: :model: 'casinos.Casino' :model: 'auth.Group' :model: 'users.EmployeeType' """ name = models.CharField( max_length=50 ) casino = models.ForeignKey( Casino, on_delete=models.CASCADE ) employee_type = models.ForeignKey( EmployeeType, on_delete=models.CASCADE, blank=True ) … -
How to fix crontab in Django?
I had a problem when implementing django-crontab in virtualenv. I have created a cron.py file in my Django app to send an email every minute, and when I ran it, I saw the running processes but the script was not executed. I'm using macOS Catalina and python3.7.4. I ran my django app in a virtualenv. In the past, I've tried: in 'django_crontab', ...) CRONJOBS = [ ('*/5 * * * *', 'mypapp.cron.send_email', '>> /tmp/file.log') ] CRONTAB_COMMAND_SUFFIX = '2>&1' this is my cron.py file (I have tested the script without crontab and it worked). import smtplib, ssl def send_email(): port = 465 smtp_server = "smtp.gmail.com" sender_email = "sender@gmail.com" receiver_email = "receiver@gmail.com" password = "" message = """\ Subject: Hi there This message is sent from Python.""" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: # server.login(sender_email, password) # server.sendmail(sender_email, receiver_email, message) Then I run python manage.py crontab add and python manage.py runserver. I saw the contab was running when I typed crontab -l and this line showed up on the terminal: */1 * * * * /Users/james/Documents/pj_django/myenv/bin/python /Users/james/Documents/pj_django/myenv/manage.py crontab run 6da410d117f9ce8casc7c6cd8c8dc78 >> /tmp/file.log 2>&1 # django-cronjobs for firstproject But the script was not running. After that, I checked my file.log … -
How to keep fields in user model in Django and add some extra field
Hi I want to add some extra fields to my user model and I read custom user model with inherit from abstractuser class but when I implement user model Django username field and etc was gone. a solution is use another model like profile but I want add extra fields to Django user model. Is this possible? Thanks , please don't give me down vote for this question -
django-admin: postgresql trigger function
i have this 3 table in django admin, if i select the section in table (student enrollment record), it will search the section in another table name (subject section teacher) then it will automatic save the search result in the another table name (student enrolled subject) using trigger function in postgres or is there any solution? -
Django Connection Timed Out when accessing the website
I have hosted my django website on a LINUX machine. I have also granted all the required permissions to my project directory. But when I am trying to access the website from my browser I am getting an error Connection Timed Out on the page. This is my /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost #DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is … -
Onclick, scroll to div that is dynamically generated
I'm working with the Wagtail CMS, most of my content is dynamically generated - which makes things like this a little tricky for me. Basically I want to click on my sidebar item and scroll to that section within my page. <div class="sidebar"> <nav> <ul> {% for block in page.article_content %} <li><a class="section-link" id="{{ block.value.header }}" href="">{{ block.value.header }}</a></li> {% endfor %} </ul> </nav> My sidebar code generates li elements for each block.value.header I have on the page. <div class="container"> {% for block in page.article_content %} <main> <section id="{{ block.value.header }}"> <h1 class="headline-text section-header" >{{ block.value.header}}</h1> <div class="header-bar"></div> <div class="case-study-body-container" > {{ block.value.description|richtext }} </div> </section> </main> {% endfor %} script.js looks like this JS Code let mainNavLinks = document.querySelectorAll("nav ul li a.section-link"); let mainSections = document.querySelectorAll("main section"); console.log(mainNavLinks) let lastId; let cur = []; window.addEventListener("scroll", event => { let fromTop = window.scrollY; mainNavLinks.forEach(link => { let section = document.querySelector(link.hash); if ( section.offsetTop <= fromTop && section.offsetTop + section.offsetHeight > fromTop ) { link.classList.add("current"); } else { link.classList.remove("current"); } }); }); The error I'm getting at the moment is: Uncaught DOMException: Failed to execute 'querySelector' on 'Document': The provided selector is empty. Heres what the page looks like to give … -
Django - Using URL dispatchers in site-level urls.py
I want to do something like this where I have a user's uuid in the path of each user-specific app: urlpatterns = [ # URLs for all users path('', HomePageView.as_view(), name='home'), ... # URLs specific to a particular user path('<uuid:user_id>/', UserHomePageView.as_view(), name='user_home'), path('<uuid:user_id>/assets/', include('mysite.assets.urls', namespace='user_assets')), path('<uuid:user_id>/components/', include('mysite.components.urls', namespace='user_components')), path('<uuid:user_id>/service_requests/', include('mysite.service_requests.urls', namespace='user_service_requests')), ... ] I'm not sure how this would work. Would the uuid be passed to every view in each of the apps? I have been searching all over the place, but haven't found any examples of others doing something like this. -
Django: Postgressql Trigger
I have this query in postgres, i just want to trigger the "StudentsEnrolledSubjects" table when "StudentsEnrollmentRecords" found. but error says: ERROR: syntax error at or near "INSERT" i dont know how to fix this, do you have any idea? please help me.. Insert into StudentsEnrolledSubjects (Students_Enrollment_Records_id,Subject_Section_Teacher_id, Status) SELECT a.id AS Students_Enrollment_Records_id, b.id AS Subject_Section_Teacher_id, 'Active' as Status FROM dbo.StudentsEnrollmentRecords AS a INNER JOIN dbo.SubjectSectionTeacher AS b ON a.School_Year_id = b.School_Year_id AND a.Education_Levels_id = b.Education_Levels_id AND a.Courses_id = b.Courses_id AND a.Section_id = b.Section_id Where a.Section_id = @Section_id and a.Education_Levels_id=@Education_Levels_id and a.Courses_id=@Courses_id and a.Section_id=@Section_id and a.Student_Users_id=@Student_Users_id -
How to serve a private file from a non static directory in Django?
I'm trying to serve a private file from Django. Although it's not super private because I don't need @login_required, I just need a view level permission, and it's what I assume is a quick and dirty way to get what I need done. I'm also not serving a file from a model. I just want to serve AAA.mp4 on the same page as the template, not as a forced download by setting a header. I know the browser has no idea what the file server's structure is, but assume this structure: projectcontainer/ project/ ... settings.py static/ media/ PROTECTED/ AAA.mp4 I don't want anyone to be able to right click for the page source, go to the url, and view the mp4 like that. So here's what I have so far: from django.core.files.storage import FileSystemStorage from django.conf import settings import os PRIVATE_STORAGE_ROOT = os.path.join(settings.BASE_DIR, 'PROTECTED') def protected_page(request): temp_password = request.POST.get('temp_password') if request.method =='POST': if temp_password == 'a_temp_password': fs = FileSystemStorage(location=PRIVATE_STORAGE_ROOT + '\\AAA.mp4') response = render(request, 'template.html', {'temp_password': True, 'fs': fs}) return response return render(request, 'template.html', {}) <video width="75%" height="auto" controls class="margintop100px"> <source src="{{ fs.location }}" /> Your browser doesn't support the mp4 video format. </video> Given the temp_password passes the test, … -
How to connect post_save signal?
I have two post_save signals which were previously working but one is getting skipped for some reason. It seems the first of the two signals is not being called upon creation of the 'Casino' instance. @receiver(post_save, sender=Casino) def create_profile(sender, instance, created, **kwargs): """Creates casino profile when casino is created.""" if created: CasinoProfile.objects.create(casino=instance) @receiver(post_save, sender=Casino) def save_profile(sender, instance, **kwargs): """Saves casino profile.""" instance.profile.save() The CasinoProfile model looks as such: class CasinoProfile(models.Model): """ Store casino profile and image, related to: :model:`casinos.Casino` """ casino = models.OneToOneField( Casino, on_delete=models.CASCADE) image = models.ImageField( default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.casino} Profile' The error is: AttributeError at /casinos/ 'Casino' object has no attribute 'profile' ...which is acting upon: instance.profile.save(). This tells me that the create_profile signal is getting skipped; but why? -
verifying users email using django rest auth without errors
I am creating a rest API and using Django-rest-auth to verify and create users. Everything works until I click the link to verify the user's email, but I get an error instead error message upon following the link to verify the email NoReverseMatch at /account-confirm-email/MjI:1iNmbO:BWhf4WhFzVR99YVYUqCB6X2CbcE/ Reverse for 'account_email' not found. 'account_email' is not a valid view function or pattern name. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'users', ] ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'test@gmail.com' EMAIL_HOST_PASSWORD = 'test' DEFAULT_FROM_EMAIL = 'test@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' urls.py from rest_auth.registration.views import VerifyEmailView urlpatterns = [ path('admin/', admin.site.urls), url('api/rest-auth/', include('rest_auth.urls')), url('api/rest-auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/$', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), ] A quick fix I made which solved the error a BIT but made it NOT a Rest API was adding a bunch of URLs as shown below from allauth.account import … -
python crash course 19-1 Blog editing posts not working
I'm working on the project Blog, the new_post works but can't get edit_post to work. In posts.html, if I keep the "post.id" on the link 'edit post', when I run localhost:8000, it shows "NoReverseMatch"; if I delete the "post.id", I'm able to get the edit post tag on the homepage but when click on it, it shows "TypeError at /edit_post/".what do I do wrong? I've been going through this problem a couple days, can't find the solution, please help! models.py from django.db import models class BlogPost(models.Model): '''A blog''' title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): '''Return a string representation of the model.''' return self.title def __str__(self): '''Return a string representation of the model.''' if len(self.text) > 50: return self.text[:50] + '...' else: return self.text forms.py from django import forms from .models import BlogPost class PostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['text'] labels = {'text': ''} urls.py '''Defines URL patterns for blogs.''' from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ # Home page path('', views.posts, name='posts'), # Page for adding a new post path('new_post/', views.new_post, name='new_post'), # Page for editing a post path('edit_post/', views.edit_post, name='edit_post'), ] views.py from django.shortcuts … -
Using .filter in Django to see if title contains a certain string?
My code is: posts = Listing.objects.filter(title=q, is_live=1) I need the equivalent of: posts = Listing.objects.filter(q in title, is_live=1) How can I just determine if a certain bit of text exists and isn't exactly equal to the query? -
Use a macro value in a tag that accepts parameters [Django]
Since the same block cannot be used more than once in a template, I am using macros (aka kwacros) inside of my Django templates so that I can reuse the values passed into the blocks. I would then like to be able to pass some of these values into the parameters of an include tag but I cannot figure out how this is supposed to be done. This causes an error: {% include 'meta_tags.html' description="{% usemacro description %}" %} Is this something that can be done or am I trying to do something that no human should ever do. -
How to generate swagger documentation for 'other' URLconfs from apps included into the project urls.py
I am working on a project using the following dependencies: Python 3.7 django 2.2.6 djangorestframework 3.9.4 I am creating multiple apps and each of these apps has their own urls.py files which are included in the URLs file of the parent project. I wish to create swagger documentation for the API endpoints described in the included URLconf files. However, swagger only documents URLs mapped in the parent URLconf file. I have already tried including the swagger view in the URLconfs of the projects but it still serves the parent URLconf only. Basically, I have added the below code to all my URLconf's from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Some APIs') urlpatterns = [ path('', schema_view), ] -
Search from every pages in django
i want to add search in my website and i want search from my pages (html) ** note : i want grab the label tag , i mean for example : i have label tag called ' test ' and when user write in search bar 'test' i want view the label to user in new page my label like this : <label id="label_main_app"> <img id="img_main_app_first_screen" src="{% static "images/android_studio.jpg" %}" alt="" > test <br><br> <p id="p_size_first_page">this is an test app <br> <br> <a href="https://www.fb.com" type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> always i got this message in result page : not found my code : * this form in home html page <form class="" action="{% url 'test_search_page'%}" method="get"> <div class="md-form mt-0 search-bar" id="search_form"> <input id="search_box" autocomplete="off" onkeyup="searchFunction()" class="form-control" type="text" placeholder="Write Here to Search ..." aria-label="Search" name="search"> </div> </form> and this is my view.py code : def search(request): input= 'search' my_template_keyword = ['label'] if 'search' in request.GET and request.GET['search'] and input == my_template_keyword: return render(request, 'home_page/testforsearch.html', {'search:':search})` finally this is my code in html result page : <div class="container"> {% if search%} {{search}} {%else%} <h2>not found</h2> {%endif%} any help please ? -
Adding a unique template in python-phonenumbers
I found project on Github that can help me to validate correct input of phonenumbers, there is such class validating it: class PhoneNumberField(CharField): default_validators = [validate_international_phonenumber] def __init__(self, *args, region=None, **kwargs): super().__init__(*args, **kwargs) self.widget.input_type = "tel" validate_region(region) self.region = region if "invalid" not in self.error_messages: if region: number = phonenumbers.example_number(region) example_number = to_python(number).as_national # Translators: {example_number} is a national phone number. error_message = _( "Enter a valid phone number (e.g. {example_number}) " "or a number with an international call prefix." ) else: example_number = "+12125552368" # Ghostbusters # Translators: {example_number} is an international phone number. error_message = _("Enter a valid phone number (e.g. {example_number}).") self.error_messages["invalid"] = error_message.format( example_number=example_number ) def to_python(self, value): phone_number = to_python(value, region=self.region) if phone_number in validators.EMPTY_VALUES: return self.empty_value if phone_number and not phone_number.is_valid(): raise ValidationError(self.error_messages["invalid"]) return phone_number But problem is i want to add one more template of phone number to consider phone number is correct E.g in Russian equivalent i would wrote 8 instead of +7 and consider it a correct way to input , but how i can do this ? Project link is here : Here -
Error: didn't return an HttpResponse object. It returned None instead
I want to press a button in an html-template <form action="{% url 'speech2text' %}" class="card-text" method="POST"> {% csrf_token %} <button class="btn btn-primary btn-sm" type="submit">Start</button> </form> <p> Sie haben das folgende gesagt: </p> <p> {{ speech_text }} </p> by pressing the button, the code in the following view shall be executed and send back the result into the template: def speech2textView(request): if request.method == "POST": r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) text = r.recognize_google(audio, language="de-DE") args = {'speech_text': Text} return render(request, 'speech2text.html', args) Whats wrong here? many thanks for your help. -
How to install tortoise hg Mercurial on Windows, virtual environment
I am trying to install Django's debug_toolbar line profiler. As per the docs, I need to install Mercurial. I have installed Mercurial on my Windows machine and it looks OK when I type hg in the command prompt outside of my project's virtual environment. The problem is that the same command throws an error when I enter it inside the virtual environment: ERROR: Error [WinError 2] The system cannot find the file specified while executing command hg clone --noupdate -q https://bitbucket.org/kmike/line_profiler 'c:\[user]\environments\[project]\src\line-profiler' ERROR: Cannot find command 'hg' - do you have 'hg' installed and in your PATH? How do I fix that? The end goal is to install line_profiler