Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the correct permissions and virtualhosts for running Django in a sub-directory?
I'm trying to install and run Django in a sub-directory, to keep it separate from a static html site in root, and am having issues with either file/folder permissions or virtualhosts. These two questions haven't helped and are very old: install django on subdirectory and Configure django on sub directory Is this file/folder permissions or virtualhosts issue? Why are the .py files not executing? Running Ubuntu 20.04.3 LTS Apache2 already installed and running Python3 and Django installed libapache2-mod-wsgi installed and enabled Apache restarted several times I ran the usual shell commands to start a Django project: django-admin.py startproject contact and then I ran createsuperuser, collectstatic, etc., successfully. https://example.com/contact/index.html works fine, But this is what I get at example.com/contact/contact: This is my file structure: settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '...' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'contact.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'contact.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS … -
graphene-django: Determine Object type when multiple GraphQL object types use the same django model in node query
This is specifically for graphene-django (not just graphene) when performing a node(id: ...) {} query. Assume a fixed schema with 2 (or more) different GraphQL object types using graphene_django.DjangoObjectType linked to the same django model: import graphene_django from .models import Org as OrgModel class Org(graphene_django.DjangoObjectType): class Meta: model = OrgModel fields = ( "id", "name", "billing" ) class AnonymousOrg(graphene_django.DjangoObjectType): class Meta: model = OrgModel fields = ( "id", "name", ) Let's assume a query to Org of ID 7eca71ed-ff04-4473-9fd1-0a587705f885. btoa('Org:7eca71ed-ff04-4473-9fd1-0a587705f885') 'T3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==' { node(id: "T3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==") { id __typename ... on Org { id } } } Return: { "data": { "node": { "id": "QW5vbnltb3VzT3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==", "__typename": "AnonymousOrg" } } } It returns the other object type 'AnonymousOrg:7eca71ed-ff04-4473-9fd1-0a587705f885', despite the relay ID specifying it was an Org object. Is there a way in graphene-django to "hint" or provide detail to assure the return type if what's specified in the ID and its fragment? Clarification on question Other questions were discussing graphene, not specifically graphene-django, which is doing the type determinations in this case. This is different from Django-graphene multiple types for the same model, as that one asked about how to handle field permissions and opened possibility to reconsidering schema structure (e.g. splitting … -
Django Test Update View(edit) error(AssertionError: 'Test Description' != 'Edited Test Description')
I wrote an edit test, the response status code is working very fine which is 302 but I went ahead to assertEquals to the updated content but it was throwing assertion error. MODELS class Banner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=150 , unique=True) description = RichTextField(blank=True, null=True) category = models.CharField(max_length=200) tag = models.CharField(max_length=200) image = models.ImageField(upload_to='banner-images/') slug = models.SlugField(unique=True, max_length=100) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super(Banner, self).save(*args, **kwargs) VIEWS @login_required(login_url='login') def editBanner(request, slug): banner = get_object_or_404(Banner.objects.all(), slug=slug) if request.user == banner.user: form = BannerForm(instance = banner) if request.method =="POST": form = BannerForm(request.POST, request.FILES, instance = banner) if form.is_valid(): form.save() return redirect('home') context = {'form':form, 'banner':banner} return render(request, 'edit-banner.html', context) return redirect('home') URLS from django.urls import path from . import views urlpatterns = [ path('banner/<slug:slug>/edit/', views.editBanner, name='edit-banner'), ] TEST def test_edit_banner(self): new_banner = Banner.objects.create( name='The Test Banner', description='Test Description', category='testcategory', user= self.user, slug= 'the-test-banner', tag='testtag', image='testimage.jpg', ) response = self.client.post(reverse('edit-banner', args=['the-test-banner']), { 'name': 'The Test Banner', 'description': 'Edited Test Description', 'category': 'testcategory', 'user': self.user, 'tag': 'testtag', 'image': 'testimage.jpg', }) self.assertEquals(response.status_code, 302) new_banner.refresh_from_db() self.assertEquals(new_banner.description, 'Edited Test Description') But I keep getting this error after many tweaking I want to get the … -
Django Form has no attribute get
I have an form class EntryForm(forms.ModelForm): status = forms.ChoiceField( choices=Maca.Status.choices, widget=forms.RadioSelect(attrs={"class": "radio-ul"}), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Entry fields = ["status", "commission"] I try to update the object with class based view def post(self, request, *args, **kwargs): entries = UsersProductConfig.objects.get(pk=request.POST["object_id"]) maca = EntryForm(request.POST or None, instance=entries) if maca.is_valid(): maca.save() return maca But I got the following error 'EntryForm' object has no attribute 'get' -
Postgres in Docker/ Django app does not work - OperationalError: could not connect to server: Connection refused
I have a Django app that runs locally with no problems. Now, I want to get a docker image of my app but when I try to build it, it gives me the following error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? I am new on Django and Docker development and i was looking for similar questions but none answer solved my problem. I'll show you my Dockerfile, I have copied the Postgres commands from another project that does work: FROM python:3.8 RUN apt-get update RUN mkdir /project WORKDIR /project RUN apt-get install -y vim COPY requirements.txt /project/ RUN pip install -r requirements.txt COPY . /project/ # Install postgresql RUN apt install -y postgresql postgresql-contrib RUN service postgresql start # Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.3`` package when it was ``apt-get installed`` USER postgres # Create a PostgreSQL role RUN /etc/init.d/postgresql start &&\ psql --command "CREATE USER admin WITH SUPERUSER PASSWORD 'administrador';" … -
Django related_name with _set function
I'm using related_name tag in my models and I'm trying to filter my form with _set function. However I'm having this error; AttributeError: 'Client' object has no attribute 'contact_owner_set' I think the problem is in right here; self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name') I've tried to remove related_name field and change this bit to; self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name') However I need related_name for my other functions. Is there any way to figure this out? models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Client(models.Model): name = models.CharField(max_length=100) def get_absolute_url(self): return reverse("client-detailview", kwargs={"slug": self.slug}) def __str__(self): return str(self.name) class Contact(models.Model): client_owner = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='contact_client') # client.contact_client name = models.CharField(max_length=100) def get_absolute_url(self): return reverse("contact-detailview", kwargs={"slug": self.slug}) def __str__(self): return str(self.client_owner) + " - " + str(self.name) class Action(models.Model): client_owner = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='action_client') # client.action_client contact_owner = models.ManyToManyField(Contact, related_name='action_contact', blank=True, null=True) # contact.action_contact topic = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.topic) + " - " + str(self.user_owner) + " - " + str(self.client_owner) + " - " + str(list(self.contact_owner.all().values_list('name', flat=True))) views.py from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy from .models import Action, Contact from .forms import ActionForm class ActionListView(ListView): model = Action context_object_name = … -
cycle through output and add to database
An API call returns some data that I want to upload into the database, it returns about 5000 records. I only want to run this manually when needed. [ { "id": "01", "symbol": "xyz", "name": "xyz" }, { "id": "02", "symbol": "abc", "name": "abc" }, { "id": "04", "symbol": "fhf", "name": "fhf" }, { "id": "05", "symbol": "gxfg", "name": "gxfg" }, ] Is there a way I can cycle through each one and upload it to a model? The model will have matching field names os ID Symbol and Name -
Django AllAuth redirecting to signin for for First and Last name despite not required
I'm using Django AllAuth and trying to let people instantly log in with Discord. When they do that, it takes them to a signup form that forces them to enter their First and Last Name. These are not required fields in my user model so I have no idea why this would be forced. Here are my settings: # Authentication - Using AllAuth ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_CONFIRM_EMAIL_ON_GET = False ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 180 ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_ACTIVATION_DAYS = 360 LOGIN_URL = '/login/' LOGOUT_URL = '/account/logout/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIALACCOUNT_EMAIL_REQUIRED = False SOCIALACCOUNT_FORMS = {} SOCIALACCOUNT_QUERY_EMAIL = False -
How to print Django Ajax return as Template Data?
I want to print Products data returned by following views on template. When I check the context its printing the correct data but when I try to print data in template it shows nothing. I checked Networks inside browser console, data is called there but I dont know why its not printing to views Template {% for product in products%} {{product.name}} {%endfor%} My Ajax: $(document).ready(function() { var compare = localStorage.getItem("comparisionItems"); var compareObj = JSON.parse(compare); console.log(compareObj) $.ajax({ url: './compare', type: "POST", data: compare, headers: { "X-CSRFToken": $.cookie("csrftoken") }, dataType: "json", contentType : "application/json", processData: "false", success: function (data) { location.reload(); }, }); }); Views.py def compare(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax and request.method == "POST": data = json.loads(request.body) compare_ids = data['itemIds'] products = Products.objects.filter(id__in=compare_ids) print(products) context={'products':products} return render(request,'./compare.html', context) else: return render(request,'./compare.html') -
Convert tuple and nested dictionary to DataFrame
I have the following code in my function get_context_data(self, **kwargs): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['uploaded'] = self.request.session['uploaded'] context['selection'] = self.request.session['selection'] dict_comparaison_p1 = dict(enumerate(context['uploaded'].items())) list_comparaison_p2 = context['selection'] dict_comparaison_p2 = {number: dict_comparaison_p1[number] for number in list_comparaison_p2} pprint(dict_comparaison_p2) My dict_comparaison_p2 has the following output: {0: ('Product', {'0': 'Smartwatch', '1': 'Shoes', '2': 'Necklace'}), 1: (' Weight', {'0': 2, '1': 50, '2': 40}), 2: (' Price', {'0': 100, '1': 240, '2': 230})} I want to convert it to a DataFrame like that: Product Weight Price 0 Smartwatch 2 100 1 Shoes 50 240 2 Necklace 40 230 But when I try to convert it with my output, I have the following result: 0 1 2 0 Product Weight Price 1 {'0': 'Smartwatch', '1': 'Shoes', '2': 'Neckla... {'0': 2, '1': 50, '2': 40} {'0': 100, '1': 240, '2': 230} Could you please help me with that? Thanks! -
Django separate location of static files
I am working with Django 3.2 and I have 3 types of static files (images, css files, js files). I did not want the images to be versioned with git so I found a way to have them served by an aws S3 bucket using django-storages and boto3. It works perfectly fine with the following configuration in my settings.py file: AWS_ACCESS_KEY_ID = "my-key-id" AWS_SECRET_ACCESS_KEY = "my-secret-key" AWS_STORAGE_BUCKET_NAME = "my-bucket-name" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_ADDRESSING_STYLE = "virtual" AWS_S3_REGION_NAME = 'my-region' AWS_S3_SIGNATURE_VERSION = 's3v4' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Whilst this configuration works perfectly fine, it forces me to have my CSS and js files in the AWS s3 bucket as well. I was perfectly happy with my CSS and js files being served by django (or NGINX in production) and versioned with my code without having to copy them to the bucket manually. Would you have a solution to serve only static images by AWS S3 and CSS/JS files by NGINX ? -
bad request when django deployed to heroku
I've just attempted to deploy my django project to Heroku and I am getting a bad request 400 error. The strange thing is that it was working fine before hand and I had to make changes to my code. This works fine locally too. Really confused right now. Any help on where I am going wrong would be great. part of my settings.py file X_FRAME_OPTIONS = 'SAMEORIGIN' ALLOWED_HOSTS = ['engagefitness.herokuapp.com', 'localhost'] -
Django Custom Filter to get video duration using MoviePy not working
I am trying to use a custom filter to find the video duration using moviepy however the function is not able to access the files even though it seems the correct video path is being passed into the function in the custom filter. I'm getting the following error: OSError at /tape/tape/ MoviePy error: the file /media/video_files/channel_Busy/171003B_026_2k.mp4 could not be found! Please check that you entered the correct path. The custom filter: vduration.py from django import template import moviepy.editor register = template.Library() @register.filter(name='vduration') def vduration(videourl): video = moviepy.editor.VideoFileClip(videourl) video_time = int(video.duration) return video_time views.py def tape(request): tapes=VideoFiles.objects.all() context={ "videos": tapes, } return render(request, "tape/tape.html", context) tape.py {% for video in videos %} <div class="video-time">{{video.video.url | vduration}}</div> {% endfor %} models.py class VideoFiles(models.Model): id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) video=models.FileField(upload_to=channel_directory_path) def get_absolute_url(self): return reverse('video_watch', args=[str(self.id)]) def __str__(self): return f"video_file_{self.id}" -
Deleting object with django inline_formset
Am trying to build a page that allows a restaurant owner to edit/delete items from their menu. Models.py: class Restaurant(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) name = models.CharField(max_length=200, verbose_name = 'Restaurant Name') class Menu(models.Model): restaurant = models.OneToOneField( Restaurant, on_delete=models.CASCADE, primary_key=True, ) class Item(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField(blank=True) views.py: def test_url(request): # Get this Restaurant object restaurant = Restaurant.objects.get(pk = 1) # Get this Restaurant's Menu object restaurant = restaurant.menu # Create inline formset ItemFormSet = inlineformset_factory(Menu, Item, fields=('name', 'description',), max_num=1, extra=0, can_delete=True) if request.method == 'POST': formset = ItemFormSet(request.POST, instance = menu) if formset.is_valid(): for form in formset: form.save() return HttpResponse(formset.cleaned_data) # referenced later in the question else: formset = ItemFormSet(instance = menu) return render(request, 'restuarant/edit_menu.html', { 'formset': formset, }) The docs state the can_delete attribute: " adds a new field to each form named DELETE and is a forms.BooleanField. When data comes through marking any of the delete fields you can access them with deleted_forms". This does add the delete field to my template, and if I select that checkbox on one of the forms it will return: {'name': 'Fried Calamari', 'description': '', 'id': , 'DELETE': True, 'menu': .RelatedManager object at 0x7fa644347a30>>>} but … -
Django urls href redirect bug
When I click on the "apropos" button on my navbar to access to my "apropos" pages it load the page correctly but with this url http://127.0.0.1:8000/contact/apropos/ when it should be http://127.0.0.1:8000/apropos/. it does the samething when I click on the "contact" button on my navbar it redirect me to this urls http://127.0.0.1:8000/contact/contact And when I click on "Accueil" it redirect me to http://127.0.0.1:8000/contact When it should redirect me to http://127.0.0.1:8000/ mysite/urls.py urlpatterns = [ path("", include("main.urls")), path('admin/', admin.site.urls), path("apropos/", include("main.urls")), path("contact/", include("main.urls")), ] main/urls.py urlpatterns = [ path("", views.home, name="home"), path("apropos/", views.apropos, name="apropos"), path("contact/", views.contact, name="contact") ] views.py def home(response): return render(response, "main/index.html", {}) def apropos(response): return render(response, "main/about.html", {}) def contact(response): return render(response, "main/contact.html", {}) index.html (navbar section) <!-- header nav section --> <header class="xs-header-nav"> <div class="container"> <div class="row menu-item"> <div class="col-lg-12"> <nav id="navigation1" class="navigation header-nav clearfix"> <div class="nav-header"> <!-- <a class="nav-brand" href="#"></a>--> <a href="./index.html" class="mobile-logo"> <img src="static/assets/images/mobile_logo.png" alt=""> </a> <div class="nav-toggle"></div> </div> <div class="nav-menus-wrapper clearfix"> <ul class="nav-menu"> <li class="active"><a href="{% url "home" %}">Home</a> </li> <li><a href="#">Services</a> </li> <li><a href="gallery.html">Portfolio</a></li> <li><a href="{% url "apropos" %}">À-propos</a></li> <li> <a href="{% url "contact" %}">Contact</a> </li> </ul> <div class="header-nav-right-info align-to-right"> <label><i class="icon icon-phone3"></i> (514) 569-2380</label> </div> </div> </nav> </div> </div><!-- .row end --> … -
Getting 500 internal Server Error using django and apache
Hi I'm in the works of making my project live but I am getting a 500 Internal error when trying to access the server domain. This is my first time making a project live using apache and django and linux so it may be something simple that I don't know how to fix, but so far I've set ownership my project with sudo chown www-data mysitenew and for my database (db.sqlite3) as well. I had a suspicion that it could be something to do with changing my pre-existing environment variables to a JSON file where all my variables are stored then added to with json.load in settings.py, but I have done a lot of research and kind find anything that relates to my case as there is nothing indicating in error.log where my problem is. My second suspicion is that I am not on the root but I am on a user which I created and gave the group sudo too, I wasn't sure if that could be problem when setting permissions it may be something there but as I said I am unexperienced when it comes to using linux. I'm going to be updating this question as I keep … -
Query data in django matched with ids in a list
I am trying to update some data in my django models But kinds stuck on how to get that particular attributes. see I have a list name ids = ['112', '111', '114', '113', '115'] And I have a model name Member class Member(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committee, on_delete=models.CASCADE,verbose_name='Committee Name') mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status') mem_note = models.TextField(null=True, blank=True) mem_order = models.IntegerField(default=0) So each id in ids have a object available in Member Model, What I want is to update the mem_order of each object like this. suppose 111 in ids is at 2nd index. I want to set mem id with 111 to set 2 in mem_order. I am getting all the desired members from Member table Now I dont know how to loop over those ids and match them the id of Each Member from Member model. -
Page not found when I log out, any idea why the logging out doesn't work?
Working on a social app with django and clicking on the log out doesn't work anymore for some reason I get: Page not found (404) No profile found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/logout Raised by: network.views.<class 'network.views.ProfileDetailView'> Using the URLconf defined in project4.urls, Django tried these URL patterns, in this order: admin/ [name='all-profiles-view'] [name='profile-view'] The current path, logout, matched the last one. Also is there an easy way to make the user's name clickable from any page directed to their profile(ProfileDetailView)?? URLs: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import ( posts_of_following_profiles, like_unlike_post, invites_received_view, invite_profiles_list_view, send_invitation, remove_friends, accept_invitation, reject_invitation, ProfileDetailView, PostDeleteView, PostUpdateView, ProfileListView, ) urlpatterns = [ path("", ProfileListView.as_view(), name="all-profiles-view"), path("<slug>", ProfileDetailView.as_view(), name="profile-view"), path("posts/", views.post_comment_create_view, name="posts"), path("posts-follow/", posts_of_following_profiles, name="posts-follow"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("liked/", like_unlike_post, name="like-post-view"), path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"), path("<pk>/update", PostUpdateView.as_view(), name="post-update"), path("invites/", invites_received_view, name="invites-view"), path("send-invite/", send_invitation, name="send-invite"), path("remove-friend/", remove_friends, name="remove-friend"), path("invites/accept/", accept_invitation, name="accept-invite"), path("invites/reject/", reject_invitation, name="reject-invite"), path("to-invite/", invite_profiles_list_view, name='invite-profiles-view') ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from … -
Can you pass a session value into a views parameter in django?
Here is a simple adding view I created: def adder(request): request.session['one'] = 1 request.session['two'] = 2 one = request.session['one'] two = request.session['two'] answer = one+two return HttpResponse(answer) I want to be able to do somethign like this: def adder(request,one = request.session['one'], two = request.session['two']): answer = one+two return HttpResponse(answer) I would create the sessions 'one' and 'two' in a separate view beforehand. The reason that I want to pass them in as parameters is that I have some python code that I wish to run in django and it requires parameters that will be input by the user. Any advice would be appreciated. -
Django ModuleNotFoundError all of a sudden
All of a sudden, my django project is not working anymore. Not only my actual branch but even master. This happened after coming back to my project after the night. The error I have is when I run any command I have this message : ModuleNotFoundError: No module named 'pur_beurre.pur_beurre' (Note : pur_beurre is the name of my project) When I run python manage.py, I have the list of all possible commands plus this new message in red : Note that only Django core commands are listed as settings are not properly configured (error: No module named 'pur_beurre.pur_beurre'). I tried to put pur_beurre and pur_beurre.pur_beurre in my installed app in settings.py but its not working. -
One-To-Many Model Serializer not displaying object in django rest framework
I have a one to many model in django rest framework. Video is the parent and Tags are the child, I'm trying to display all the tags in the Video serializer. class Video(Base): video = models.FileField(null=True, blank=True) thumbnail = models.ImageField(null=True, blank=True) class Tag(Base): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='tags') text = models.CharField(max_length=100, null=True, blank=True) score = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) In my serializer I have this, class VideoSerializer(serializers.ModelSerializer): video = serializers.FileField(max_length=None, use_url=True, allow_null=True, required=False) thumbnail = serializers.ImageField(max_length=None, use_url=True, allow_null=True, required=False) class Meta: model = Video fields = ('id', 'video', 'thumbnail', 'tags') The problem is that the serialized data only show the id for the Tags. Any help appreciated. -
How to display search term on search results page in django?
I made a form and then i made little search form and it works but, i didnt display the search term on the search results page... I just wanna show Search Results for (Search Term) Here are my codes. Views.py class SearchResultsView(ListView): model = Post template_name = 'search.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Post.objects.filter(Q(soru1__icontains=query) | Q(soru2__icontains=query) | Q(soru3__icontains=query) | Q(soru4__icontains=query) | ) return object_list Base.html ( search bar in it) <form class="d-flex" action="{% url 'search' %}" method="get"> <input class="form-control me-2" name="q" type="text" placeholder="Arama..."> <button class="btn btn-outline-success" type="submit">Ara</button></form> And search.html {% extends 'base.html' %} {% block content %} <h1>Search Results for </h1> <ul> {% for Post in object_list %} <li> <a href="{% url 'article-detail' Post.id %}">{{ Post.soru1 }}</a> </li> {% endfor %} </ul> {% endblock %} -
Django how to add a form to a DetailView with FormMixin
I am attempting to add a form for comments to a DetailView. The DetailView displays notes for specific projects. So the comments have a foreign key that is the specific note and the note has a foreign key for the specific project. I am attempting to use FormMixin with DetailView. So far I have not bee successful. Currently I can get the form to display but it does not save and in the terminal I see the following error Method Not Allowed (POST): /projects/project/1/note/1/ I can get these to work separately but not with the form in the DetailView. Here are my models: class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title class ProjectNoteComments(models.Model): body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments') The View: class ProjectNotesDetailView(DetailView, FormMixin): model = ProjectNotes id = ProjectNotes.objects.only('id') template_name = 'company_accounts/project_note_detail.html' comments = ProjectNotes.comments form_class = NoteCommentForm def form_valid(self, form): projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk')) comment = form.save(commit=False) comment.projectnote = projectnote comment.save() return super().form_valid(form) def get_success_url(self): return reverse('project_detail', args=[self.kwargs.get('pk')]) The form: class NoteCommentForm(forms.ModelForm): class Meta: model = ProjectNoteComments fields =['body',] widgets = { 'body': forms.TextInput(attrs={'class': 'form-control'}) } The … -
Want to show the image_name in the Django update form
This is my post item view code if request.method == 'POST': form = MenuItemForm(request.POST,request.FILES) image = request.FILES['image'] image_url = upload_image(image, 'menu_item', image.name) if form.is_valid(): obj = form.save(commit=False) obj.image_url = image_url form.save() return redirect('menu-item') This is my view for the update def menu_item_update(request, id): item = MenuItem.objects.get(id=id) if request.method == 'POST': form = MenuItemForm(request.POST,request.FILES, instance=item) if form.is_valid(): form.save() return redirect('menu-item') else: form = MenuItemForm(instance=item) context = { 'form': form, } return render(request, 'menu/menu_item_update.html', context) and this is my form class MenuItemForm(forms.ModelForm): image = forms.ImageField() class Meta: model = MenuItem fields = ['name', 'description', 'menu_category'] And this is my model class MenuItem(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) As you can see in my post view, I am uploading the file to the google storage bucket and saving only the URL to the database. Now I want to show the same file or its file name to the update form in the image field, after reading the image from google storage. I have the image URL but how to do it I do not know. -
How to update a model which contains an ImageField in django rest framework?
I need help updating a model that contains an ImageField with django rest framework (3.12.4). I've checked many questions related to this, but none seem to fix the problem. models.py class Image(models.Model): title = models.CharField(max_length=200, unique=True) image = models.ImageField(upload_to="images/") def delete(self, *args, **kwargs): self.image.delete() super().delete(*args, **kwargs) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['id', 'title', 'image'] views.py class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() parser_classes = (MultiPartParser, FormParser) def create(self, request, *args, **kwargs): file_serializer = ImageSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) This way I can add a new image. The file is successfully added to images folder and the fields are serialized correctly. I can also delete created image, removing the file from images folder and instance from database. However, when I access the instance, I am unable to modify it without reloading the file; so if I want to change the title, I have to reload the file again and then make the request. Is there any way to update a model that contains an ImageField in django rest framework?