Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to provide initial data to ForeignKey in ModelFormSet?
So I have this thing. These are the relationships of my models To define an event you have a Place, a QR Link and an ImageAlbum which have up to five Images. An event may or may not have a Place An event MUST have the main image which is marked by the main attr in the Image Form. All the forms are in the same page, they all are processed with a single Submit Now my troubles begin and end in the Forms Department, i have several Model Forms: #FORMS FILE class EventForm(ModelForm): date_time_start = forms.DateTimeField(input_formats=["%Y-%m-%d"], required=True, widget=forms.DateTimeInput(format="%Y-%m-%d", attrs={"id": "cal_start", "placeholder": "yyyy-mm-dd"})) has_place = forms.BooleanField() class Meta: model = Event fields = ['title', 'subtitle', 'phrase', 'date_time_start', 'prices', 'has_place'] class BaseImageFormSet(BaseModelFormSet): def clean_main(self): """Checks that there is only one main image""" if any(self.errors): return boolean_arr = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue main_data = form.cleaned_data.get('main') main = main_data if main_data is not None else False if sum(boolean_arr) > 1: raise ValidationError('There can only be one main image.') boolean_arr.append(main) class PlaceForm(ModelForm): class Meta: model = EventPlace exclude = ['uuid', 'event'] class QRForm(ModelForm): class Meta: model = EventQR exclude = ['uuid', 'event'] My headache is with the Images, … -
importing models into commands file causing Error module not found django
I'm trying to import my app's models into my update.py located inside website/management/commands knowing that website is my application, the problem that i get is that there is no module named 'website' even that I've mentioned it in my Installed_APPS in my settings.py: this is my update.py file : from django.core.management.base import BaseCommand import pandas as pd #from website.models import Product from website.models import Main_data class Command(BaseCommand): help='import booms' def add_arguments(self, parser): pass def handle(self,*args,**options): df=pd.read_excel('main.xlsx',engine='openpyxl') for P_N,P_P,P_L,P_I,P_Logo in zip(df.Product_Name,df.price,df.Link,df.Image,df.Logo): models=Data_Main(Product_Name=P_N,Product_Price=P_P,Product_Link=P_L,Product_Image=P_I,Product_Logo=P_Logo) models.save() this is the error that i get : Traceback (most recent call last): File "C:\Users\dell\Desktop\tam\website\management\commands\update.py", line 4, in <module> from website.models import Main_data ModuleNotFoundError: No module named 'website' this is my INSTALLED_APPS section located in my settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] -
The file is downloading in local but not in production server in Django Rest framework?
I have a simple API that downloads a file in the system. It works perfectly in the local server, but when I deploy the same code to production, it gives me a 500 server error. If I try with another id that doesn't exist, it will say the object is not found. My code is as follows. def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.request.query_params.get("download") == "file": return [] return [permission() for permission in self.permission_classes] def get(self, request, *args, **kwargs): if request.query_params.get("download") == "file": return self.download_file(request) /....other codes........./ def download_file(self, request, *args, **kwargs): instance = self.get_object() file_handle = instance.file.path document = open(file_handle, "rb") response = HttpResponse(FileWrapper(document), content_type="") response["Content-Disposition"] = ( 'attachment; filename="%s"' % instance.file_name ) return response My endpoint URL is this: {{prod}}api/v1/example/notes/12/?download=file When I call this api, putting local in place of prod, it works and I get a file downloaded, but not in production. Is it something to do with file being closed before getting a response?? -
Django complex query with a many to many field
Let's explain the problem. I am trying to filter out all Person that have certain attributes. These are my models: class Person(models.Model): community = models.ForeignKey( Community, on_delete=models.CASCADE, related_name="people" ) class Attribute(models.Model): community = models.ForeignKey( Community, on_delete=models.CASCADE, related_name="attributes" ) name = models.CharField(max_length=50) value = models.CharField(max_length=100) class Trait(models.Model): person = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="person_attributes" ) attribute = models.ForeignKey( Attribute, on_delete=models.CASCADE, related_name="traits" ) A person could have the following attributes: Attribute(name='head', value='big') Attribute(name='head', value='small') Attribute(name='head', value='medium') Attribute(name='hands', value='white') Attribute(name='hands', value='red') #... These attributes are linked to Person through the Trait entity. Now, I have the following dict, witch I use to dynamically build the query: { "head": ["small", "medium"], "hands": ["white", "red"], } I want to filter out all the Person that have the attribute "head" with the value "small" or "medium" and the "hands" "white" or "red" This is what I have done so far, but it doesn't works: # value is the dict like the one explained above from which # I will obtain the elements for filtering def routine(self, value): query = Q() for attr, traits in value.items(): if len(traits) > 0: query &= Q( Q(person_attributes__attribute__name=attr) & Q(person_attributes__attribute__value__in=traits) ) return Person.objects.filter(query) -
how to make use of the file field in django
what else do I need to add to that "file = models.FileField()" this is what I have done but am still not getting any results, why that? class Course(models.Model): TOPIC_CHOICES = ( ("History", "History"), ("Chemistry", "Chemistry"), ("Computer", "Computer") ) lecturer = models.ForeignKey(Lecturer, on_delete=models.CASCADE) category = models.CharField(choices=TOPIC_CHOICES, max_length=100) topic = models.CharField(max_length=250) file = models.FileField() date_created = models.DateTimeField(default=datetime.now) def __str__(self): return f"{self.lecturer}: {self.topic}" -
Django category dosent show up
Am making a django blog and i got problems with it displaying the posts when they are in categories. I got them to work on category_list.html to show the categories listed. But when you click in on a category you should be able to see the blog posts in that category from the categories.html I got no idea why the category posts dosent show up when you enter a category. anyone got any idea what the problem can be? I used {% for cats in cat_menu_list %} in the categories template to display it and ithink the code: def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'categories.html', {'cats': cats.replace('-', ' ').title(), 'cat_menu_list': cat_menu_list, 'page_obj': page_obj}) newsapp views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView) from .models import Post, Category, Comment from .forms import PostForm, EditForm, CommentForm from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator def LikeView(request, pk): post = get_object_or_404(Post, id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name … -
How to send multiple email invitations with django-allauth and django-invitations
I installed django-invitations to use it together with django-allauth, but it doesn't let me send several mails at the same time, which is inefficient for the correct functioning of the app. Maybe I installed something wrong. I only wrote in setting.py this: ACCEPT_INVITE_AFTER_SIGNUP = os.getenv('ACCEPT_INVITE_AFTER_SIGNUP', True) #I think allow json invites is for multiple emails, but doesn't work INVITATIONS_ALLOW_JSON_INVITES = True INVITATIONS_LOGIN_REDIRECT = os.getenv('INVITATIONS_LOGIN_REDIRECT', '/') ACCOUNT_ADAPTER = 'invitations.models.InvitationsAdapter' Or maybe exists another app who send invitations with allauth, if anyone have any advices please comment, thanks. -
creating django proejcts gets error ValueError: No closing quotation?
I want to create django project.The first thing which I did is install virtualenv for this; after run the following codes I get this error every time.And Pipfile.lock file doesn't create pipenv install virtualenv $ pipenv install virtualenv Creating a virtualenv for this project... Pipfile: C:\Users\Muhammed's\Desktop\django\kkk\Pipfile Using C:/Users/Muhammed's/AppData/Local/Programs/Python/Python39/python.exe (3.9.6) to create virtualenv... [ ] Creating virtual environment...created virtual environment CPython3.9.6.final.0-64 in 1130ms creator CPython3Windows(dest=C:\Users\Muhammed's\.virtualenvs\kkk-fuKJ3HTM, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\Muhammed's\AppData\Local\pypa\virtualenv) added seed packages: pip==22.0.4, setuptools==62.1.0, wheel==0.37.1 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator [= ] Successfully created virtual environment! Virtualenv location: C:\Users\Muhammed's\.virtualenvs\kkk-fuKJ3HTM Creating a Pipfile for this project... Installing virtualenv... Adding virtualenv to Pipfile's [packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Locking...Building requirements... Resolving dependencies... Locking Failed! Traceback (most recent call last): File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 764, in <module> main() File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 758, in main _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write, File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 741, in _main resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 702, in resolve_packages results, resolver = resolve( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 684, in resolve return resolve_deps( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1397, in resolve_deps results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1110, in actually_resolve_deps resolver.resolve() File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line … -
cant load wsgi_mod on apache server centOS
im using httpd (apache) for rocky linux to develop a django application. I am currently stuck in this problem so I dont get why dont work. Does anybody knows? -
Django Class based view comment section
Blessings, I have a page where DetailView is is being displayed and I would like to add an option to comment on the same page without redirecting to /add-comment url I've tried everything from this Tutorial and the comments still do not work. (comments wont show or post upon submitting) models.py class Comment(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, default=None) email = models.EmailField(max_length=100) content = models.TextField() post = models.ForeignKey(Movie, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return 'Comment by {}'.format(self.name) views.py class MovieDetail(DetailView): model = Movie def render_to_response(self, *args, **kwargs): self.object.refresh_from_db() self.object.views_count += 1 self.object.save() return super().render_to_response(*args, **kwargs) def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLink.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) self.object = self.get_object() context = super().get_context_data(**kwargs) post = Movie.objects.filter(slug=self.kwargs['slug'])[0] comments = post.comment_set.all() context['post'] = post context['comments'] = comments context['form'] = form if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] content = form.cleaned_data['content'] comment = Comment.objects.create( name=name, email=email, content=content, post=post ) form = CommentForm() context['form'] = form return self.render_to_response(context=context) return self.render_to_response(context=context) -
Advanced Search in Django with Multiple Fields and Keeping Filters in Pagination
I have this piece of code that is working already. It enables you to have a search form, to search in a specific table with multiple filters. The results are paginated, and this form allows you to keep these filters when you browse multiple pages. The problem I'm having now is that I am reusing this piece of code in another scenario, and it involved checking one filter in multiple fields in the database table. Example of a standard scenario: First Name Last Name City In this case, the view will be as such: def clean_filters(filters): filters = {k: v for k, v in filters.items() if v} return filters def search(request): filters = { "user__first_name__icontains": request.GET.get("fname_kw"), "user__last_name__icontains": request.GET.get("lname_kw"), "city__name__icontains": request.GET.get("city_kw"), } html_queries = { "fname_kw": request.GET.get("fname_kw"), "lname_kw": request.GET.get("lname_kw"), "city_kw": request.GET.get("city_kw"), } filters = clean_filters(filters) html_queries = clean_filters(html_queries) people = Person.objects.filter(**filters) page_num = request.GET.get("page", 1) p = Paginator(people.order_by("-pk"), 12) people = p.get_page(page_num) context = { "people": people, "cities": City.objects.all(), "filters": html_queries, } return render(request, "pages/index.html", context) And the HTML will be as such: <form method="GET" action="{% url 'search' %}"> <div class="row"> <div class="col-xl-3 col-lg-3 col-md-3 col-sm-12 col-xs-12"> <div class="row"> <div class="col-6"> <input class="form-control" name="fname_kw" id="search_fname" placeholder="First Name" /> </div> <div class="col-6"> … -
selinux is disabled and I'm still getting error 13
I'm running a django project on rhel7. Current selinux status: SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: permissive Mode from config file: permissive Policy MLS status: enabled Policy deny_unknown status: allowed Max kernel policy version: 31 Despite that, my application is still throwing this in the logs: [Mon Jun 06 17:09:12.573815 2022] [wsgi:error] [pid 34476] (13)Permission denied: mod_wsgi (pid=34476, process='graphite', application=''): Call to fopen() failed for '/opt/graphite/conf/graphite.wsgi'. -
update data using ajax with django and bootstrap modal
here is my views.py def update_article(request, pk): obj = Article.objects.get(pk=pk) if request.headers.get('x-requested-with') == 'XMLHttpRequest': new_designation = request.POST.get('designation') new_famille = request.POST.get('famille_id') new_quantite = request.POST.get('quantite') obj.designation = new_designation obj.famille = new_famille obj.quantite = new_quantite obj.save() return JsonResponse({ 'designation': new_designation, 'famille': new_famille, 'quantite': new_quantite, }) return redirect('/article') Here is my modal <div class="modal fade" id="UpdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" > <form action="" method="post" id="update-form"> {% csrf_token %} {% for field in form %} <div class="form-group col-lg-12"> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update</button> </div> </form> </div> </div> </div> here is my Js const getData = () =>{ $.ajax({ type:'GET', url:'/load/', success: function(response){ console.log(response) const data = response.article console.log(data) data.forEach(element => { articleBox.innerHTML +=` <tbody> <tr> <td><div ><a data-bs-toggle="modal" data-bs-target="#detailModal" href="" data-pic=${element.designation} class="detail" >${element.designation}</a></div></td> <td>${element.famille}</td> <td><a href="#">${element.quantite}</a></td> <td>${element.date}</td> <td>Available</td> <td><a href="#" data-bs-toggle="modal" data-bs-target="#delete">Delete</a> |<div data-bs-toggle="modal" data-bs-target="#UpdateModal" id="update-article" >Edit</div></td> </tr> </tbody> ` }); }, error: function(error){ console.log(error) } }) } from this code I want to update my data by id,I've tried everything but when I click the edit button , the form modal … -
Can multiple values be assigned to one variable without brackets "[]" or parentheses "()" (Python)
From this django answer in SO, I found 3 variables "JAN", "FEB" and "MAR" in the class "Month" extending "models.TextChoices" as shown below: # "models.py" from django.db import models class MyModel(models.Model): class Month(models.TextChoices): JAN = "1", "JANUARY" # Here FEB = "2", "FEBRUARY" # Here MAR = "3", "MAR" # Here # (...) month = models.CharField( max_length=2, choices=Month.choices, default=Month.JAN ) And multiple values are assigned to each variable without brackets "[]" which creates Array or parentheses "()" which creates Tuple as shown below: JAN = "1", "JANUARY" FEB = "2", "FEBRUARY" MAR = "3", "MAR" Now, can multiple values be assigned to one variable without brackets "[]" or parentheses "()"? -
Undefined Json response from django backend to chrome extension alert
Hi i am trying to return a json file to the chrome extention to show it to the user, the query go to server without a problem, fetched url is also working and does return the json file when i try it directly, but the chrome extention shows "undefined" message in the alert instead of the json file. the returned json file have this type : JsonResponse(data) data is a dict[str, Union[str, list]], another question, is how can i show the json file in the popup html page? to my chrome extension code: Manifest.json: { "name": "Price Comparator", "description": "Compare prices across other websites!", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "background.js" }, "icons": { "16": "images/logo16.png", "48": "images/logo48.png", "128": "images/logo128.png" }, "action": { "default_icon": "images/logo16.png", "default_popup": "popup.html" }, "host_permissions": ["XXX*"], "permissions": [ "XXX", "http://127.0.0.1:8000/", "storage", "activeTab", "scripting", "tabs", "background", "identity", "notifications" ], "content_scripts": [ { "matches": [ "https://www.google.com/*" ], "css": [ "main.css" ] } ] } popup.js: $(function(){ $('#keywordsubmit').click(function(){ var search_topic = $('#keyword').val(); if (search_topic){ chrome.runtime.sendMessage( {topic: search_topic}, function(response) { result = response.farewell; alert(result.summary); var notifOptions = { type: "basic", iconUrl: "icon48.png", title: "WikiPedia Summary For Your Result", }; chrome.notifications.create('WikiNotif', notifOptions); }); } $('#keyword').val(''); }); }); Background.js: chrome.runtime.onInstalled.addListener(() => … -
Django-tables2 exporting badly
I'm using django-tables2 for export my tables. When I export the table to excel format it seems like this: enter image description here. I can't see all of the cell. How can I set the width of excel columns before export? tables.py import django_tables2 as tables from .models import Customer class CustomerTable(tables.Table): export_formats = ['xls','xlsx','csv'] class Meta: model = Customer fields = ('orderorbarcode','item_barcode','order_id', 'full_name','company','email','phone_number','note') html part <div class="container"> {% for format in table.export_formats %} <a id="{{format}}" href="{% export_url format %}">.{{ format }}</a> {% endfor %} {% render_table table %} </div> -
Extend User model in Django with jwt authorization
I am trying to extend User model in Django. I already have authorization using jwt Token and I am currently trying to add another field to User model, such as phone number and address. My views.py looks like this: class MyObtainTokenPairView(TokenObtainPairView): permission_classes = (AllowAny,) serializer_class = MyTokenObtainPairSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer models.py like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.IntegerField(blank=False) address = models.CharField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() In here I'm trying to create another class that will store phone number and address. How can I incorporate my Profile class into User so that it will create new user model and what is more use earlier implemented Token authorization. -
Multiple nested choices in Django models
Forgive me if I'm not describing this correctly - I'm still learning and I've hit a wall with a problem I'm working on. I want to create a way (in the Admin backend for now) for users to show the books they like by fiction/non-fiction, age-range, genre(s) and sub-genre(s). So, a user who liked gothic horror books could select fiction>adult>horror>gothic. Or, a user who likes literally all YA books could select fiction>Young Adult and their selection would cascade down to every genre and sub-genre. I think the Choices field option and the MultiSelectField functionality might be a start, but there doesn't seem to be a way to add 'layers' to the choices beyond the categories below, and it seems like an inelegant solution when there could be hundreds of choices. I also don't know how it could be presented in the Admin - ideally with checkboxes that can 'open up' to show the sub-categories beneath them. GENRE_CHOICES = ( ('Fiction', ( ('FCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ('Non-Fiction', ( ('NCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ) genres = MultiSelectField(max_length = 100, choices=GENRE_CHOICES, null=True) I don't even know the name of … -
Django blog categories wont show up
I got a problem where my blog post categories dosent show up on my categories page with the code i used below from cat_menu_list and {% for post in cat_menu_list %}. How do i get the diffrent categories to show up in my categories.html? hope someone can help ithink below is all the code that does this if u need anymore tell me and i upload it asap. views.py def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', { 'cat_menu_list': cat_menu_list}) def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render( request, 'categories.html', { 'page_obj': page_obj, 'cats': cats.replace('-', ' ').title(), "cat_menu_list": cat_menu_list}) categories.html {% extends 'base.html' %} {% block content %} <h1 class="headerh1">{{ cats }}</h1> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in cat_menu_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title"><a href="{% url 'article-detail' post.pk %}" class="text-dark">{{post.title }}</a></h2> <p class="card-text text-dark h6">{{ post.author.first_name }} {{post.author.last_name }} | {{ post.post_date }} <a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a></p> <div class="card-text">{{ post.body|safe|slice:":200" }}</div> <a href="{% url 'article-detail' post.pk %}" class="btn btn-info">Read More</a> {% if user.is_authenticated %} {% if user.id == … -
Django file/image upload not responding
I've gone through about 8 tutorials across YouTube and Online websites. I believe everything is configured correctly. However, when my objects are created it is not creating the media directory or storing the files. I have done the settings file, urls, views, models everything. Any advice is greatly appreciated here are my files: // setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') // models.py class Trip(models.Model): city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) description = models.CharField(max_length= 255) creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE, null=True) favoriter = models.ManyToManyField(User, related_name= 'fav_trips') photo = models.ImageField(null=True, blank =True, upload_to='trips') // urls.py ( there were 2 ways to write media according to tutorial) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('travelsiteapp.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) // views.py (lastly) def tripAdd(request): form = TripForm() if request.method == 'POST': form = TripForm(request.POST, request.FILES) if form.is_valid(): form.photo = form.cleaned_data["photo"] form.save() context = { 'form': form} return render(request, 'tripAdd.html', context) // I have hit all the steps not sure whats wrong? & and installed pip pillow -
Getting Errors while starting mod wsgi (Django app) via apache
Starting up a dockerised django application as a mod wsgi app via apache. Getting an endless stream of below errors. Errors: 2022-06-02 16:05:12.225137 [notice] [pid 10002] mpm_unix.c(436): [client AH00052: child pid 10992 exit signal Aborted (6) 2022-06-02 16:05:12.225382 [info] [pid 10002] src/server/mod_wsgi.c(7761): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' has died, deregister and restart it. 2022-06-02 16:05:12.225411 [info] [pid 10002] src/server/mod_wsgi.c(7775): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' terminated by signal 6 2022-06-02 16:05:12.225433 [info] [pid 10002] src/server/mod_wsgi.c(7846): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' has been deregistered and will no longer be monitored. 2022-06-02 16:05:12.227789 [notice] [pid 10002] mpm_unix.c(436): [client AH00052: child pid 10993 exit signal Aborted (6) 2022-06-02 16:05:12.227856 [info] [pid 10002] src/server/mod_wsgi.c(7761): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' has died, deregister and restart it. 2022-06-02 16:05:12.227874 [info] [pid 10002] src/server/mod_wsgi.c(7775): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' terminated by signal 6 2022-06-02 16:05:12.227896 [info] [pid 10002] src/server/mod_wsgi.c(7846): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' has been deregistered and will no longer be monitored. 2022-06-02 16:05:12.228150 [info] [pid 10994] src/server/mod_wsgi.c(9381): [client mod_wsgi (pid=10994): Starting process 'in.goibibo.com' with uid=2, gid=2 and threads=30. 2022-06-02 16:05:12.229803 [info] [pid 10995] src/server/mod_wsgi.c(9381): [client mod_wsgi (pid=10995): Starting process 'in.goibibo.com' with uid=2, gid=2 and threads=30. 2022-06-02 16:05:12.230033 [info] [pid 10994] src/server/wsgi_interp.c(2260): [client mod_wsgi (pid=10994): Initializing Python. … -
How do you pass options to Django-flatpickr date picker?
Im trying to implement a datetime picker on a Django app but im having some trouble working out how to pass options to the picker using the django-flatpickr package -->docs here: django-flatpickr. The docs really just get you started but don't go into any detail on how to apply some options and filter provided by the flatpickr.js package. I have successfully implemented the basics with the form fields and passing it to and from the the template which all works fine. However im having difficulty passing options i.e a start date, end date, allowed dates, making sure dates can't be selected I the past etc So the backend: forms.py class DatePickerForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) date_from = forms.DateTimeField(widget=DateTimePickerInput()) date_to = forms.DateTimeField(widget=DateTimePickerInput()) amount = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) views.py def check_availability(request): #Get date time vals from client, pass to check_availabilty to query db if request.method == 'POST': form = DatePickerForm(request.POST) if form.is_valid(): cd = form.cleaned_data availability = check_availability(cd['id'], cd['date_from'], cd['date_to'], cd['amount']) else: print('Not bloody valid') return HttpResponse(f'Availabilty = {availability}') ClientSide: mytemplate.html <form action="{% url 'check_availability' %}" method="post"> {{ date_form.media }} {{ date_form.as_p }} <input type="hidden" name="id" value="{{ rental.id }}"> {% csrf_token %} <br> <button type="submit" value="Check Dates">Check Availability</button> </form> So what im really looking … -
Exporting tables in Django
I'm trying to export my Table datas. I tried to use django-tables2 but I couldn't did. From documentation I didn't understand much. How can I export my table? my html <!DOCTYPE html> {% load django_tables2 %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <title>Admin Page</title> </head> <body> <div class="container"> {% for format in table.export_formats %} <a href="{% export_url 'csv' %}">.{{ format }}</a> {% endfor %} </div> {% render_table table %} </body> </html> tables.py import django_tables2 as tables from .models import Customer class CustomerTable(tables.Table): export_formats = ['xls','xlsx','csv'] class Meta: model = Customer fields = ('orderorbarcode','barcode', 'full_name','company','email','phone_number','note') And it keep saying no module named django-tables2: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'olvapp', 'tablib', 'django-tables2', ] And When I pip list: django-tables2 2.4.1 -
Django + Django Rest Framework: get correct related objects on intermediate model
I have an intermediate model with the following fields: class UserSkill(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='user_skills') disabled = models.BooleanField(default=False) As you can see, it has two foreign keys, one to the auth user and one to another table called skill. I am trying to get all Skills assigned to an specific user, so I do the following get_queryset in my ViewSet: class AssignedSkillViewSet(viewsets.ModelViewSet): queryset = Skill.objects.all() serializer_class = AssignedSkillSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user return Skill.objects.filter(user_skills__user=user, user_skills_user__disabled=False)) Now, I also need to include the intermediate model information in the API, which I can access trough users_skills related name in DRF's Serializer, as follows: class AssignedSkillSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Skill fields = [ 'id', 'url', 'title', 'description', 'user_skills', ] But when I try to get that information it returns ALL user_skills related to the assigned skill, no matter if they are assigned to other users. I need the related model information only for that user and that skill. For Example: If I have a skill named Math, and a user named Maria related_skills = Skill.objects.filter(user_skills__user=user, user_skills_user__disabled=False)).user_skills.all() The above code will return: [ <UserSkill: Math+Jenniffer>, <UserSkill: Math+Gabriel>, <UserSkill: Math+John>, <UserSkill: Math+Maria>, ] I only … -
Can't Create Django Test Database
I have a django 3.2/mysql 5.7.38 web site that is working. I am trying to write some unit test for the first time, and I am getting an error regarding the creation of the test database. About 1/2 of the tables are created before this error occurs (hence the question about the database already exists. Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_hopi_django'; database exists") Type 'yes' if you would like to try deleting the test database 'test_hopi_django', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'test_hopi_django.CurrentArticle' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/commands/test.py", line …