Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what should I learn to create an (image upload=>perform image recognition) webpage?
I understand a bit of programming with python, how make simple image recognition models that runs locally on my machine, I know how to use React.js, mongoDB and create some toy web apps. my question is, what do I need to learn to make a webpage that upload an image and do some analysis in python and send back the result? I hope my question is clear. Flask? Django? Learn to do analysis in Javascript? where should the images be stored? What tech allows me to make a python server that receive and image, do analysis, send back an image? Anyway that's my question, my apology if I sound ignorant to you. -
Django: the server responded with a status of 403 (Forbidden) (fix the error please)
I successfully registered from React app(front-end) and saved the key (Got from server) in local storage. here is my code: signupHandler=()=>{ fetch('http://127.0.0.1:8000/api/rest-auth/registration/', { method: 'POST', headers:{ 'content-type':'application/json', }, body:JSON.stringify({ 'username':this.state.username, 'email': this.state.email, 'password1': this.state.pass1, 'password2': this.state.pass2 }) }) .then((response)=>{ response.json().then((result)=>{ if (result.key !== undefined){ localStorage.setItem('login', JSON.stringify({login: true,token:result.key})) this.setState({registered: true}) } }) }) } I made a method , which will do this.setState({addedToCart: true}), if the result = 'response':'ok'. here is the method: addToCart=()=>{ var id = this.props.id let store = JSON.parse(localStorage.getItem('login')) console.log(store.token);//successfully print the key var url = 'http://127.0.0.1:8000/addToCart/'+id+'/' fetch(url,{ method:'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Token '+store.token } }).then(res=>res.json().then(result=>{ if(result.response === 'ok'){ this.props.dispatch({ type: 'itemInCart', }) this.setState({addedToCart: true}) } })) } and in Django(views.py): @api_view(['GET']) @permission_classes((IsAuthenticated,)) def addToCart(request, pk): product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(user=request.user) mycart.product.add(product) return Response({'response':'ok'}) but it shows >>>the server responded with a status of 403 (Forbidden) I know Django is saying I'm un-authenticated. but why i'm un-authenticated? (where i send the token/key to the server). so, How can I get the response:ok? how can i make me authenticated? -
Python, django: all objects in form works fine except only one
On website page user select 'flight_date', 'flight_number', 'suburb', 'no_of_passenger' on the form and hit summit button. after that, views.py calculate the price with those information and send them back to webiste page (html). all objects appear on webpage as User selected but only 'price' does not appear. 'price_cal()' works fine (I did test it - simple function). I don't know what the problem is... no error message come out. only price does not appear. it says "None" Here are the codes at views.py from django.shortcuts import render, redirect from .area import suburbs def price_detail(request): if request.method == "POST": flight_date = request.POST.get('flight_date') flight_number = request.POST.get('flight_number') suburb = request.POST.get('suburb') no_of_passenger = request.POST.get('no_of_passenger') def price_cal(): if flight_number == 'Drop off To airport': return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) - 10 elif flight_number == 'Pickup from airport': return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) price_cal() price = price_cal() return render(request, 'basecamp/price_detail.html', {'flight_date': flight_date, 'flight_number': flight_number, 'suburb': suburb, 'no_of_passenger': no_of_passenger, 'price': price}, ) else: return render(request, 'basecamp/price_detail.html', {}) I am now struggling with this matter for several days... please help me or any hint, much appreciated. -
How to deploy Docker project(Django,nginx,gunicorn) to Production environment
I'm currently developing an application using Django, Nginx, Gunicorn, Postgresql, and Docker. I've created a simple project that just displays a welcome page of Django. I can check the display and operation in the local server(0.0.0.0/), but I cannot check the display and operation if I start the project in the production environment(remote server)()... How could I solve this problem? Directory structure docker_django ├─Dockerfile ├─docker-compose.yml ├─requirements.txt ├─entrypoint.sh ├─docker_django │ │─django_project │ │ ├─settings.py │ │ ├─urls.py │ │ ├─wsgi.py │ │ ├─asgi.py │ │ └─__init__.py │ └─manage.py ├─nginx │ ├─Dockerfile │ └─default.conf └─.env Here are the codes: Dockerfile FROM python:3 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./django_project /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] docker-compose.yml version: "3.7" services: db: image: postgres environment: - "POSTGRES_USER=postgres" - "POSTGRES_PASSWORD=postgres" django_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" depends_on: - db nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - django_gunicorn volumes: static: requirements.txt Django==3.0.8 gunicorn==20.0.4 psycopg2 entrypoint.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn django_project.wsgi:application --bind 0.0.0.0:8000 settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') ALLOWED_HOSTS = ['*'] ... … -
SQL join that happens in the view of Django Rest Framework
I just want to know what type of SQL join is happening in the following view. I read about types of SQL joins but I am not able to figure out what is happening here. class WishListItemsView(ListAPIView): permission_classes = [IsAuthenticated] serializer_class = WishListItemsCreateSerializer def get_queryset(self): user = self.request.user return WishListItems.objects.filter(owner=user) My models: class WishListItems(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE,blank=True) #wishlist = models.ForeignKey(WishList,on_delete=models.CASCADE, related_name='wishlistitems') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) wish_variants = models.ForeignKey(Variants,on_delete=models.CASCADE, related_name='wishitems') I can see it in Django debug toolbar, but it is authenticated so I cant see the quries. -
mw_instance = middleware(adapted_handler) TypeError: __init__() takes 1 positional argument but 2 were given
I have upgraded python and django version. resolved all the conflicts but unable to get the cause of this error. old -> python 3.5, django 1.8 upgraded -> python 3.9 django 3.2 Any Idea why this error is for? Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 138, in inner_run handler = self.get_handler(*args, **options) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/m.susmita/code/seldon-hercules/sp-hercules/opdashboard/wsgi.py", line 29, in <module> application = get_wsgi_application() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 127, in __init__ self.load_middleware() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/handlers/base.py", line 58, in load_middleware mw_instance = … -
Django REST authentication not working with React
actually I want: if a user is authenticated: then create/get the Cart with user, else: create/get the Cart with session key. But at first problem happened with authentication. At first I tried to register the user and saved the key(got from drf) in local storage. in Reactjs: signupHandler=()=>{ fetch('http://127.0.0.1:8000/api/rest-auth/registration/', { method: 'POST', headers:{ 'content-type':'application/json', }, body:JSON.stringify({ 'username':this.state.username, 'email': this.state.email, 'password1': this.state.pass1, 'password2': this.state.pass2 }) }) .then((response)=>{ response.json().then((result)=>{ if (result.key !== undefined){ localStorage.setItem('login', JSON.stringify({login: true,token:result.key})) this.setState({registered: true}) } }) }) } I think no problem here. if I console.log() the key , it prints the key successfully. now look at my views.py . I think the problem is here. @api_view(['GET']) #@permission_classes((IsAuthenticated,))<<< if i comment out this line, and try to call this function, it shows >>>Forbidden: /addToCart/21/ def addToCart(request, pk): print(request.user)#>>>AnonymousUser product = get_object_or_404(Product, pk=pk) if request.user.is_authenticated: print('authenticated')#>>> nothing prints mycart, __ = Cart.objects.get_or_create(user=request.user) mycart.product.add(product) else: print('session')#>>>session if not request.session.exists(request.session.session_key): request.session.create() mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'ok'}) now i made a button and if i click, this function call reactjs: addToCart=()=>{ var id = this.props.id let store = JSON.parse(localStorage.getItem('login')) console.log(store.token);//successfully print the key var url = 'http://127.0.0.1:8000/addToCart/'+id+'/' fetch(url,{ method:'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Token '+store.token } }).then(res=>res.json().then(result=>{ if(result.response === … -
How to subscribe to a model in django channels rest framework?
I'm trying to subscribe for changes in a model using Django Channels Rest Framework. I've been following the example at https://djangochannelsrestframework.readthedocs.io/en/latest/examples/model_observer.html and at latest following question: How to subscribe to all instances of a model in django channels rest framework?. However, I'm not receiving updates via WebSockets when the models are updated. I'm having consumser set as below: # consumers.py from djangochannelsrestframework.consumers import AsyncAPIConsumer from djangochannelsrestframework.observer import model_observer from .models import User, Comment class ModelConsumerObserver(AsyncAPIConsumer): async def accept(self, **kwargs): print("WebSocket Connect 1") await super().accept() print("WebSocket Connect 2") await self.model_change.subscribe() print("WebSocket Connect 3") @model_observer(Comment) async def model_change(self, message, **kwargs): print("Model Observer 1") await self.send_json(message) print("Model Observer 2") I'm trying to subscribe for Comment-model as in the example in documentation. However, I'm not receiving the updates on model. On my side there is currently no authentication, no exception on server. The local server console shows: System check identified no issues (0 silenced). June 06, 2021 - 10:11:10 Django version 3.2.3, using settings 'websocket.settings' Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. HTTP GET / 200 [0.01, 127.0.0.1:64527] WebSocket HANDSHAKING /ws/my-consumer/ [127.0.0.1:64528] WebSocket Connect 1 WebSocket CONNECT /ws/my-consumer/ [127.0.0.1:64528] WebSocket Connect 2 WebSocket Connect 3 I'm not sure, … -
Uncaught (in promise) SyntaxError: Unexpected end of JSON input for JSON data processing received form Django backend
I have used Django to develop a web app. When I tried to receive and process the JSON data sent from backend, error occurs: Uncaught (in promise) SyntaxError: Unexpected end of JSON input at Function.parse [as parseJSON] (<anonymous>) view.py: @csrf_exempt def content_checklist_name_url(request): msg = "Duplicate Entry. This Course Code already exists." json_data = {'msg': msg} return JsonResponse(json_data) Javascript: const response = await fetch({% url 'bms:content_checklist_name_url' %}); var msg_json = jQuery.parseJSON("{{json_data}}"); console.log(msg_json.toString()); if (msg_json === "Duplicate Entry. This Course Code already exists.") ... -
Django website can't find template in new project website
Hey I'm looking for some advice on my situation as I can't seem to figure this out. I'm trying to build a website with Django following along with the tutorial they have on the webpage and I got stuck at a step where I want to add a view to my web page. My folder structure is so fart like this: PersonalWebsite | |--PersonalWebsite | |--urls.py |--dashboard | |--urls.py |=-views.py |--templates |--dashboard | |--index.html In my PersonalWebsite/urls.py I have : urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), path('resume/', include('resume.urls')), ] In my dashboard/urls.py I have: urlpatterns = [ path('', views.index, name='index'), ] And in my dashboard/view.py I have: def index(request): return render(request, 'dashboard/index.html') Then I have just some html in the index.html. I'm trying to basically have the dashboard app as the landing page of the website and from there I want to redirect to other apps like portofolio, articles, etc. My issue is that now I get a TemplateNotFound error when the website tries to access dashboard/index.html at localhost:8000/ address. I haven't changed anything in the settings files, it is a standard project. Any idea's why it can't find the index.html? -
FileNotFoundError in Docker django project even though the file is present
I had created a django project and it was working correctly. Then I dockerised the project. Now I an getting this file not found error even though the file is present at the address. It is a normal text file which the views.py file needs to access. -
How to access fields of a Model from ForeignKey for Validation?
Basic idea is Task --> Submission means each submission is associated with a Task with ForeignKey. This is my models.py file from django.db import models from django.core.validators import FileExtensionValidator class Task(models.Model): task = models.CharField(max_length=20) min_marks = models.IntegerField(default=0) max_marks = models.IntegerField(default=100) late_submission_date = models.DateField() late_submission_panalty = models.IntegerField() file_type = models.CharField(max_length=10) file_size = models.IntegerField("File Size in mb") created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Task:{self.task}" class Submission(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) team_id = models.IntegerField(unique=True) file = models.FileField("File", validators=[FileExtensionValidator(allowed_extensions=['zip'])]) # see here created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.team_id}@{self.created_date.strftime('%H:%M_%d_%m_%Y')}" Inside Submissions --> file i want to access file_type of task so i could validate submission file extension. I am really new to Django so any help would be nice. -
IntegrityError at /users/signup NOT NULL constraint failed: users_user.username
What I was doing I was making the signup form with using ModelForm in forms.py and FormView in views.py. I am making users to use their email as their username when they are logging in so that they can easily set new passwords if they lost. Error Image It just threw IntegrityError in my console. IntegrityError at / NOT NULL contraint failed What I have tried to solve issue I deleted all the migration files and db file so that there won't be any duplicated users in my database. And then I created new superuser and then created new user. I got rid of email field in fields in Meta class and then created cleaning method of email (def clean_email(self):). However this solution didn't work obviously because it will delete the email field in my signup form. Source code Below are my all source codes that might be related to this topic. templates/users/signup.html {% block content %} <section id="signup"> <form method="POST", action="{% url 'users:signup' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Signup</button> </form> </section> {% endblock content %} users/forms.py class SignupForm(forms.ModelForm): class Meta: model = models.User fields = ['first_name', 'last_name', 'email'] password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput, label='Confirm Password') … -
Daphne showing blank screen on browser with Django ASGI, unable to load static files. Why?
When I run the server using :- python manage.py runserver everything is working correctly, but for the hosting purpose I have to run it with daphne which is not working correctly. Its not giving any error but showing blank screen because it is not loading static files even though I have specified STATIC_URL and STATICFILES_DIRS in settings. asgi.py settings.py command view browser showing blank screen Help me fixing it, its been so long I am searching for the solution but unable to figure out any. if anything else required in question comment me, I will re-edit for the same. -
How to create a url for each object in django rest?
I have a Jason file. I want to create a url for each object with django rest. How do I do that? example json: [{"name":"John","age":30,},{"name":"ali","age":44,},] -
How to fix errors when trying to run a server using django?
I'm trying to learn how to use Django and I have created a folder called "lecture3" and when I type in lecture3 % python manage.py runserver, I get the error lecture3 : The term 'lecture3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 lecture3 % python manage.py runserver ~~ CategoryInfo : ObjectNotFound: (lecture3:St ring) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Django: How to call the same model class inside it s self?
I have a function make_fields_permissions that I need to use it inside the model calss in order to parse the fields and to make permissions for each field like [('can_view_first_name_field','can view first name'),...] goal I need to call and override Person class and inside it self I tried def __init__(self,*args, **kwargs): self.Meta.permissions = make_fields_permissions(self.model) super().__init__(*args, **kwargs) from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __init__(self, *args, **kwargs): # kwargs['user']['permissions'] = make_fields_permissions(Profile) # x = self['age'] super().__init__(*args, **kwargs) class Meta: permissions = make_fields_permissions(Person) #< I can't use the same model inside meta -
How can I use prefetch_related to get the name field of objects with ForeignKey relationships?
I have two models: class ModelA(models.Model): name = models.CharField() class ModelB(models.Model): A = models.ForeignKey(ModelA, related_name="links") name = models.CharField() In my template I would like to print out the 'name' of each object associated to each ModelA object via ForeignKey, I am doing so like this {% for a in modela_list %} <p>{{ a.name }} </p> {% for link in modela_list.links.all % } <p>Link name: {{ link.name }} </p> {% endfor %} {% endfor %} While this does work, from what I understand it is incredibly inefficient, and very slow. How can I use prefetch_related to make this better? -
TypeError: contact() got an unexpected keyword argument 'name' -why I get such error in django?
Hello I am learning django framework for web development. After makemigrations and migrate command I did runserver command hence I got the following error. File "D:\learn django\ashokWeb\portfolio\home\views.py", line 21, in contact ins=contact(name=name,email=email,phone=phone,desc=desc) TypeError: contact() got an unexpected keyword argument 'name' [06/Jun/2021 15:08:25] "POST /contact HTTP/1.1" 500 64573 from django.shortcuts import render from home.models import contact # Create your views here. def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def projects(request): return render(request, 'projects.html') def contact(request): if request.method=="POST": name=request.POST['name'] email=request.POST['email'] phone=request.POST['phone'] desc=request.POST['desc'] #print(name,email,phone,desc) ins=contact(name=name,email=email,phone=phone,desc=desc) ins.save() print('the deta has been written to the db') return render(request, 'contact.html') '''models.py file''' from django.db import models # Create your models here. class contact(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=50, null='True') phone = models.CharField(max_length=10) desc = models.TextField() -
Django looping through 10 items of an array each time a button is pressed
I would like a page to start by showing 10 items, once a button is clicked, the next 10 items are shown and so on. Pressing the back button will show the previous 10 items. How would I got about doing this? The items are in an array. Each item is a queryset. Current code: {% for item in items %} #format item to be shown {% endfor %} -
Writing DRF reusable APIs
I am trying to create a PIP package for a set of reusable APIs. I have already implemented those API in a project and are working perfectly fine. I started looking for the way to package these API so that it can be integrated with any other project and that is how I learned about setuptools. To gain a little hands on experience with setuptools I simply created a PIP package for a helloworld() program. Now, I have started creating the package for the API I have in my DRF app. I created an empty directory and moved all the modules of this DRF app into that directory. The setup.py file is well configured to install the dependencies which are required by these modules. However, now I want to start this application and see if it is working or not. So when I run python manage.py runserver it didn't work because of an obvious reason - No such file or directory. Moreover, there are certain configuration which are required for this package to work and in my previous project it is defined in settings.py file. setup.py import os from setuptools import setup, find_packages # allow setup.py to be run from … -
how to return to a precise position in a django template
I have an html table where I can modify the cell fields, since the table is a bit long; when i commit the change i want to go back to the last modified line. i am using django. is there a solution for that. ps: I am using this code for page loading: return render(request, "./ui-panneaux-gerer-prix-form.html", context) and this is the table row : <td> <div class="row mb-5 mb-lg-5"> <div class="col-lg-3 col-sm-6 mt-4 mt-md-0"> <form action="gerer-prix-operation" method="POST"> {% csrf_token %} <fieldset> <legend class="h6">Matiere de fonds</legend> {% for objet_list in produit_list_fond %} <div class="form-check"> <input class="form-check-input" type="radio" name="matiereFond" id="exampleRadios2" value="{{objet_list.id}}" > <label class="form-check-label" for="exampleRadios2"> {{objet_list.nom}} </label> </div> {% endfor %} </div> <div class="col-lg-3 col-sm-6 mt-4 mt-md-0"> <legend class="h6">Champs</legend> {% for objet_list in produit_list_contour %} <div class="form-check"> <input class="form-check-input" type="radio" name="matiereContour" id="exampleRadios2" value="{{objet_list.id}}" > <label class="form-check-label" for="exampleRadios2"> {{objet_list.nom}} </label> </div> {% endfor %} </div> <div class="col-lg-3 col-sm-6 mt-4 mt-md-0"> <legend class="h6">Autre</legend> {% for objet_list in produit_list_autre %} <div class="form-check"> <input class="form-check-input" type="radio" name="autreMatiere" id="exampleRadios2" value="{{objet_list.id}}" > <label class="form-check-label" for="exampleRadios2"> {{objet_list.nom}} </label> </div> {% endfor %} <div class="form-check"> <input type="hidden" name="id" value="{{panneaux.id}}"> </div> <div class="form-check"> <input type="hidden" name="idObjetPanneaux" value="{{objet_panneaux.id}}"> </div> <div id="test"> </div> <button id="gerer_surface" class="btn btn-sm btn-danger" type="submit">Valider</button> <!-- End of Radio … -
Filtering Django admin site by user group
i want to filter the objects displayed on the admin site by using user groups. Each user is assigned to one or more groups which represent different categories of articles. Each article falls into one or more categories (the names of the groups and categories are identical). On the admin site for the Article object, users shall only see articles from categories of which they are a member. I found a basic approach by overriding get_queryset within ModelAdmin and retrieving a list with the user's group names. But how can i reference the ArticleCategory model within ArticleAdmin to do the comparison with the group names? models.py class Article(models.Model): title = models.CharField(max_length=200, default=None) class Category(models.Model): name = models.CharField(max_length=50, default=None) class ArticleCategory(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, default=None) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None) admin.py class ArticleAdmin(admin.ModelAdmin): model = Article def get_queryset(self, request): if request.user.is_superuser: queryset = Article.objects.all() else: try: l = request.user.groups.values_list('name',flat = True) l_as_list = list(l) queryset = Article.objects.filter(??? in l_as_list) except: queryset = Article.objects.none() return queryset admin.site.register(Article, ArticleAdmin) -
Is there a way to make clickable images and select an that particular one?
I am working on a Graphical password authentication system using Django. During the registration process, I want to display few images , out of which the user can select any one. i want the selected image to be highlighted and also on the click of submit button, i want that image to be stored in the database. I had tried adding images in a button, but it did not work out. This is what i did <button name="b3" style="border:0px"><img src="/static/r9.jpg" class="d-block w-100" alt="..."></button> Then I tried a different approach and used use-maps in HTML. But apparently that also seems to not work. <img src="/static/r1.jpg" class="d-block w-100" name="img" alt="..." usemap="#imagemap"> the use map is defined as follows: <map name="imagemap"> <area shape="rect" coords="34,44,270,350" href=""> </map> Can you please guide me what is the way to go forward with it. Thanks in advance. -
I'm trying to link the post created by the specific user account in Django
models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200,null=True) ## phone = models.IntegerField(null=True) email = models.EmailField(max_length=250) profile_pic = models.ImageField(default='default_pic.png',null=True,blank=True) date_created = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class Task(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) title = models.CharField(max_length=200) description = models.TextField(null=True,blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete'] views.py @login_required(login_url='login') def taskCreate(request): if request.method == 'POST': form = TaskForm(request.POST or None) if form.is_valid(): form.instance.customer = request.user form.save() return redirect('tasks') else: form = TaskForm() context = {'form':form} return render(request,'todo_list/task_create.html',context) Error: ValueError at /create_task/ Cannot assign "<SimpleLazyObject: <User: Dominic>>": "Task.customer" must be a "Customer" instance. I am trying to link the username in the user account to be shown on the model Task.customer that represents the post is created by that user. May I ask any methods could be done in order to specify the customer in the model Task? Also I do not understand the error message in detail because my admin panel already has the current username in the Customer model. However if I used request.user.customer the username does not show up instead returning None so how to solve this issue?