Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can we insert data into django default database sqlite3 without using models?
like without importing models and using the following commands: conn=sqlite3.connect("db.sqlite3") c=conn.cursor() c.execute("sql command") I am new to Django ,could you please??? -
'NoneType' object is not iterable' when using chrome browser
I get this error: 'TypeError at /' with the exception value: ''NoneType' object is not iterable' when i run my Django project on my local host. This only occurs when i'm specifically using the chrome browser ONLY. When i run my local host on safari, there are no issues. I am pretty certain that my code is not at fault, because i was running it, and closed my laptop, and when i opened up my laptop again, it gave me this error, and i had not changed a single line of code. Also i'm sure that its not my code because it is working on safari as i have stated earlier -
Django URL with blank parameter
I am new to Django. I created a Django web app wherein after a user logs in, it will redirect to the basic_list template which contains a list of wines. In the basic_list template, there is a “manage account” button which will redirect to the manage_account template. However, when I click the manage account button, it loads to localhost:8000/manage_account// instead of having a parameter such as localhost:8000/manage_account/1/ if 1 is the pk value of the user who just logged in. What should I do? Any suggestions would be greatly appreciated. models.py from django.db import models class Wine(models.Model): name = models.CharField(max_length=300) year = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.name class Account(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.username urls.py from django.urls import path from . import views urlpatterns = [ path('', views.view_login, name='view_login'), path('login', views.view_login, name='view_login'), path('basic_list', views.view_basic_list, name='view_basic_list'), path('manage_account/<int:pk>/', views.manage_account, name='manage_account'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * from django.core.exceptions import ObjectDoesNotExist def view_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') account = Account.objects.get(username=username) if password == account.password: return redirect('view_basic_list') else: return render(request, 'myapp/login.html', … -
How to use add-to-cart functionality in Django and after adding item in table the button should be hidden/disable?
I'm using Django as a backend and PostgresSQL as a DB and HTML, CSS, JS as frontend. Well, I have successfully added data to Django and also in PostregsSQL with models. And the data are fetch to the item_list successfully. So, while doing this I have stuck in a major problem that is ADD-TO-CART, While I'm trying to do as same as this Website. Where a user: Click on add/choose button(mainpage.html) -> PRODUCT ITEM LIST DISPLAYED (itemlist.html) -> Selected PRODUCT (itemlist.html) -> Added Product succesfully (mainpage.html) AND add/choose button should be disabled and instead of the add/choose button EDIT & DELETE Button should appear. How the code will work. I have no IDEA (TOTALLY NOOB). Please do suggest. And I'm adding my code down below. The Code Goes Here.... models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Product(models.Model): brand = models.CharField(max_length = 100) title = models.CharField(max_length=200) view_count = models.PositiveIntegerField(default=0) def __str__(self): return self.title class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) product = models.ManyToManyField(Product, null=True, blank=True) rate = models.PositiveIntegerField() total = models.PositiveIntegerField(default=0) subtotal = models.PositiveIntegerField() def __str__(self): return "Cart:" + str(self.id) admin.py admin.site.register(Cart) class CartAdmin(admin.ModelAdmin): class Meta: Model = Cart … -
502 nginx bad gateway error when uploading video to digital ocean droplet
I get this error in my django app when I try uploading large files in my digital ocean droplet.but when I try uploading low file it works. -
Django some columns in a model is migrated
I have the following model from django.db import models class Todo(models.Model): content = models.CharField(max_length=100) created_at_one: models.DateField(auto_now_add=True) finished_at: models.DateField(null=True) is_completed: models.BooleanField(default=False) list = models.ForeignKey( "TodoList", related_name="todos", on_delete=models.CASCADE) class TodoList(models.Model): title: models.CharField(max_length=20) created_at: models.DateField(auto_now_add=True) Then when I run python manage.py makemigrations and python3 manage.py migrate, there is no error. But when I check the tables created, some columns are missing. I run .schema app_todo to check the tables of Todo CREATE TABLE IF NOT EXISTS "app_todo" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content" varchar(100) NOT NULL, "list_id" bigint NOT NULL REFERENCES "app_todolist" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "app_todo_list_id_c59d99ef" ON "app_todo" ("list_id"); Only id, content and list_id are created and three columns missing. For TodoList: CREATE TABLE IF NOT EXISTS "app_todolist" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT); title and create_at are missing. Please let me know if there is additional information that I should provide. Thanks a lot! -
raise KeyError(key) from None KeyError: 'AWS_ACCESS_KEY_ID'
when i am trying to execute the command python manage.py runserver i got this error File "C:\Users\Thripura sai\PycharmProjects\pythonProjectbiddd\Online_Auction_System_Project\online_auction_system\settings.py", line 164, in <module> AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] File "C:\Users\Thripura sai\AppData\Local\Programs\Python\Python39\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'AWS_ACCESS_KEY_ID' i don't know what's wrong with my code this is the code in my os.py which i got error def __getitem__(self, key): try: value = self._data[self.encodekey(key)] except KeyError: # raise KeyError with the original key value raise KeyError(key) from None return self.decodevalue(value) please provide me a solution -
OAuth 2.0 redirect url with django
I am making 2 django apps (one is the client and the other is the provider) and i am having problem redirecting to the correct url (the one that i entered when client registerd to provider). Does anyone knows how and where the client app process and create the redirect url??? I build the provider using OAuth toolkit and the client with social-oauth -
How to solve SMTNotSupported extension by the server Error?
Actually i am creating a registration form using django and when user will submit it he will get successful registration mail but it will give me error SMTPNotSupported extension server. my settings.py file EMAIL_HOST = 'smpt.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = myusername EMAIL_HOST_PASSWORD = my password EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend I am sharing my error photo with you all. -
Django song not being added to 'favourite songs'
I want my users to be able to add certain songs to Favourite Songs but although the success message 'Added to favourite songs' but when I visit the Favourite Songs page, I see no songs there. How can I fix this? Thanks in advance! My models.py: class Songs(models.Model): title = models.CharField(max_length = 100) lyrics = models.TextField() author = models.CharField(max_length = 100) track_image = models.CharField(max_length=2083) def __str__(self): return self.title def get_absolute_url(self): return reverse('/', kwargs={'pk': self.pk}) My views.py: def home(request): context = { 'songs': Songs.objects.all() } return render(request, 'home.html', context) @login_required def add_to_fav_songs(request, **kwargs): fav_song = Songs.objects.filter(id=kwargs.get('id')) messages.success(request, f'Added to favourite songs') return redirect('/') class Fav_songs(ListView): model = Songs template_name = 'fav_songs.html' context_object_name = 'fav_song' paginate_by = 2 def get_queryset(self): return Songs.objects.filter(pk=self.kwargs.get('pk')) My favoutie_songs.html: {% for song in fav_song %} <article class="media content-section"> <div class="media-body"> <h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ song.title }}</a></h2> <div class="article-metadata"> <a class="mr-2" href="{% url 'author-songs' song.author %}">{{ song.author }}</a> </div> <br> <img class="card-img-bottom" height="339px" width="20px" src="{{ song.track_image }}"> </div> </article> {% endfor %} -
Django ListView Filter
In my project am using Django ListView and it works fine. What I want now is to list data from database but with filter. One of the field I want to filter is resolution_date. below is my code: class RequestListView(ListView): model = Customer_Requests template_name = 'requests_list.html' paginate_by=2 def get_queryset(self): filter_val=self.request.GET.get("filter","") order_by=self.request.GET.get("orderby","id") if filter_val!="": reqo=Customer_Requests.objects.filter(Q(request_name__icontains=filter_val) | Q(subject__icontains=filter_val)).order_by(order_by) else: reqo=Customer_Requests.objects.all().order_by(order_by) return reqo def get_context_data(self,**kwargs): context=super(RequestListView,self).get_context_data(**kwargs) context["filter"]=self.request.GET.get("filter","") context["orderby"]=self.request.GET.get("orderby","id") context["all_table_fields"]=Customer_Requests._meta.get_fields() return context The above code list everything from the table but I want the records where resolution date is empty. How can I achieve this? Thank you -
Django for loop from one DB table
I'm working on a livescore app and can't get matches within leagues in the table, nested for loop is empty. I only get listed leagues and I would like to have inside the leagues all the matches that belong to those leagues -Leaugue match match -League match match My DB Model: class basic_scores(models.Model): time_status = models.CharField(max_length=5) time_minute = models.CharField(max_length=5) localteam_data_name = models.CharField(max_length=255) visitorteam_data_name = models.CharField(max_length=255) scores_localteam_score = models.CharField(max_length=15) scores_visitorteam_score = models.CharField(max_length=15) country_name = models.CharField(null=True, max_length=255) league_name = models.CharField(null=True, max_length=255 View: def league(request): #live_list = football_nows.objects.all() live_list = basic_scores.objects.all() return render(request, 'league.html', {'live_list': live_list}) league.html: <h1>Live</h1> {% for league in live_list %} <center> <td>{{ league.league_name }}</td> {% for live in league %} <td>{{ live.time_minute }}</td> <td>{{ live.localteam_data_name }}</td> <td>{{ live.scores_localteam_score }} : {{ live.scores_visitorteam_score }}</td> <td>{{ live.visitorteam_data_name }}</td> {% endfor %} </center> {# This is a comment. #} {% endfor %} Browser result: -
Efficiently extract large amounts of data from Django ORM
I have a Django setup with PostgreSQL DB. One of the tables contains large amounts of data (>1e9 rows) and I need to efficiently iterate over a large subset of it. Currently, when I try to select a large amount of data it starts buffering the result and my computer runs out of memory. If I use .iterator() on QuerySet, it just hangs. If I try to use raw SQL and fetchall() it also starts buffering. I believe Django uses psycopg2 for PostgreSQL which has cursor.itersize parameter, but when I try to use it with cursor in Django it doesn't do anything. I know that the problem is not on database end, since I can execute the query using psql (with -A --variable="FETCH_COUNT=10000") and it starts loading immediately without using any memory. Extra info: The table has >10 columns, but I only need 2 of them, so if it is possible to only fetch selected for faster loading it would be nice. -
'QuerySet' object has no attribute 'name' Django
So I have a get function class HorseEquipmentView(APIView): lookup_url_kwarg = 'horse' def get (self, request, format = None): horse = 1 if horse != None: tab = [] #queryset = HorseEquipment.objects.raw('SELECT H.horse_id, E.name FROM horse_equipment H JOIN equipment E ON H.equipment_id = E.id WHERE H.horse_id =' + str(horse)) queryset = HorseEquipment.objects.filter(horse_id=horse).select_related("equipment") for i in queryset: i.equipment = Equipment.objects.filter(id = 1).name #equipment = HorseEquipment.objects.filter(horse_id=horse).select_related('equipment') serializer = HorseEquipmentSerializer(queryset, many = True) return Response(serializer.data) else: return Response(status = status.HTTP_400_BAD_REQUEST) and my Equipment Model: class Equipment(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(unique=True, max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'equipment' So it has id and name attributes but somehow it gives me error on my get function, precisely on my for loop where I refer to "name" attribute. Can you help me find out what's wrong? -
Django ManyToManyField prefetch multiple level
I created a mapping table for ManyToMany relationships. The model is roughly as below. //PageTemplate Model class PageTemplate(models.Model): id = models.AutoField(primary_key=True) page = models.ForeignKey( Page, null=False, related_name='pt_page' ) template = models.ForeignKey( Template, null=False, related_name='pt_template' ) created = models.DateTimeField(auto_now_add=True, verbose_name=_('Created At')) //Page Model class Page(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey( Project, related_name='pages', on_delete=models.CASCADE, verbose_name=_('project_id') ) page_type = models.ForeignKey( ProjectType, related_name='pages', on_delete=models.CASCADE, verbose_name=_('page_type') ) page_template = models.ManyToManyField( 'Template', through='PageTemplate' ) ... //Template Model class Template(models.Model): id = models.AutoField(primary_key=True) @property def width(self): return self.page.page_type.width @property def height(self): return self.page.page_type.height ... After this, I created a serialize class. class PageTemplateSerializer(ExtendedValidationErrorSerializer): page_id = serializers.ReadOnlyField(source='page.id') page_type = serializers.ReadOnlyField(source='page.page_type') page_title = serializers.ReadOnlyField(source='page.title') page_order = serializers.ReadOnlyField(source='page.order') template_id = serializers.ReadOnlyField(source='template.id') template_width = serializers.ReadOnlyField(source='template.width') template_height = serializers.ReadOnlyField(source='template.height') class Meta: model = PageTemplate fields = ('page_id', 'page_type', 'page_title', 'page_order', 'template_id', 'template_width', 'template_height') This is not a problem, but Template has a reference to TamplateDetailItem, a class with detailed data inside Template. Reverse reference relation referencing TamplateDetailItem to Template. class TemplateDetailItem(models.Model): id = models.AutoField(primary_key=True) template = models.ForeignKey( Template, null=False, related_name='template_detail_items', ) ... That is, the structure is mapped to the PageTemplate as a many-to-many relationship (Page <-> Template), and the Template and TemplateDetailItem are mapped as a one-to-many relationships. (TemplateDetailItem -> … -
is it possible create export as CSV button when there is pagination in your HTML using plane javascript?
I am able to download the content on the current page but not able to download all the content coming to the table from the backend. // Quick and simple export target #table_id into a csv function download_as_csv(table_id, separator = ',') { // Select rows from table_id var rows = document.querySelectorAll('table#' + table_id + ' tr'); // Construct csv var csv = []; for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll('td, th'); for (var j = 0; j < cols.length; j++) { // Clean innertext to remove multiple spaces and jumpline (break csv) var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ') // Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv) data = data.replace(/"/g, '""'); // Push escaped string row.push('"' + data + '"'); } csv.push(row.join(separator)); } var csv_string = csv.join('\n'); // Download it var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv'; var link = document.createElement('a'); link.style.display = 'none'; link.setAttribute('target', '_blank'); link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string)); link.setAttribute('download', filename); document.body.appendChild(link); link.click(); document.body.removeChild(link); } I have hound similar question here with no answer. For the backend, I am using Django and to render a table using Vue.js.Any suggestions will be highly appreciated. TIA. -
Django error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found
So I want users to be able to add songs to a section called 'Favorite songs'(just like adding products to a cart in an e-commerce website) but I'm getting this error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found. 1 pattern(s) tried: ['add\\-to\\-fav\\-songs/(?P<pk>[0-9]+)/$']. Can anyone correct my code and show me how can I add songs to favorite songs. Thanks in advance! My models.py: class Songs(models.Model): title = models.CharField(max_length = 100) lyrics = models.TextField() author = models.CharField(max_length = 100) track_image = models.CharField(max_length=2083) def __str__(self): return self.title def get_absolute_url(self): return reverse('/', kwargs={'pk': self.pk}) My views.py: def home(request): context = { 'songs': Songs.objects.all() } return render(request, 'home.html', context) @login_required def add_to_fav_songs(request): fav_song = get_object_or_404(Songs) class Fav_songs(ListView): model = Songs template_name = 'fav_songs.html' context_object_name = 'fav_song' paginate_by = 2 def get_queryset(self): return Songs.objects.filter(id=self.kwargs.get('pk')) My urls.py: path('add-to-fav-songs/<int:pk>/', views.add_to_fav_songs, name='add-to-fav-songs'), path('favourite-songs/', Fav_songs.as_view(), name='favourite-songs'), My home.html: <form class="form" method="POST" action="{% url 'add-to-fav-songs' object.id %}"> {% csrf_token %} <div class="action"> <button class="like btn btn-danger" type="button"><span class="fa fa-heart"></span></button> </div> </form> My fav_songs.html: {% for fav_song in songs %} <article class="media content-section"> <div class="media-body"> <h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ fav_song.title }}</a></h2> <div class="article-metadata"> <a class="mr-2" href="{% url 'author-songs' song.author %}">{{ fav_song.author }}</a> </div> <br> … -
ValueError: The view videos.views.add_comment_post didn't return an HttpResponse object. It returned None instead in Django
I tried to add comments with the post and it raise this error, and I supmit my comment using ajax but it seems the problem coming from the view but I couldn't figure out what exactly the problem My add comments View @login_required def add_comment_post(request): comment_form = PostCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) My comment Model class PostCommentIDF(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() publish = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) likes = models.ManyToManyField(Account, blank=True, related_name='pos_com') class MPTTMeta: order_insertion_by = ['-publish'] def __str__(self): return f'{self.author}---{self.content[:15]}' My form for the comments class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True'}) } def save(self, *args, **kwargs): PostCommentIDF.objects.rebuild() return super(PostCommentForm, self).save(*args, **kwargs) the comments form in the template <form id="Postcommentform" class="Postcommentform" method="post" style="width: 100%;"> {% load mptt_tags %} {% csrf_token %} <select class="d-none" name="video" id="id_video"> <option value="{{ video.id }}" selected="{{ video.id }}"></option> </select> <div class="d-flex"> <label class="small font-weight-bold">{{ comments.parent.label }}</label> {{ comment_form.parent }} {{comments.content}} <button … -
Implementation of Nginx Container for Reverse Proxying and SSL certificates for Django Containers inside Docker Swarm
I want to deploy Django Application with Docker Swarm. I was following this guide where it does not use the docker swarm nor docker-compose, and specifically created two Django containers, one Nginx container, and a Certbot container for the SSL certificate. The Nginx container reverse proxy and load balance across the two Django containers which are in the two servers using their IPs upstream django { server APP_SERVER_1_IP; server APP_SERVER_2_IP; } server { listen 80 default_server; return 444; } server { listen 80; listen [::]:80; server_name your_domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name your_domain.com; # SSL ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem; ssl_session_cache shared:le_nginx_SSL:10m; ssl_session_timeout 1440m; ssl_session_tickets off; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off; ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384"; client_max_body_size 4G; keepalive_timeout 5; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django; } location ^~ /.well-known/acme-challenge/ { root /var/www/html; } } I want to implement all this same functionality but with Docker Swarm so that I can scale the containers with one command docker service update --replicas 3 <servicename> The problem is I am not able to understand How to use implement the Nginx container in this scenario, Docker Swarm … -
The gunicorn server of the blog system deployed on EKS becomes "WORKER TIME OUT"
We are migrating the blog system that was previously deployed on EC2 to the AWS EKS cluster. On EC2 of the existing system, it operates in two containers, a web server (nginx) container and an AP server (django + gunicorn) container, and can be accessed normally from a browser. So, when I deployed it to the node (EC2) on AWS EKS in the same way, I could not access it from the browser and it was displayed as "502 Bad Gateway". The message "TIMEOUT (pid: 18294)" is displayed. We are currently investigating the cause of this, but the current situation is that we do not know. If anyone has any idea, I would appreciate it if you could teach me. gunicorn of log・status root@blogsystem-apserver01:/# systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2021-05-09 08:57:19 UTC; 5 days ago Main PID: 18291 (gunicorn) Tasks: 4 (limit: 4636) Memory: 95.8M CGroup: /kubepods/besteffort/podd270872c-cc5b-4a3b-92ed-f463ee5f5d77/1eafc79ffd656ff1c1bc39175ee06c7a5ca8692715c5e2bfe2f979d8718411ba/system.slice/gunicorn.service ├─18291 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/socket/myproject.sock myproject.wsgi:a pplication ├─18295 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/socket/myproject.sock myproject.wsgi:a pplication ├─18299 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/socket/myproject.sock myproject.wsgi:a pplication └─18300 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - … -
launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} -Error While Creating Django Project
When I tried to create Django project in virtual Environment, I am getting below Error, C:\Users\new\Desktop\Desktop Files\Django Projects>activate myDjangoEnv (myDjangoEnv) C:\Users\new\Desktop\Desktop Files\Django Projects>django-admi n startproject first_project Traceback (most recent call last): File "C:\Users\new\anaconda3\envs\myDjangoEnv\lib\site-packages\django\apps\config.py", line 7, in from django.utils.deprecation import RemovedInDjango41Warning File "C:\Users\new\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\deprecation.py", line 5, in from asgiref.sync import sync_to_async File "C:\Users\new\anaconda3\envs\myDjangoEnv\lib\site-packages\asgiref\sync.py", line 114 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax Please help me on this.Thanks in advance -
parse multiple values to user_passes_test in a function-based view
I have a function-based view #views.py def my_view(request,pk): post = Posts.get(pk) . . . return redirect("my-view") I want to make sure, that the user created the post, also is the one approaching the page. In the class-based update-view we can define the test_func class MyPosts(UserPassesTestMixin): def test_func(self): """ Check if the logged in user is the one created the link """ post= self.get_object() #Gets the current post if self.request.user == post.user: return True return False but I cannot figure out how to parse the post argument (or the post.user) to the user_passes_test function in the function-based view. According to the documentation the user_passes_test decorator has to take a function which takes a User argument as the first arguemnt and two optional arguments - and I need to parse both the User and the post-user i.e two user objects and not 1 e.g something like def my_test_func(User,post-user): if User==post-user: return True return False How do I accomplish this w/o using a Class-based view as described above? -
How to call python api from android?
I want to make login app in android which should call python api for matching username and password in database. I know how to call php api but don't know calling python api. Can anyone please help me! -
when i am trying to add post then add successfully but it is not show in dashboard it is show only home page what i do for show post in dashboard
when i am add post then add successfully but it is not show in dashboard it is show only home page what i do to add post in dashboard please help me login code def user_login(request): if not request.user.is_authenticated: if request.method == "POST": form = LoginForm(request=request, data=request.POST) if form.is_valid(): uname = form.cleaned_data['username'] upass = form.cleaned_data['password'] user = authenticate(username=uname, password=upass) if user is not None: login(request, user) messages.success(request, 'Login Successfully !!') return HttpResponseRedirect('/dashboard/') else: form=LoginForm() else: return HttpResponseRedirect('/dashboard/') return render(request, "login.html", {'form':form} ) Sign UP code def user_signup(request): if request.method =="POST": form = SignUpForm(request.POST) if form.is_valid(): messages.success(request, 'Successfully SignUp') form.save() form = SignUpForm(request.POST) else: form = SignUpForm() return render( request, "signup.html", {'form' : form} ) Dashboard code def dashboard(request): if request.user.is_authenticated: current_user = request.user posts = Post.objects.filter(user=current_user) else: redirect('/login/') return render( request, "dashboard.html", {'posts':posts} ) Dashboard HTML code Dashboard <a href="{% url 'addpost' %}" class="btn btn-success">Add Post</a> <h4 class="text-center alert alert-info mt-3">Show Post Information</h4> {% if posts %} <table class="table table-hover bg white"> <thead> <tr class="text-center"> <th scope="col" style="width: 2%;">ID</th> <th scope="col" style="width: 25%;">Title</th> <th scope="col" style="width: 55%;">Description</th> <th scope="col" style="width: 25%;">Action</th> </tr> </thead> <tbody> {% for post in posts %} {% if post.user == request.user%} <tr> <td scope="row">{{post.id}}</td> <td>{{post.title}}</td> <td>{{post.decs}}</td> … -
Id Field Showing null while saving data in Django rest framework
Whenever I try to add new recored to data base using django rest api it is showing 'null' in the id field I haved attached my serializers code and views code, Views.py @api_view(['POST']) def createcostumer(request): serializer = Costumerdetailsserializer(data=request.data) print(request.data) if serializer.is_valid(): # some_dict = {'id': serializer.data['id']} serializer.save() else: pass return Response(serializer.data) Serializers.py class Costumerdetailsserializer(serializers.ModelSerializer): class Meta: model = Costumerdetails fields = '__all__' Help me to fix This OUTPUT image Here