Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset for a multiple table query
For the below sample schema # schema sameple class A(models.Model): n = models.ForeignKey(N, on_delete=models.CASCADE) d = models.ForeignKey(D, on_delete=models.PROTECT) class N(models.Model): id = models.AutoField(primary_key=True, editable=False) d = models.ForeignKey(D, on_delete=models.PROTECT) class D(models.Model): dsid = models.CharField(max_length=255, primary_key=True) class P(models.Model): id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=255) n = models.ForeignKey(N, on_delete=models.CASCADE) # raw query for the result I want # SELECT * # FROM P, N, A # WHERE (P.n_id = N.id # AND A.n_id = N.id # AND A.d_id = \'MY_DSID\' # AND P.name = \'MY_NAME\') What will be the queryset for this kinda raw query ? or is there a better way to do it ? Above code is here https://dpaste.org/DZg2 -
Django Python | Returning Render(request) and HTTP Reponse at the same time?
I'm trying to return a Render(request) and an HTTPReponse at the same time.. def home(request): db_userpull = user.objects.all().values_list('userkey', flat=True) http_resp = HttpResponse() http_resp.set_cookie('foo', 'bar') #return render(request, 'home.html', {"db":db_userpull}) #return http_resp return render(request, 'home.html', {"db":db_userpull, "sesstest":request.session['user_s_key']}) , http_resp Essentially the goal is, on load the page displays stuff from the database, and create a Cookie using an http response at the same time.. When I return them separately, they work fine (either creates a cookie, or returns the database data) I'm trying to get it to return both, but I'm getting an Attribute Error; AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.4 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' -
Django with CherryPy - ModuleNotFound errors
I found a gist that feasibly would allow me to integrate a CherryPy webserver into my program, and run a Django project via that CherryPy webserver. However I'm having some difficulties getting the thing to work properly. Here's the Class in my code from the gist, largely unchanged class ClientThread(object): HOST = "127.0.0.1" PORT = int("3852") DIR = "/home/user/project/" STATIC_ROOT = DIR + '/clientFiles/static/' def mount_static(self, url, root): """ :param url: Relative url :param root: Path to static files root """ config = { 'tools.staticdir.on': True, 'tools.staticdir.dir': root, 'tools.expires.on': True, 'tools.expires.secs': 86400 } cherrypy.tree.mount(None, url, {'/': config}) def run(self): cherrypy.config.update({ 'server.socket_host': self.HOST, 'server.socket_port': self.PORT, 'engine.autoreload_on': False, 'log.screen': True }) self.mount_static(settings.STATIC_URL, self.STATIC_ROOT) cherrypy.tree.graft(WSGIHandler()) cherrypy.engine.start() print("[Info]: Client started. Use http://{0}:{1} to access the WebApp.".format(self.HOST,self.PORT)) cherrypy.engine.block() def init(self): print("[Info]: Starting Client WebApp...") cThread = Thread(target=self.run) cThread.start() This entire class is initiated via ClientThread().init() The first few lines of the gist at the top of my app (in order): import os from threading import Timer os.environ["DJANGO_SETTINGS_MODULE"] = "clientFiles.settings" import django django.setup() import cherrypy from django.conf import settings from django.core.handlers.wsgi import WSGIHandler My project is laid out like this: . ├── clientFiles │ ├── clientFiles │ │ ├── asgi.py │ │ ├── __init__.py │ │ … -
designing an api to send same response code with different meaning
What is the proper way to design an API response that could have the same response status code but with a different meaning for the fronted to display? Here is my example: On our frontend, the user can submit an address and our backend validates the submitted address. It checks if the address is real. The response could be that the address does not exist, or that more information about the address is required to find it. In both scenarios the API returns 400. We want the frontend to be able to distinguish between the 2 because the type of alert we show the user changes color based on the bad request type. This is how we are currently achieving it: {"message": "Missing field in api", "type": 1}, 400 {"message": "123 Apple Wood Drive.", "type": 2}, 400 If the frontend gets the type 1, the color of the alert is red, while 2 it is orange. How can we improve this approach so that we arent instructing the client how to display? -
Updating the quantity of items in a shopping Cart not working properly
I am working on a Django E-commerce Project, and I have been following a tutorial and afterwards I decided to redo it on my own without the tutorial but I am stuck in a small issue which I don't understand the logic behind it. When a user adds an Item to Cart I want it to reflect on the no. of items that are showing on the navbar cart icon, but I am getting Invalid filter: 'cart_item_count' Here is my Item model.py class Item(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) The application name is store, so here is what I have been done in the tutorial Added a new folder in the app with the name of templatetags and inside the template tags folder created file called cart_template_tags and here is what is inside it: from django import template from store.models import Order register = template.Library() @register.filter def cart_item_count(user): if user.is_authenticated: qs = Order.objects.filter(user=user, ordered=False) if qs.exists(): return qs[0].items.count() return 0 My question is how do I fix this error and I want to understand behind the logic of having … -
After adding custom columns in list_display, the background page display the columns, but the values of the columns is null, why is it happen?
the coding of adminx.py is below: class ProdAdmin(object): list_display = ['id','name','cats','aa'] def aa(self, obj): print("This is a demo...") return 'hello world' aa.short_description = 'aaaaa' xadmin.site.register(models.Prod, ProdAdmin) The versions is Django3.1.3-xadmin2.0.1. enter image description here -
Django - How to gruouping colomn datatble in django?
I havescript for my datatable. So, I store my atribut from API and I need to grouping column into one coloumn. Can django di that ? As long I know, that could but in JQuery, but it's impossible to bring my datatable to JQuery bcs so many atributes. Here my code : ['No. Telp <br/>Nasabah 1','notelp1_debitur',''], ['No. Telp <br/>Pasangan 2','notelp2_pasangan',''], ['No. Telp <br/>Pasangan 1','notelp1_pasangan',''], ['No. Telp <br/>Nasabah 2','notelp2_debitur',''], And i want to grouping like this : Grouping Atributes Thanks before. -
Handling multiple forms of different form tags in a function view in Django
HTML: <form method="POST" enctype="multipart/form-data" id="p_formUpload"> {% csrf_token %} <fieldset class="form-group"> <p> { p_form|crispy }} </p> </fieldset> </form> <form method="POST" enctype="multipart/form-data" id="c_formUpload"> {% csrf_token %} <fieldset class="form-group"> <p> {{ c_form|crispy }} </p> </fieldset> </form> views.py: def profile(request): p_photos = ProfilePicture.objects.all() c_photos = CoverPicture.objects.all() if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profilepicture) c_form = CoverUpdateForm(request.POST, request.FILES, instance=request.user.coverpicture) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been successfully updated!') return redirect('profile') if c_form.is_valid(): c_form.save() messages.success(request, f'Your account has been successfully updated!') return redirect('profile') else: p_form = ProfileUpdateForm(instance=request.user.profilepicture) c_form = CoverUpdateForm(instance=request.user.coverpicture) context={ 'p_form' : p_form, 'c_form' : c_form, 'p_photos': p_photos, 'c_photos': c_photos, } return render(request, 'user/profile.html',context) I am trying to have both the form in same page but in different form tag. But my first form(p_form) is submitting data but second form(c_form) is not working. My problem looks like in the views.py. I tried to find many solutions bit could'nt find it. I have multiple submit buttons through javascript and have two forms in the same page in different tags. -
How do I make my whitenoise static files show up?
Many solutions to this already on SO, but each one is different, and none work for me. I uploaded my Django/Whitenoise website to Heroku, and the static files stopped working, as usual. Collectstatic worked and saved them to /staticfiles, but the logo and few images I need won't show up on the website. Does anyone have a cure for this strain of the "Universal but poorly documented Django staticfiles error"? Filemap: sfl_website --website(app) ----website/static(contains my static files) --staticfiles(where collectstatic sends them) settings.py STATIC_URL = '/staticfiles/' STATIC_ROOT = '/Users/Lewis/Documents/sfl_website/staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' template code {% load static %} src="{% static "website/images/logo" %}" The logs say: "Not found: static/website/images/logo". Why is it looking there? Where does my code tell it to look? -
Django How do I edit posts?
I use to code with flash and recently change to Django. I just start Django and having trouble with editing post. This is the code below. When I edit the post and press submit, it redirect to the post detail page but the post isn't changed. post_form.html {% extends 'blog/base.html' %} {% block content %} <form action="/blog/{{ blog_post.pk }}/update", method="POST"> {% csrf_token %} <input type='text' name='title' value='{{ blog_post.title }}'/> <input type='text' class='textinput' name='content' value='{{ blog_post.content }}'/> <input type="submit" value="Submit"/> </form> {% endblock %} urls.py urlpatterns = [ path('admin/', admin.site.urls), path('blog/', index), path('blog/<pk>', post_detail), path('blog/<pk>/edit', postEdit), path('blog/<pk>/update', postUpdate) ] veiws.py def postEdit(request, pk): blog_post = Post.objects.get(id=pk) return render(request, 'blog/post_form.html', {'blog_post':blog_post}) def postUpdate(request, pk): if request.method == 'POST': blog_post = Post.objects.get(id=pk) blog_post.title = request.POST.get('title') blog_post.content = request.POST.get('content') blog_post.save return redirect(f'/blog/{pk}') What did I do wrong? -
How to get user ID/name as variable in django-allauth
I'm trying to build a simple django API that uses django-allauth's Discord OAuth2 to log in. To generate API tokens, however, I would like to have the user's ID or username. Allauth provides support to load the username/id in HTML ({% user_display user %} ), but I can't find anything to get it from a variable to store in a database. How can I get the ID of the user without using HTML?? -
Django same set of permissions for different models
So I've got two models structed like: class DataSheetsCluster(models.Model): """ Represents a group of datasheets made by the owner. Has it's own icon, name and description. A parent can only have one owner at a time. """ class Meta: permissions = [ ('READ_DATA', 'can read cluster data'), ('WRITE_DATA', 'can write to cluster'), ('MANAGE_CLUSTER', 'can manage cluster'), ('MANAGE_FIELD_DATA', "can manage cluster's field data"), ('MANAGE_DATASHEETS', "can manage cluster's datasheets"), ('MANAGE_ROLES', "can manage cluster's roles"), ('MANAGE_FIELDS', "can manage cluster's fields") ] objects = models.Manager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.CharField(max_length=50) description = models.CharField(max_length=1024, db_index=True) members = models.ManyToManyField('api_backend.Member') roles = models.ManyToManyField('api_backend.Role') datasheets = models.ManyToManyField(DataSheet) total_size_limit = models.FloatField(null=True, blank=True, db_index=True) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [name] class DataSheet(models.Model): """ Represents a single dataSheet. dataSheets have their own model at the core. Model data is added to the dataSheets in the form of separate records. """ class Meta: permissions = [ ('READ_DATA', 'can read datasheet data'), ('WRITE_DATA', 'can write to datasheet'), ('MANAGE_FIELD_DATA', "can manage datasheet's field data"), ('MANAGE_ROLES', "can manage datasheet's roles"), ('MANAGE_FIELDS', "can manage datasheet's fields") ] objects = models.Manager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.CharField(max_length=75, db_index=True) description = models.CharField(max_length=1024, db_index=True) owner = models.ForeignKey('api_backend.Member', on_delete=models.CASCADE, db_index=True) fields … -
Single login seesion for django application
I have Web application with VUE as frontend stack and Django DRF as backend stack I want to enable the feature that if someone is login from one system he/she can't login from other system unless and until logout from previous session is there any proper mechanism to do so -
Running django developing server in a docker container
So I'm trying to run Django developing server on a container but I can't access it through my browser. I have 2 containers using the same docker network, one with postgress and the other is Django. I manage to ping both containers and successfully connect 2 of them together and run ./manage.py runserver ok but can't curl or open it in a browser Here is my Django docker file FROM alpine:latest COPY ./requirements.txt . ADD ./parking/ /parking RUN apk add --no-cache --virtual .build-deps python3-dev gcc py3-pip postgresql-dev py3-virtualenv musl-dev libc-dev linux-headers RUN virtualenv /.env RUN /.env/bin/pip install -r /requirements.txt WORKDIR /parking EXPOSE 8000 5432 The postgres container I pulled it from docker hub I ran django with docker run --name=django --network=app -p 127.4.3.1:6969:8000 -it dev/django:1.0 I ran postgres with docker run --name=some-postgres --network=app -p 127.2.2.2:6969:5432 -e POSTGRES_PASSWORD=123 -e POSTGRES_DB=parking postgres Any help would be great. Thank you -
Ref doesn't work correctly with my settings
I'm learning to make some chat website, and i cannot quite get how to use urls correctly. The problem is that when I get to "http://127.0.0.1:8000/chat", links into the header became like "http://127.0.0.1:8000/chat/main" instead of "http://127.0.0.1:8000/main" project urls: from django.contrib import admin from django.urls import path from django.urls import include, path from chat import views as chat_views from mainapp import views as mainapp_views urlpatterns = [ path('admin/', admin.site.urls), path('', mainapp_views.index), path('chat/', include('chat.urls')), ] chat app urls: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] chat app views: from django.shortcuts import render def index(request): return render(request, 'chat/chatindex.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name }) I'm pretty sure that the problem is about "path('<str:room_name>/', views.room, name='room')", but i can't understand how to fix it and save opportunity to enter rooms with chat-page. Thanks a lot! -
Django - ManyToMany - how to filter on parent's ManyToMany object
I have problems with writing a filter on my queryset models: class Order(models.Model): items = models.ManyToManyField(OrderLine) store = models.ForeignKey(Store, blank=True, null=True, on_delete=models.SET_NULL) class OrderLine(models.Model): orderItemId = models.IntegerField(blank=False, null=False, unique=True) quantity = models.IntegerField(blank=True, null=True) class Store(models.Model): storeName = models.CharField(max_length=200, blank=True, null=True) access_from_account = models.ManyToManyField(EDUser, blank=True) I have my queryset of EDUser "accounts" Now I want to select OrderLines that belongs to Order that are from Store that is visible by an account in access_from _account. So, for example: store_name_1 has access_from_account user_1, user_2 store_name_2 has access_from_account user_1 There at Orders that belongs to store_name_1. Those Orders have many OrderLines. I would like to select order_lines that should be accessible by user_1. Can I do it by: acounts is queryset of ['user_1'] lines = OrderLine.objects.filter(order__store__access_from_account__in=accounts)? I tried that, but I get some strange values... Any suggestion of how to do it properly? I would like to avoid making lists and iterate over them. Thanks in advance :) -
HTML required attribute in Django form
I have an HTML form which I'm using with a required attribute and I'm using Django to capture the user's input NOT Django generated form but a custom HTML. However, the required attribute isn't working! Index.Html <form id="contactForm" name="sentMessage" novalidate="novalidate" method="POST"> {% csrf_token%} <div class="row align-items-stretch mb-5"> <div class="col-md-6"> <div class="form-group"> <input class="form-control" id="name" type="text" placeholder="Your Name *" required="required" data-validation-required-message="Please enter your name." name="name"/> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input class="form-control" id="email" type="email" placeholder="Your Email *" required="required" data-validation-required-message="Please enter your email address." name="from_email" /> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group form-group-textarea mb-md-0"> <textarea class="form-control" id="message" placeholder="Your Message *" required="required" data-validation-required-message="Please enter a message." name="message"></textarea> <p class="help-block text-danger"></p> </div> </div> </div> <div class="text-center"> <div id="success"></div> <button class="btn btn-primary btn-xl text-uppercase" id="sendMessageButton" type="submit">Send Message</button> </div> </form> Views.py def index (request) : form = contact_form(request.POST or None) if form.is_valid(): form.name = request.POST.get("name") form.from_email = request.POST.get("from_email") form.message = request.POST.get("message") try: send_mail(form.name, form.message, form.from_email, ['test@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "index.html", {}) -
Blank React.JS results
Using URL: http://localhost:3000/ After running the cmd: npm start. (In a frontend terminal) And running the cmd: python manage.py runserver (In a backend terminal) This is the app.js import React, { Component } from 'react'; class App extends Component { state = { todos: [] }; async componentDidMount() { try { const res = await fetch('http://127.0.0.1:8000/api/'); const todos = await res.json(); this.setState({ todos }); } catch (e) { console.log(e); } } render() { return ( <div> {this.state.todos.map(item => ( <div key={item.id}> <h1>{item.title}</h1> <span>{item.description}</span> </div> ))} </div> ); } } export default App; settings.py CORS_ORIGIN_WHITELIST = [ 'http://www.localhost:3000', ] #API PERMISSIONS REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } INSTALLED_APPS = [ 'corsheaders', 'rest_framework', 'crispy_forms', 'todo.apps.TodoConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I am attempting to create todos based on this tutorial: https://wsvincent.com/django-rest-framework-react-tutorial/ There should currently be three todos displayed. (I've confirmed these three todos are in the database and under the admin screen). -
Problems with Django Crontab
I am running my Django project with pipenv, when the cronjob runs, the following text is the log output Failed to complete cronjob at ('*/1 * * * *', 'almacen.cron.cron_job', '>> ~/file.log') Traceback (most recent call last): File "/home/emilio/.local/share/virtualenvs/env1-X6Hvyawx/lib/python3.8/site-packages/django_crontab/crontab.py", line 145, in run_job func(*job_args, **job_kwargs) File "/home/emilio/proyectos/env1/hogar/almacen/cron.py", line 9, in cron_job html_string = render_to_string('pdf_template/marca.html', {'marca': marca}) File "/home/emilio/.local/share/virtualenvs/env1-X6Hvyawx/lib/python3.8/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/home/emilio/.local/share/virtualenvs/env1-X6Hvyawx/lib/python3.8/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: pdf_template/marca.html and nothing is happen, but, when I do the job manually, the log output is the same but, the task run without problem. -
Merge these two json objects based on a specific key inside of them in python? (Plz view example)
Is there a way to match these json objects based on the "matchID" and make them into one object with merged data? I basically want these to make a table that contains the stat of each player participating on the same match id. Input: data_list = [ { "kloweritotv#3560772":[ { "kd":2, "kills":4, "teamPlacement":11, "damageDone":1218, "matchID":"4196836767861917674" }, { "kd":2, "kills":6, "teamPlacement":3, "damageDone":2388, "matchID":"12887455297423544724" }, { "kd":1, "kills":4, "teamPlacement":14, "damageDone":1828, "matchID":"11929202821836542057" }, ] }, { "Stylnox07":[ { "kd":4.5, "kills":9, "teamPlacement":3, "damageDone":2549, "matchID":"12887455297423544724" }, { "kd":1.5, "kills":3, "teamPlacement":14, "damageDone":1008, "matchID":"11929202821836542057" } } ] Desired output (Pseudo code): [ { "matchid":12887455297423544724, "kloweritotv":{ "kd":2, "kills":6, "teamPlacement":3, "damageDone":2388, "matchID":"12887455297423544724" }, "Stylnox07":{ "kd":4.5, "kills":9, "teamPlacement":3, "damageDone":2549, "matchID":"12887455297423544724" } }, { "matchid":11929202821836542057, "kloweritotv":{ "kd":1, "kills":4, "teamPlacement":14, "damageDone":1828, "matchID":"11929202821836542057" }, "Stylnox07":{ "kd":1.5, "kills":3, "teamPlacement":14, "damageDone":1008, "matchID":"11929202821836542057" } } ] Any information would definitely be very helpful! TIA! -
filter view from many-to-many and one-to-many
So, I have three models profile, topic and major models profile and major has one-to-many relationship, major can have multiple profile and profile can only have one major profile and topic has many-to-many relationship My Goal is I want topic can only made and see by profile from the same major. example only profile with Math major can create Math topic and only profile from Math Major can see it models.py class Major(models.Model): name = models.CharField(_("Name"), max_length=400) is_published = models.BooleanField(_("Users can see it and answer it"), default=True) publish_date = models.DateField(_("Publication date"), blank=True, null=False, default=now) expire_date = models.DateField(_("Expiration date"), blank=True, null=False, default=in_duration_day) class Profile(AbstractUser): email = models.EmailField(_("Email Address"), max_length=254, unique=True) first_name = models.CharField(_("First Name"), max_length=254) last_name = models.CharField(_("Last Name"), max_length=254) major = models.ForeignKey(Major, verbose_name=_("Major Name"), on_delete=models.SET_NULL, null=True) topics = models.ManyToManyField(Topic) class Prodi(models.Model): major_ode = models.CharField(_("Major Code"), max_length=5, unique=True,) name = models.CharField(_("Major Name"), max_length=250) status = models.BooleanField(_("Major Status"), default=True, help_text="check the box to make Major active") views.py from datetime import date from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView from Lesson.models import Major, Topic, Profile class MajorList(LoginRequiredMixin, TemplateView): template_name = "topic/list.html" def get_context_data(self, prodi_id, **kwargs): context = super(MajorList, self).get_context_data(**kwargs) topics = Topic.objects.filter( is_published=True, expire_date__gte=date.today(), publish_date__lte=date.today(), ).order_by("publish_date") context["topics"] = topics return context -
How can I let the user of an Django Admin Page control which list_display fields are visible?
I have an ModelAdmin with a set of fields in list_display. I want the user to be able to click a checkbox in order to add or remove these fields. Is there a straightforward way of doing this? I've looked into Widgets but I'm not sure how they would change the list_display of a ModelAdmin -
django-filter not filtering the query
I applied django-filter library in my project if it's not filtering the items. if i visit the url http://127.0.0.1:8000/products/?q=&category=electronics it should gives the only electronics products but its giving the all available products. What i am doing wrong? class ProductFilter(FilterSet): # by using django-filters title = CharFilter(field_name='title', lookup_expr='icontains', distinct=True) category = CharFilter(field_name='categories__title', lookup_expr='icontains', distinct=True) category_id = CharFilter(field_name='categories__id', lookup_expr='icontains', distinct=True) min_price = NumberFilter(field_name='price', lookup_expr='gte', distinct=True) max_price = NumberFilter(field_name='price', lookup_expr='lte', distinct=True) class Meta: model = Product fields = ['category', 'title', 'description', 'min_price', 'max_price'] class FilterMixin(object): filter_class = ProductFilter search_ordering_param = 'ordering' def get_queryset(self, *args, **kwargs): try: qs = super(FilterMixin, self).get_queryset(*args, **kwargs) return qs except: raise ImproperlyConfigured("You must have a queryset in order to use the FilterMixin") def get_context_data(self, *args, **kwargs): context = super(FilterMixin, self).get_context_data(*args, **kwargs) qs = self.get_queryset() ordering = self.request.GET.get(self.search_ordering_param) if ordering: qs = qs.order_by(ordering) filter_class = self.filter_class print(filter_class) if filter_class: f = filter_class(self.request.GET, queryset=qs) context['object_list'] = f return context class ProductListView(FilterMixin, ListView): queryset = Product.objects.all() filter_class = ProductFilter def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) context['filter_form'] = ProductFilterForm(data=self.request.GET or None) return context -
Seperate folder for images
I have an API that delivers images and puts them in a folder. I want to make that folder accessible via Django. folder structure: - theProject settings.py urls.py . . . - theApp - apiimagesfolder views.py forms.py urls.py . . . I tried adding the apiimages folder to my static dirs: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "theProject", "static"), os.path.join(BASE_DIR, "theApp", "apiimages"), ] and I tried accessing an image in apiimages on the debug server with 127.0.0.1:8000/imagename.bmp but failed. What would the correct path be? Is the path staying the same after deploying? -
How to post with references in Django Rest Framework
I have Comment model # models.py class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) more fields... .... # serializers.py class CommentSerializer(serializers.ModelSerializer): # id of comment id = serializers.CharField(read_only=True) user = myuserSerializer() class Meta: fields = ['id', 'user'] def create(self, validated_data): user_data = validated_data.pop('user') user = Card.objects.create(**validated_data) Comment.objects.create(user=user, **user_data) I want to make a comment, referencing the user # views.py class CommentViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = CommentSerializer But I have an exception, that the user has no comment