Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django file upload in REST-framework : TypeError: a bytes-like object is required, not 'TemporaryUploadedFile'
I want to make a post create view. There are various functions to write an article, and there is a file upload function in particular. So, I use Multipartparser and override create function in serializer. like below: create instance first. save the file on the created instance. but when I save, the error occur: TypeError: a bytes-like object is required, not 'TemporaryUploadedFile' but don't know how to convert 'TemporaryUploadedFile' to 'a bytes-like object'. <api_view> class PostCreate(generics.CreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer # parser_classes = (FileUploadParser,) # parser_classes = (FormParser, MultiPartParser) parser_classes = (MultiPartParser,) # def put(self, request, format = None): # post_files = request.data['post_files'] def post(self, request, *args, **kwargs): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PostSerializer(serializers.ModelSerializer): post_files = serializers.FileField(required=False) def create(self, request): print("@@@@@request") print(request) post_files = request.pop("post_files") print("@@@ post_files.path : " + post_files.temporary_file_path()) print("@@@ post_files.name : " + str(post_files)) instance = Post.objects.create(**request) # files = open(post_files.temporary_file_path(), "wb+") # for chunk in post_files.chunks(): # files.write(chunk) # files.close() instance.post_files.save(str(post_files), ContentFile(files), save=True) return instance -
Custom 500 error page for only one template
Hi i cant figure out how i can create a custom 500 page but only for a single view, i basically want to redirect to another template when i get an 404 error by not passing a positional argument. i currently made an .html custom page, but its works for any page. im triying to do something like this: def handler_no_board(request,exception): board= request.GET["board_id"] if board == null return render(request,'board-not-found.html') -
Django Channels error appears in separate Django project (broken pipe error)
I'm relatively new to ASGI and Django Channels, so this is probably a very basic question. I got ASGI running thanks to Django Channels in one of my Django projects and it works fine. I then want to work on my old project, which doesn't yet use ASGI. I kill the debug server running locally on 127.0.0.1, switch environments (in an entirely new shell window) and start the debug server running for the old project: (server) me@laptop server % ./manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 12, 2021 - 11:23:40 Django version 3.2, using settings 'oldproj.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: /ws/chats/1056/ [12/Jun/2021 11:23:46] "GET /ws/chats/1056/ HTTP/1.1" 404 6103 [12/Jun/2021 11:23:46,327] - Broken pipe from ('127.0.0.1', 58901) Not Found: /ws/chats/1056/ [12/Jun/2021 11:37:43] "GET /ws/chats/1056/ HTTP/1.1" 404 6103 [12/Jun/2021 11:37:43,293] - Broken pipe from ('127.0.0.1', 59096) Not Found: /ws/chats/1056/ [12/Jun/2021 11:37:43] "GET /ws/chats/1056/ HTTP/1.1" 404 6103 [12/Jun/2021 11:37:43,293] - Broken pipe from ('127.0.0.1', 59096) These error messages repeat every 30 seconds or so. I suspect there's a process still running in support of the new, ASGI-equipped project but I don't know what … -
Can I add any kinda condition to the model.py file in django?
Can I add any kinda condition to this model? If it's possible, how can I do that? class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) is_bestseller = models.BooleanField(default=False) slug = models.SlugField(default="", null=False, db_index=True) def __str__(self): return f"{self.title} ({self.rating})" -
Django: How to read an image sent using Dio from flutter
I'm a newbie to Flutter and trying to build a Flutter App. I want to upload an image from android device to django, process it and send the results back to flutter in a json format without saving the image anywhere. But I'm facing difficulty in reading image in django. However, the image is sent successfully from flutter. Here is my flutter code for sending an image using Dio : Future<void> _clearImage() async { try { String filename = imageFile!.path.split('/').last; FormData formData = FormData.fromMap({ "image": await MultipartFile.fromFile(imageFile!.path, filename: filename, contentType: MediaType('image', 'jpg')), "type": "image/png" }); Response response = await dio.post('http://192.168.43.63:8000/scan/', data: formData, options: Options( followRedirects: false, // will not throw errors validateStatus: (status) => true, headers: { "accept": "*/*", "Content-Type": "multipart/form-data", })); print(response); } catch (e) { print(e); } setState(() {}); } } Here is my code for django: file = request.FILES['image'] print(file) img = cv2.imread(file.read()) print(img) I'm getting the following error: img = cv2.imread(file.read()) TypeError: Can't convert object of type 'bytes' to 'str' for 'filename' Your help will really be appreciated. Thank you in advance! -
Filter django QuerySet on subclassed type (multi-table inheritance)?
I'm looking for an efficient model manager method that uses the following class structure to generate the QuerySet described by code in views.py: #models.py from django.db import models class Super(models.Model): date_of_interest = models.DateField(...) # <other model_fields> class SubA(Super): # <other model_fields> class SubB(Super): # <other model_fields> class SubC(Super): # <other model_fields> #somewhere else (eg. views.py) ... query_set = Super.objects.filter(date_of_interest=today) qs_to_list = [e for e in query_set if hasattr(e, 'subb') or hasattr(e, 'subc')] I would like to keep qs_to_list a QuerySet, so I'm searching for a way to filter with a model manager, based on the type of subclass. As noted, I'm using multitable inheritance with abstract=False and implicitly using the OneToOneField created with this type of inheritance. Thanks! -
TypeError show_poll() got an unexpected keyword argument 's'
i'm trying to redirect the user after submitting a form to the polls list.. the form is saved in the admin after submitting but the redirection is failing anyone can help me with this? my views.py def show_poll(request, id): p = Poll.objects.get(id=id) pops = p.option_set.all() context = { 'poll': p, 'options': pops, } return render(request, "show_poll.html", context) def create_poll(request): c_form = PollForm(request.POST or None) data = {} data["create_form"] = c_form if c_form.is_valid(): poll = c_form.save(commit=False) poll.slug = slugify(poll.title) poll.save() return redirect("show_poll", s=poll.slug) return render(request, "create_poll.html", context=data) my urls.py from django.urls import path from . import views urlpatterns = [ path('show/poll/<int:id>/', views.show_poll, name="show_polls"), path('c_poll/<slug:s>/',views.show_poll, name="show_poll"), path('create/poll/',views.create_poll) ] -
I want to Upload a file and then I want to parse that file to get the phone number and email id to fill the the columns email and mobile
I have created this model files to store a file two fields more fields. class Profile(models.Model): email = models.EmailField(max_length=254, blank=False) mobile = PhoneField(blank=False) resume = models.FileField(upload_to='resume/') and here is the view file. @api_view(['POST']) @parser_classes([MultiPartParser]) def upload_file(request, format=None): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) and with the help of this all i can do is that i have to provide all the three field which are there in the the model.py but i want just to upload the file and parse that file to get those two fields. Suggest a way through which it can be achieved, I know it is something really basic but i cant figure it out. here is the seriliazers.py file class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['email', 'mobile', 'resume'] -
Not able to navigate between two templates in a Django application
I have a ran into a difficulty when navigating between different templates in a Django (v3.2) application. The app is called 'manage_remittance'. The default landing page (which uses template manage_remittance/templates/manage_remittance/view_remittance.html) for the app should show a list of items (list is not relevant at the moment), and at the top of that list there should be a link, leading to another page in the same app, which would allow to add new items to the list. The form that is invoked first is here: manage_remittance/templates/manage_remittance/view_remittance.html {% extends "root.html" %} {% load static %} {% load crispy_forms_tags %} {% url 'manage_remittance:remittance_add' as remittance_add %} {% block title %} VIEW REMITTANCES PAGE {% endblock title %} {% block content %} <div class="list-group col-6"> <a href="{{ remittance_add }}" class="list-group-item list-group-item-action shadow-mt list-group-flush list-group-item-dark text-light">Click here to add remittance data</a> </div> I want to be able to get to another template (manage_remittance/templates/manage_remittance/remittance_add.html), but the {{ remittance_add }} has no value. In addition, when I specify exact name of the html file (remittance_add.html) in the a href (see above), and click on it, I get a following error: Using the URLconf defined in sanctions_project.urls, Django tried these URL patterns, in this order: admin/ [name='login'] login/ … -
Problem while transferring data between POST request and GET in django
I have a select tag, and what my logic is that after the user selects an option, we would send that response and search through the db to find similar records. The problem is how to access that data. After the user has selected an option, I would take them to other page which is just a GET request page. So how to access the select tag data(which is a POST request data) on a GET request page. -
How to pass a Django url in AJAX?
I'm trying to pass a Django URL in ajax after I get the data from the views.py but i get a page not found when I do so : data.forEach((item) => { var url = "{% url 'delete_user' 1 %}".replace('1', item.id); tableBody.innerHTML += '<tr><td>'+item.username+'</td><td>'+ item.first_name+'</td><td>'+item.last_name+'</td><td>'+item.email+ '</td><td><a href='+url+'><i class="fa fa-trash btn btn-danger"></i></a></td>' + '<td><a href="{% url \'admin_edit_profile\''+ item.id +'%}"><i class="fa fa-edit btn btn-warning"></i></a></td></td></tr>' }); i've Tried this i saw it somewhere here : var url = "{% url 'delete_user' 1 %}".replace('1', item.id); but it doesn't seem to work the error i get : Not Found: /admin_users/{% url 'delete_user' item.id %} [12/Jun/2021 11:04:23] "GET /admin_users/%7B%%20url%20'delete_user'%20%20%20item.id%20%20%%7D HTTP/1.1" 404 7099 -
How to allow Django container to use Docker SDK without permission error?
I have a container running a Django application from which I need to spawn other containers on the host machine. I'm using the Docker SDK for Python within one of my views however when running the application I get a Permission Denied error. Dockerfile: # syntax = docker/dockerfile:experimental FROM python:slim-buster MAINTAINER "" "" RUN mkdir -p /opt/app && \ mkdir -p /opt/app/pip_cache WORKDIR /opt/app COPY ./config ./src /opt/app/ RUN chmod +x web/start-server.sh && \ chmod +x web/wait-for-it.sh && \ chmod +x web/setup.sh && \ python3 -m pip install --upgrade pip && \ python3 -m pip install -r requirements.txt --cache-dir pip_cache && \ chown -R www-data:www-data /opt CMD ./web/start-server.sh STOPSIGNAL SIGTERM docker-compose.yaml: version: "3" services: nginx: build: ./config/nginx container_name: nginx restart: always ports: - "8084:80" - "443:443" command: nginx -g "daemon off;" volumes: - static:/static/ - media:/media/ links: - web:web depends_on: - web web: build: . container_name: web restart: always expose: - "8010" links: - db:db volumes: - static:/static/ - media:/media/ - /var/run/docker.sock:/var/run/docker.sock env_file: - config/web/django.env depends_on: - db stdin_open: true tty: true db: image: postgres:latest container_name: postgres restart: always ports: - "5432:5432" env_file: - config/postgres/database.env volumes: static: media: views.py: import docker from django.http import HttpResponse def container_view(request): if request.method == … -
Django cms in action menu in something went wrong error
In Django cms framework in when clicking on page models(action menu) showing an error and getting an error on the backend side. This is traceback : Internal Server Error: /admin/cms/page/1/actions-menu/ Traceback (most recent call last): File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/cms/admin/pageadmin.py", line 343, in actions_menu return render(request, self.actions_menu_template, context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/defaulttags.py", line 401, in render return strip_spaces_between_tags(self.nodelist.render(context).strip()) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/home/username/Documents/Django/project/env/lib/python3.8/site-packages/django/template/defaulttags.py", line 305, in render match … -
Can I expose the API URL to the public in a Python library?
I have built a Django API which has a lot of proprietary algorithms for analyzing stock portfolios. The API is hosted in AWS and this API is also connected to the website where I show the visualizations of the calculated metrics. I want to build a library to provide these metrics in Python like pandas. Users can install this package using pip install . In my Python library code, I would expose only the API URL and I will call the API with different parameters and endpoints. Paid users will get a unique access code in email using which only they can access the Python package functions. I don't want to expose my Django API code to the public as the analysis itself requires a lot of stock price data from the Database and also there are a lot of proprietary algorithms. Does the solution make sense? Should I hide the API URL or just leave it. -
Django - python manage.py runserver error - TypeError: function takes at most 3 arguments (4 given)
I'm running into this error for the first time today and can't find any solution on other threads. Here is the response I'm getting when I run 'python manage.py runserver' ➜ duncs_django python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) … -
Django: Voting System Not Working With Radio Buttons
I am trying to make a simple reddit clone with a voting system that is basically just upvotes - downvotes however now that I changed from using buttons for voting to radio buttons so that you could only vote once, no votes are being counted at all. If anybody could help me out with this that would be great. My Html: {% extends 'thefeed/base.html' %} {% block content %} <div class="announcement"> <h5 style="background: yellow;">Forum.Chat is the Internet's home for debate on any topic, keep it civil!</h5> </div> <br> {% for post in object_list %} <div style="margin-bottom: 2%;"> <h3><a href="#" style="color: red;">{{post.ranking}} </a><a href="{% url 'feed-post' post.pk %}">{{post.title}}</a><a href="#"></h3> <p><a href="#">By: {{post.author}}</a><a href="{% url 'edit-post' post.pk %}"> Edit Post</a></p> <form action=""> <p> <input class="btn btn-outline-primary" type="radio" name="vote"> <a href="{% url 'upvote-post' pk=post.pk %}" style="color: black; font-weight: bold;"></a> </input> <input class="btn btn-outline-danger" type="radio" name="vote"> <a style="font-weight: bold; color: black;" href="{% url 'downvote-post' pk=post.pk %}"></a> </input> </p> </form> </div> <hr> {% endfor %} {% endblock %} My Urls: path('post/<int:pk>/downvote', views.DownvoteView, name='downvote-post'), path('post/<int:pk>/upvote', views.UpvoteView, name='upvote-post'), My Model: class post(models.Model): title = models.CharField(max_length=200) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) ranking = models.IntegerField(default=0) My View: def UpvoteView(request, pk): selected_post = post.objects.get(pk=pk) selected_post.ranking+=1 selected_post.save() return redirect('feed-home') … -
How to have 2 textboxes as mutually exclusive in an html form?
I would like to have 2 mutually exclusive fields. One will be a FileField and other TextBoxField. Is there a ready html form I can get my hands on to. I have searched the web and couldnt find any. -
Change Products by Form in Django
I have two models about my products class Product(models.Model): product_model = models.CharField(max_length=255, default='', verbose_name="نام محصول") product_url = models.SlugField(max_length=200, default='', verbose_name="اسلاگ محصول" ) description = tinymce_models.HTMLField(verbose_name="توضیحات") size = models.ManyToManyField(Size , verbose_name="سایز", related_name="rel_size") ... class Size(models.Model): size = models.CharField(max_length=20) size_url = models.SlugField(max_length=200, default='', verbose_name="اسلاگ سایز") class Stock(models.Model): amount = models.PositiveIntegerField(verbose_name="موجودی انبار") product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="محصول") size = models.ForeignKey(Size, on_delete=models.CASCADE, verbose_name="سایز") product_price = models.FloatField(null=True, verbose_name="قیمت محصول") we have L M Xl XXL sizes and in views.py i have: def product_detail(request, product_url): if request.user.is_authenticated and request.user.is_staff or request.user.is_superuser: product = get_object_or_404(Product, product_url=product_url) stock = get_list_or_404(Stock, product=product) if request.method == "POST": amount = request.POST['amount'] price = request.POST['price'] stock.amount = amount stock.product_price = price stock.save() ctx = {'product':product, 'stock':stock} return render(request, 'staff/product_detail.html',ctx) else: return redirect('/staff') and my html : <div class="container-fluid"> {{product.product_model}} <br> <br> {% for sto in stock %} <form method="POST" class="register-form" id="register-form"> {% csrf_token %} <p>{{sto.size}}</p> <input type="text" value="{{ sto.amount | default_if_none:"" }}" name="amount" id="lo" placeholder="موجودی"/> <input type="text" value="{{ sto.product_price | default_if_none:"" }}" name="price" id="lo" placeholder="قیمت (تومان)"/> <br> <input type="submit" name="signup" id="signup" class="form-submit" value="ذخیره"/> </form> {% endfor %} <br> </div> My problem is that each size has own amount and price from a product, like each product has 1 or more size it … -
how to select manytomany objects only for the current instance
i want the manytomany select display the values related for a current instance like this: in this image he display interet sql & nage but sql not for a current instance Hanin sql interet is for person Ahmedmahmoud nage is for acurrent instance Hanin Models.py class Formation(models.Model): Nom = models.CharField(max_length=100) Niveau = models.CharField(max_length=200) institution = models.CharField(max_length=100) contexte = models.CharField(max_length=100) Description = models.TextField() DateDebut = models.DateField(null=True) DateFin = models.DateField(null=True) id_candidat = models.ForeignKey(Candidat, null= True, on_delete=models.SET_NULL,default=Candidat.id) def __str__(self): return self.Nom class CV(models.Model): interet = models.ManyToManyField(Interet) candidat = models.ManyToManyField(Candidat) Langues = models.ManyToManyField(Langue) Certifications= models.ManyToManyField(Certification) Experiences= models.ManyToManyField(Experience) Competence = models.ManyToManyField(Competence) Refferances= models.ManyToManyField(Réfférence) Declaration = models.ManyToManyField(DeclarationPerson) Formations = models.ManyToManyField(Formation) views.py def createcv(request): if request.method=='POST': cv_form=CVForm(request.POST) if cv_form.is_valid(): cv_form = cv_form.save(commit=False) cv_form.id_candidat= Candidat.objects.get(id=request.user.candidat.id) cv_form.save() return redirect('/resume') context={'cv_form':cv_form} return render('/') forms.py class CVForm(ModelForm) : class Meta: model=CV fields="__all__" exclude = ["candidat"] -
How to extract data from Django api rest framework POST method
I'm trying to build an API that execute a script with some variables, those variables are in the POST msg, like {'command': 'start', 'name': 'var'}.. The thing is that I can't find the function the extraction those exact values and not all of the data. after a few days I tried with flask but that idea is the same. from flask import Flask, request from flask_restful import Api, Resource import os script = 'python /home/USER/somepath/client.py start ' app = Flask(__name__) api = Api(app) class Netflix(Resource): def get(self): return "Success", 201 def post(self): name = request.data os.system(script+name) print(name) return "Success", 201 api.add_resource(Netflix, "/netflix") if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=8000) -
Login and Authentication in Django
I am trying to create a login function and login authentication in the views.py inside def login(request) for particular username and password from my model class "Signup" . Could someone please help me in my existing code how to do so or share any resources to perform the following operation. P.S. I am new to Django and getting overwhelmed by the information present in the internet due which couldn't get the solution to my problem. I am adding my code snippets for models.py , views.py , urls.py and login.html . "models.py" from django.db import models # Create your models here. class SignUp(models.Model): username= models.CharField(max_length=100) email=models.EmailField(max_length=254) password=models.CharField(max_length=20) address=models.CharField(max_length=250) "views.py" from django.shortcuts import render,redirect from django.http import HttpResponse from .models import SignUp from django.contrib.auth import login,authenticate,logout # Create your views here. def login(request): if request.method == 'POST': username= request.POST['username'] password= request.POST['password'] user = authenticate(username=username,password=password) html2 = "<html><body>No such user</body></html>" if user is not None: login(request,user) return redirect('') else: return HttpResponse(html2) else: return render(request,'login.html') def signup(request): if request.method == 'POST': username= request.POST['username'] email= request.POST['email'] password1= request.POST['password1'] password2= request.POST['password2'] address= request.POST['address'] html = "<html><body>Confirm Password and Password should be same </body></html>" html1= "<html><body>User Already present </body></html>" if password1 != password2: return HttpResponse(html) else: for … -
django admin filter_list by manytomany filed
models.py class Author(models.Model): nickname = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=255) authors = models.ManyToManyField(Author) admin.py @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_filter = (???,) How to filter the books of a particular author through the admin panel. -
Return redirect wont pass parameters
i cant find solution to this simple problem. urls.py path('board/<id>/', board, name="board"), views.py def index(request): if request.method == 'GET': usuario = request.user last_board = Usuario.objects.filter(user=usuario.id).values_list("last_board", flat=True) if usuario.is_authenticated: return redirect('/board/', last_board ) return render(request, "index.html") i tried with get, post, without a request.method but its just simple dont pass the arguments, i literally have the same line on another method and works perfectly. Error url returned: 127.0.0.1/8000/board/ TypeError at /board/ tablero() missing 1 required positional argument: 'id' -
ngrok: Access subdirectory URLs in Django
I am using ngrok to test my website. I am able to launch the home page, but how do I launch directories other than homepage? such as 127.0.0.1:8000\apartment_listing? I get Error 500: Internal Server Error. Any solution? -
Django admin : TypeError: __str__ returned non-string (type NoneType)
Please help noob.. Although there is no seed(any instance) in my tables or DB, the error occur when I try to ADD instance in http://localhost:8000/admin/posts/post/add/ If there are seeds, I can see on the admin page, but try to edit or add, then error occur. Can't find where is the problem. (I also tried return str(~~variable) things...) error is same as below: TypeError at /admin/posts/post/add/ str returned non-string (type NoneType) class Post(core_models.TimeStampedModel): pno = models.IntegerField(null=True) # 게시물_번호 password = models.CharField(max_length=100, null=True) # 비밀번호 union = models.ForeignKey( union_models.Union, on_delete=models.CASCADE, null=True ) # 조합 # null=True 안하면 에러남 title = models.CharField(max_length=50, null=True) # 제목 content = models.CharField(max_length=10, null=True) # 내용 writer = models.ForeignKey( user_models.User, related_name="writer", on_delete=models.PROTECT, null=True ) # 작성자 receiver = models.ForeignKey( user_models.User, related_name="receiver", on_delete=models.PROTECT, null=True ) # 받는사람 hits = models.IntegerField(null=True) # 조회수 is_notice = models.BooleanField(null=True, default=False) # 공지사항_구분 category = models.CharField(null=True, max_length=50) # 공지사항_카테고리 def __str__(self): if self.title == None: return "ERROR- IS NULL" return self.title