Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fatal error and unable to create django process
So I am trying to create a new project with Django. However, when I tried to create a new project, I got an error message. Here's what my command prompt looks like so far Microsoft Windows [Version 10.0.19041.572] (c) 2020 Microsoft Corporation. All rights reserved. C:\Users\Ben>cd Documents C:\Users\Ben\Documents>django-admin startproject photoshare Fatal error in launcher: Unable to create process using '"c:\users\ben\appdata\local\programs\python\python38-32\python.exe" "C:\Users\Ben\AppData\Local\Programs\Python\Python38-32\Scripts\django-admin.exe" startproject photoshare': The system cannot find the file specified. C:\Users\Ben\Documents> I've never had this issue before, so....hoping someone can help me figure it out?! I've been tying my head around it all afternoon. -
Can't get Django to render template
I am trying to get my view to render my HTML through a POST request from javascript but I can't make it work using the onclick="" function of an tag? I'm struggling to find an answer as I'm not sure how to pose the question so I will just try to show.... My view looks like: def photos(request): BASE_DIR = Path(__file__).resolve().parent.parent workingDir = os.path.join(BASE_DIR, 'main', 'static', 'gallery', 'img') vehicle = request.POST.get('car') # Assigns the 'pass_vehicle' JS function returned value to 'vehicle' variable print(request) # Debug number_of_images = len(os.listdir(f'{workingDir}/{vehicle}/')) - 1 # Retrieve number of images within folder for <p> tag cols = [(3, 6, 3), (8, 4), (6, 6), (4, 8)] # CSS columns used below for displaying images in specific layout on HTML page htmlText = [] imgNum = 0 while imgNum <= 25: # During development limit number of pictures to display (will have specific amount in deployment) for colNum in cols: for x in range(len(colNum)): # Generate HTML to display each image within folder within the CSS column layout above imgNum += 1 inputText = f'<div class="col-6 col-md-6 col-lg-{colNum[x]}" data-aos="fade-up">\n <a href="/main/static/gallery/img/{vehicle}/img_{imgNum}.jpg" class="d-block photo-item" data-fancybox="gallery">\n <img src="/main/static/gallery/img/{vehicle}/img_{imgNum}.jpg" alt="Image" class="img-fluid">\n <div class="photo-text-more">\n <span class="icon icon-search"></span>\n</div>\n</a>\n</div>' htmlText.append(inputText) context = … -
Uploading images to an SQLite Database
I am looking for some advice please. As a beginner learning Python, what would be the most straight forward way to allow a user to upload images and .pdf documents to a SQLite database through a GUI. OR, perhaps I am looking at webpage solution here - Django has come up in some initial research that I did. Does anyone have experience of this? Any advice is much appreciated. -
How to create multiple collapse when i use for loop in Django template
How to create multiple collapse when i use for loop in Django template I have created a django template which show lists of subjects and i want to create collapse for each subject such that on click of it , it shows the video . For now i have used django template html code : <div id="accordion"> {% for lesson in course_posts.lesson_set.all %} <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0 text-center"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{lesson.name}} </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <iframe width="100%" height="400px" src="{{lesson.youtube_url}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> </div> {% endfor %} </div> -
Django Admin - list of all instances for Tabular.Inline
Sorry I am beginner in Django.I have model with foreign key and TabularInline view. How I can visualize list of all instances instead of selection from list of instances. enter image description here -
Django: filtering on ManyToMany only return exact matches
let's say I have a model like class Group: users = ManyToMany(User, related_name='groups') and I have groups with a different mixture of users group1 = Group(users=[user1]) group2 = Group(users=[user1, user2]) group3 = Group(users=[user1, user2, user3]) How would I go about querying for groups only with user1 and user2? I'd like to do something that's like Group.objects.filter(users=[user1, user2]) -> [group1, group2] but I'm getting TypeError: Field 'id' expected a number but got [<User: user1>, <User: user2>]. if I do Group.objects.filter(user__in=[user1, user2].distinct('id') it returns back all the groups [group1, group2, group3] I know how to go through the User instance to get all of the user's groups but I specifically want to go through the Group model. I imagine I may have to do some type of matching with the ORM... maybe a subquery? -
Why is django telling me im missing the 'request' positional argument even though im calling it?
Ok, a little bit of context first. My view ProjectView has a link which takes you to another view called memorandum_download, which has the only function of downloading the memorandum assigned to the Project model shown in project view. The memorandum is stored as a FileField in the project model. I take the slug of the project as an argument via url, which is created by slugify(project.name). Then in the second view (memorandum_download), I try to request the project based on the slug, and download the memorandum assigned to it with a FileResponse. The problem is, that django keeps telling me that im missing the request argument even tough im using, it. Sending source code of urls.py and views.py. def download_memorandum(request, slug): project:Project = get_object_or_404(Project, slug=slug) response = FileResponse(open(project.memorandum, 'rb')) return response urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('<str:slug>/', views.ProjectView.as_view(), name='project'), path('<str:slug>/memorandum', views.download_memorandum(), name='download'), ] Apart from that, im just starting to learn how to manage FileFields with django, so any feedback or improvements on my actual download system are welcomed -
how to send mails to the users who are inactive for 2 weeks
I am building a subscription type Django model in which i have to identify the users who are inactive for certain duration, say 2 weeks an send mail, does any one have an idea how it could be done -
can anyone help me regarding change of quiz app to annual exam in django app
I am newbie to django app , can anyone help me out regarding the heading in the django model on admin panel of my app Here is a sample for idea which is marked with black -
Unable to save image to databse using modelForm django?
models.py class Organization(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) logo = models.ImageField(null=True, upload_to='media', default='avatar.png') forms.py class OrganizationForm(forms.ModelForm): logo = forms.ImageField( widget=forms.FileInput, label='Company Logo', required=False) class Meta: model = Organization exclude = ['user'] views.py def addorganization(request): if request.method == "POST": fm = OrganizationForm(request.POST,request.FILES, label_suffix='', auto_id=True) if fm.is_valid(): org = fm.save(commit=False) org.user = request.user org.save() return redirect('organization') else: fm = OrganizationForm(label_suffix='', auto_id=True) return render(request, 'crm/manageorganization.html', {'form': fm}) I am not able to upload images to MEDIA_ROOT programatically.But if i upload through admin it gets uploaded -
RichTextField doesn't load in the website
I try to use RichTextField to import image into my content. The admin site is ok but when I open it the website, it onlys load like this. I had import it from ckeditor.fields, and also inside "INSTALLED_APPS". Please help me, thanks guysenter image description hereenter image description here -
IntegrityError at /admin/main/post/add/ NOT NULL constraint failed: main_post.status
How fix this? This after when i create new post #models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model):enter code here title = models.CharField(max_length=200) slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now= True) def __str__(self): return self.title #admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',), } admin.site.register(Post,PostAdmin) -
How can i load Vue components with Django using Webpack-Loader?
I'm just getting started to Vue and i decided to add it to my Django project using the Webpack-Loader approach, in order to get the best of Django and Vue both. When i'm developing, i run two development servers: one for django using manage.py runserver, and another one for vue using npm run serve. Now i'm trying to deploy a very simple Django+Vue application that i found on Github, to see how does that work on production, but i'm having some problems: I cloned and deployed this code on Digital Ocean using Nginx+Gunicorn. Everything works on the Django side but i can't see the Vue components loading, i can only see the standard Django templates. Why is that? I thought that, when on production, i would not need to run two servers. Am i doing something wrong? -
Reason why CSS file not reflecting on PDF using Weazprint
I am trying to add style to my PDF file using a CSS file which for some reason is not linking to it. I have tried the following: PDF template {% load static %} <link rel="stylesheet" href='{% static "css/pdf.css" %}' media="all" /> I have tried to link it through the views page: views.py @staff_member_required def admin_order_pdf(request, order_id): -------------------------------------------- weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) return response I am using the followig config in the settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') -
Django shows valid object as NoneType
views.py def profile(request, username): user = User.objects.filter(username=str(username)).first() posts = Post.objects.filter(user=user).count() followers = User.objects.filter(following=user).count() following = user.following.all().count() return render(request, "network/profile.html", { "user": user, "posts": posts, "followers": followers, "following": following }) urls.py path("<str:username>/", views.profile, name="profile"), models.py class User(AbstractUser): following = models.ManyToManyField("self") django shows this error- File "C:\Users\Mufaddal\Desktop\cs50w\project4Network\network\views.py", line 98, in profile following = user.following.all().count() AttributeError: 'NoneType' object has no attribute 'following' The website shows the username, posts, following, followers correctly which means the query is returning a valid user. Then why does django show this error? -
Django Exif Data: 'IFDRational' object is not subscriptable
I got an issue with the code: 'IFDRational' object is not subscriptable Here is the trace: lat = get_decimal_from_dms(geotags['GPSLatitude'], geotags['GPSLatitudeRef']) degrees = dms[0][0] / dms[0][1] the is issue is: Variable Value dms (45.0, 46.0, 34.29) ref 'N' {'GPSAltitude': 22.90324416619237, 'GPSAltitudeRef': b'\x00', 'GPSDateStamp': '2020:10:17', 'GPSDestBearing': 18.1919587128, 'GPSDestBearingRef': 'M', 'GPSHPositioningError': 65.0, 'GPSImgDirection': 108.199192887128, 'GPSImgDirectionRef': 'M', 'GPSLatitude': (12.0, 26.0, 14.09), 'GPSLatitudeRef': 'N', 'GPSLongitude': (1.0, 47.0, 39.38), 'GPSLongitudeRef': 'E', 'GPSSpeed': 0.0, 'GPSSpeedRef': 'K', 'GPSTimeStamp': (12.0, 58.0, 42.0)} That what I get from an image for instance. I think the code assimilate GPSLatitudeRef to degrees = dms[0][0] / dms[0][1]. The thing is GPSLatitudeRef is a letter none a number. def get_geotagging(exifgps): geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exifgps: raise ValueError("No EXIF geotagging found") for (key, val) in GPSTAGS.items(): if key in exifgps[idx]: geotagging[val] = exifgps[idx][key] return geotagging def get_decimal_from_dms(dms, ref): degrees = dms[0][0] / dms[0][1] minutes = dms[1][0] / dms[1][1] / 60.0 seconds = dms[2][0] / dms[2][1] / 3600.0 if ref in ['S', 'W']: degrees = -degrees minutes = -minutes seconds = -seconds return round(degrees + minutes + seconds, 5) def get_lat_coordinates(geotags): lat = get_decimal_from_dms(geotags['GPSLatitude'], geotags['GPSLatitudeRef']) return lat def get_lon_coordinates(geotags): lon = get_decimal_from_dms(geotags['GPSLongitude'], geotags['GPSLongitudeRef']) return … -
Why doesn't the debug output in my views.py file get printed when there is a database constraint violation in Django?
I have three forms which have one submit button. The three forms represent employers, job listings and job listing categories. When a user enters the employer name in the form, I want to check if it already exists in the database. If it does, I want to use that employer database row and have it tied to the newly added job listing. Here are the relevant parts of my forms.py file: from django.forms import modelform_factory from .models import Employer, JobListing, Category_JobListing EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"]) JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer", "due_date", "job_application_url"]) Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"]) models.py file: class Employer(models.Model): # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES) short_bio = models.TextField(blank=True, null=True) website = models.URLField() profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True) def __str__(self): return self.name class JobListing(models.Model): employer = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=100) job_description = models.TextField() job_requirements = models.TextField(); what_we_offer = models.TextField(); due_date = models.DateField(); job_application_url = models.URLField() admin_approved = models.BooleanField(default=False) def __str__(self): return self.job_title class Category_JobListing(models.Model): job_listing = models.ForeignKey(JobListing, on_delete=models.CASCADE) category = models.CharField(max_length=MAXIMUM_INTEREST_LENGTH, choices=INTEREST_CHOICES) views.py file: def submitJobListing(request): if request.method == "POST": employer_form = EmployerForm(request.POST, request.FILES) job_listing_form = JobListingForm(request.POST, request.FILES) category_job_listing_form = Category_JobListingForm(request.POST, request.FILES) if employer_form.is_valid() and job_listing_form.is_valid(): … -
Django check buttons send to models backend
I am creating a Django web site in which a user has to select a skill category and then skill or skills in the same category that selected category and skill or skills have to be stored in model with a username which is logged in... how can I do it?? <form method="post"> {% csrf_token %} <div class="row"> <div class="col-4"> <div class="list-group" id="list-tab" role="tablist"> <a class="list-group-item list-group-item-action active" id="list-lead_generator-list" data-toggle="list" href="#list-lead_generator" role="tab" aria-controls="lead_generator"><i class='fas fa-users'></i>Lead generator</a> <a class="list-group-item list-group-item-action" id="list-content_creator-list" data-toggle="list" href="#list-content_creator" role="tab" aria-controls="content_creator"><i class='fas fa-pen'></i>Content Creator</a> <a class="list-group-item list-group-item-action" id="list-social-social_media_handler-list" data-toggle="list" href="#list-social_media_handler" role="tab" aria-controls="social_media_handler"><i class='fas fa-icons'></i>Social Media Handler</a> </div> </div> <div class="col-8"> <div class="tab-content" id="nav-tabContent"> {% comment %} <input class="bg-white rounded border border-gray-400 focus:outline-none focus:border-indigo-500 text-base px-4 py-2 mb-4" placeholder="Skill" name="Skill" type="text"> {% endcomment %} <div class="tab-pane fade show active" id="list-lead_generator" role="tabpanel" aria-labelledby="list-lead_generator-list"> <label class="container">Lead Generator <input type="checkbox" name="lead_generator" class="lead_generator"> <span class="checkmark"></span> </label> <input type="hidden" name="skill" id="txt_lead_generator"> </div> <div class="tab-pane fade" id="list-content_creator" role="tabpanel" aria-labelledby="list-content_creator-list"> <label class="container">instagram <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> </label> <label class="container">facebook <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> </label> <label class="container">linkedin <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> </label> <label class="container">twitter <input type="checkbox" name="content_creator" class="content_creator" > <span class="checkmark"></span> </label> <label class="container">youtube <input type="checkbox" name="content_creator" class="content_creator"> <span class="checkmark"></span> … -
How to serialize nested objects?
I have Django models: class Client(models.Model): name = models.CharField() class Office(models.Model): name = models.CharField() class HolidayOffer(models.Model): name = models.CharField() class Booking(models.Model): holiday_offer = models.ForeignKey(HolidayOffer, null=True) office = models.ForeignKey(Office, null=True) client = models.ForeignKey(Client, null=True) start_date = models.DateField() end_date = models.DateField() How to construct django-rest-framework serializer for API JSON to get a response similar to the example below: { "offices": [ { "name": "New York Office", "clients": [ { "name": "Client A", "bookings": [ { "holiday_offer": { "name": "Cyprus - Exclusive Vacation f> } "start_date": "20180608", "end_date": "20180615" } ] } ] } ] } Changing of the model relations is ofc possible. -
How to change join and group by SQL to ORM in Django
I'm new in Django. So, I want to join two model which is company and client and count the number of client for each of the company. Here the SQL SELECT Company_company.name, count(Client_client.cid) FROM Company_company LEFT JOIN Client_client ON Company_company.comid = Client_client.comid_id GROUP BY Company_company.name; But since in Django we use ORM. So I'm a little bit confusing since I'm beginner. I already refer few SQL to ORM converter website such as Django ORM and do some try and error. But, I didn't know where the problem since I want the output from the ORM to be classify into different array. Here is my code: labels = [] data = [] queryClientCompany = client.objects.values('comid').annotate(c=Count('cid')).values('comid__name','c') for comp in queryClientCompany: labels.append(comp.comid__name) data.append(comp.c) The error stated that the comid__name is not defined. So actually how to append the result? I hope someone can help me. Thank you for helping in advanced. -
How to Access URL Params in Django Channels Consumers
If i had the following url in routing.py: /rooms/<int:id>/ How would I access the id parameter from withing a JSONWebsocketConsumer? -
How to solve a 405 error in a class based view
I am currently working on my first website. But I am experiencing this problem. I have this class: class TranslatorView(View): def translator(self, request, phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return translation, render(request, 'main/translator.html') And the url for this class is path('translator/', TranslatorView.as_view(), name='translator'), When I enter to the website, it appears a HTTP 405 error. I think I have the problem in the class. But Idk how to solve it -
Django - no module named config
I'm trying to deploy a Django application using Gunicorn, but whenever i try to start the Gunicorn Daemon, i get the following error: ModuleNotFoundError: No module named 'config' Here is my daemon: [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/tes/tes ExecStart=/tes/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/tes/tes.sock config.wsgi:application Restart=always SyslogIdentifier=gunicorn User=root Group=django [Install] WantedBy=multi-user.target Here is my folder: tes |-tes |-venv |-staticfiles |-config |-urls.py |-wsgi.py |-__init__.py |-settings |-base.py |-production.py |-local.py I'm struggling to find the error here, can anyone help me? -
Django comments and add comment form same page
I want to to display my comments on the post detail page. After trying hard I ran the codes. But I think there are some problems with my code. I am not particularly sure that I am using the redirect function correctly. Also, do I need to define the get function like post? view.py model = Post template_name = 'blog/post_detail.html' form_class = AddCommentForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['comments'] = Comment.objects.filter(is_active=True) context['form'] = AddCommentForm return context def post(self, request, *args, **kwargs): post = get_object_or_404(Post, slug=kwargs['slug']) # List of active comments for this post new_comment = None if request.method == 'POST': # A comment was posted comment_form = AddCommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = AddCommentForm() return redirect('blog:post_detail', kwargs['slug']) ``` url.py `` path('detail/<slug:slug>/', PostDetailView.as_view(), name='post_detail'), ``` -
How can i write this if statement on my template Django
I would like to write something in the form of an entry to a particular tournament where the user after clicking on the "join" button is moved to a sheet where the user is asked to enter their name and choose which tournament they want to join. Is it possible to write a conditional instruction that checks if the name of a given tournament is equal to the name of the tournament that the user has chosen and using it to list the users assigned to the given tournament. my views.py file def content(request, pk): tournament = Tournament.objects.get(id=pk) users = TournamentUsers.objects.all() return render(request, 'ksm_app2/content.html', {'tournament': tournament, 'users': users}) my models.py file class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) tournament_info = models.TextField(max_length=10000) def __str__(self): return self.tournament_name class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name {% for user in users %} {% if user.user_tournament == tournament.tournament_name %} <p>{{ user.user_first_name }} {{ user.user_last_name }}</p> {% else %} <p>no one takes part in this tournament </p> {% endif %} {% endfor %} if u have any idea what i can do i will …