Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Please solve this im getting this error when i am trying to fetch "sr" value from my post named model
ValueError at /blog/postcmt Field 'sr' expected a number but got ''. Request Method: POST Request URL: http://127.0.0.1:8000/blog/postcmt Django Version: 3.1.3 Exception Type: ValueError Exception Value: Field 'sr' expected a number but got ''. Exception Location: C:\djangoproj\Blogwebsite\myprojenv\lib\site-packages\django\db\models\fields_init_.py, line 1776, in get_prep_value Python Executable: C:\djangoproj\Blogwebsite\myprojenv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\djangoproj\Blogwebsite', 'c:\users\admin\appdata\local\programs\python\python38\python38.zip', 'c:\users\admin\appdata\local\programs\python\python38\DLLs', 'c:\users\admin\appdata\local\programs\python\python38\lib', 'c:\users\admin\appdata\local\programs\python\python38', 'C:\djangoproj\Blogwebsite\myprojenv', 'C:\djangoproj\Blogwebsite\myprojenv\lib\site-packages'] Server time: Wed, 25 Nov 2020 09:22:46 +0000 -
Paginator returns a wrong number for next page in django
I am trying to add the pagination functionality on my blog page and it worked in theory but I don't understand why when it comes to give me text page number or the previous is giving something like this in the url: http://localhost:8000/blog/?page=%3Cbound%20method%20Page.next_page_number%20of%20%3CPage%201%20of%202%3E%3E I now that the Page.next_page_number should return me the next number of the next page, but it doesn't, here is my class based view: class BlogListView(generic.ListView): model = Page template_name = 'pages/blog_list.html' paginate_by = 1 def get_queryset(self): return Page.objects.filter(blog_post=True).order_by('-created_dt') and the rendering template {% extends 'j2base.html' %} {% block breadcrumb %} <h6 class="breadcrump"> <a href="/"><i class="fa fa-home"></i></a> <i class="fa fa-chevron-right"></i> Blog </h6> {% endblock breadcrumb %} {% block content %} <h1>BLOG</h1> {% if page_list %} {% for page in page_list %} <div class="blog_post"> <div class="blog_a"> <a href="{% url 'blog_page' page.slug %}">{{ page.title }}</a> </div> <div class="blog_body"> {{page.formatted_markdown|safe}} </div> <div class="blog_date"> Published {{ page.created_dt }} </div> </div> {% endfor %} {% else %} <p>There are no pages yet.</p> {% endif %} {% if page_obj.has_previous %} <!-- <a class="btn btn-outline-info mb-4" href="?page=1">First</a> --> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" … -
How to mock function call inside other function using pytest?
def publish_book(publisher): # some calculations factor = 4 print('xyz') db_entry(factor) # db entry call which I want to mock print('abc') def update(): publish_book('xyz') @pytest.mark.django_db def test_update(mocker): # in here I'm unable to mock nested function call pass I have db_entry() function call in publish_book(). how can we mock db_entry() function call inside publish_book.I want to perform other calculations of publish_book(), but only skip(mock) the db_entry() call. -
Git bash stopped after trying to push local database
I want to deploy a django project to heroku, so I moved the data in my sqlite database to data.sql in my project folder. I'm trying to push it to the database in heroku, but after this happened, git bash just stopped(not closed). Why is this happening? ssamt@DESKTOP-79IBIQ6 MINGW64 /c/(path to my django project) (master) $ heroku pg:push data HEROKU_POSTGRESQL_TEAL -a (my app name) heroku-cli: Pushing data ---> postgresql-rigid-46893 I can still type stuff, but nothing happens. -
How do I make a collaborative workspace with Django with my friends? [closed]
My friends and I, are working on an e-commerce website and now we need to work on the back-end using Django. We are new beginners with almost zero knowledge of Django. How can I make sure that the changes I make here on our website will also reflect on their files? We used to edit our files using a shared drive on OneDrive but Django runs on the cmd, so, I'm not sure how to make this happen. Anyone help us, soon??? -
Django - Get objects from the table which do not have a Foreignkey in another table
I am Django rest framework to return the list of objects who do not have a foreign key in another table. what queryset should I write to get those objects. models.py class Event(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=100,default='') description = models.TextField(blank=True,default='', max_length=1000) link = models.URLField(null=True) image = models.ImageField(null=True, blank=True) organizer = models.CharField(max_length=100, default='') timings = models.DateTimeField(default=None) cost = models.IntegerField(default=1,null=True,blank=True) def __str__(self): return self.title class Featured(models.Model): event = models.ForeignKey(Event, null=True ,on_delete=models.PROTECT, related_name="event") def __str__(self): return self.event.title class Meta: verbose_name_plural = 'Featured' views.py class Upcoming2EventsViewSet(mixins.RetrieveModelMixin,mixins.ListModelMixin,viewsets.GenericViewSet): serializer_class = Upcoming2Events def get_queryset(self): featured_events = Featured.objects.all().values_list('id') return Event.objects.filter(id__in=featured_events) # return Event.objects.exclude(id__in=featured_events.event.id) # # return Event.objects.exclude(id__in = [featured_events.id]) serializers.py class Upcoming2Events(serializers.ModelSerializer): id = serializers.CharField(source='event.id') title = serializers.CharField(source='event.title') timings = serializers.DateTimeField(source='event.timings') organizer = serializers.CharField(source='event.organizer') class Meta: model = Featured fields = ['id','title','organizer','timings'] Error Got AttributeError when attempting to get a value for field `id` on serializer `Upcoming2Events`. The serializer field might be named incorrectly and not match any attribute or key on the `Event` instance. Original exception text was: 'RelatedManager' object has no attribute 'id'. Can you tell me what queryset should I write to get the only objects which are not present in the table Featured? Also, what should I do to get only the … -
how to implement branch wise permission in Django
This question is concerned about role and permission in DJango.I am developing web CRM for a company who have multiple branches. But the problem a staff may have multiple role in each branches. That mean Satff x will be working as 'branch manager' at branch-1 and also will be work as 'sales manager' at branch -2. Both roles are different permissions, and also user should be able to customize permission of each user even though they are belongs to role. I thought to implement this Django Group, Permission options, I have created staff by extends User,Please help me to design its model effectively. from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from branch.models import Branch from django.contrib.auth.models import Group from django.contrib.auth.models import Permission class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" … -
In template /home/ryszardb/Desktop/classProject/config/templates/base.html, error at line 0
<!-- templates/forages/project_list.html --> {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} <div class="welcome-user" style="color:darkcyan; text-align:center; font-size: x-large;"> <h1>Welcome {{ user.username }}</h1> </div> {% for project in object_list %} <div class="card"> <div clas="card-header"> <span class="font-weight-bold"><a href="{% url 'project_detail' project.pk %}">{{ project.title }}</a></span> &middot; <span class="text-muted">by {{ project.author }} | {{ project.date }}</span> </div> <div class="card-body"> {{ project.description }} <a href="{% url 'project_edit' project.pk %}">Edit</a>| <a href="{% url 'project_delete' project.pk %}">Delete</a> </div> <div class="card-footer"> {% for entry in project.entries.all %} <p> <span class="font-weight-bold"> {{ entry.author }} &middot; </span> {{ entry }} | longitude: {{ entry.longitude }} | laditude: {{ entry.latitude}} </p> {% endfor %} </div> <div class="card-footer text-center text-muted"> </div> </div> {% endfor %} {% else %} <h1 style="color:darkcyan; text-align: center; font-size: xx-large;"> Please Sign-In before viewing. <br/> Thank you :)</h1> {% endif %} {% endblock content %} <!--- templates/forages/project_detail.html --> {% extends 'base.html' %} {% block content %} <div class="project-detail"> <h2>{{ project.title }}</h2> <p> by {{ project.author }} | {{ project.date }}</p> <p>{{ project.description }}</p> </div> <p><a href="{% url 'project_edit' project.pk %}">Edit</a></p> <p><a href="{% url 'project_delete' project.pk %}">Delete</a></p> <p>Back to <a href="{% url 'project_list' %}">All projects</a></p> {% endblock content %} #urls.py from django.urls import path from .views … -
How much websocket connection can one daphne handle at the same time and how can I increase the max connection
I have 10 daphne instances running When I try to connect 400 clients, only a few connection lost. When I try to connect 1000 clients, more than 400 connection lost. from channels.consumer import SyncConsumer,AsyncConsumer from websocket.utils import * from asgiref.sync import async_to_sync import threading import time #from channels_presence.models import Room #from channels_presence.models import Presence class Consumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): await self.send({ "type": "websocket.send", 'text': "testtt" }) async def websocket_disconnect(self, close_code): #Room.objects.remove("some_room", self.channel_name) pass Django==2.2.8 channels==2.3.1 channels-redis==2.4.1 psycopg2==2.8.5 daphne==2.5.0 django-channels-presence settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } -
how to add days to django annotate from already built annotation
my model looks like this class Model(models.Model): user_id = models.ForeignKey() date = models.DateField() field1 = models.FloatField() field2 = models.FloatField() I have a below queryset queryset = Model.objects.filter(user_id__exact=5) \ .annotate(weekstartdate=Trunc('date', 'week')) \ .values('weekstartdate') \ .annotate(avg_distance=Avg('field1')) \ .annotate(avg_speed=Avg('field2')) \ .order_by('-weekstartdate') which is working perfectly. now I want to add weekenddate field to above queryset which has a date = weekstartdate + 6 days. I have added below line to above query .annotate(weekenddate=Trunc('date', self.duration) + timedelta(days=7), output_field=DateField()) but it is complaining :- TypeError: QuerySet.annotate() received non-expression(s): <django.db.models.fields.DateField> Relative imports from django.db.models import Avg, Q from django.db.models.functions import Trunc from django.db.models import DateTimeField, ExpressionWrapper, F, DateField -
Exception inside application: You cannot call this from an async context - use a thread or sync_to_async
I have been using django-channels, I had created a room for 2 users using single thread from django.db import models from django.contrib.auth import get_user_model from django.db.models import Q from channels.db import SyncToAsync # Create your models here. model = get_user_model() class threadmanager(models.Manager): def get_or_create(self,firstuser,seconduser): thread = self.get_queryset().filter(((Q(first=firstuser)and Q(second = seconduser ))) or ((Q(first=seconduser)and Q(second = firstuser )))) if thread: print(thread.first()) return thread thread = self.model(first=firstuser,second=seconduser) thread.save() return(thread) class thread(models.Model): first = models.ForeignKey(model,on_delete=models.CASCADE,related_name="first") second = models.ForeignKey(model,on_delete=models.CASCADE,related_name="second") objects = threadmanager() def __str__(self): return self.first.username + "-" + self.second.username My chatconsumer is from channels.consumer import AsyncConsumer import asyncio from channels.db import database_sync_to_async import json from accounts.models import thread from django.contrib.auth import get_user_model model = get_user_model() class ChatConsumer(AsyncConsumer): async def websocket_connect(self,event): await self.send( { 'type':'websocket.accept', } ) print("connected",event) async def websocket_receive(self,event): print("received",event) firstuser,seconduser = await self.get_socket_users(event) currentthread = await self.get_current_thread(firstuser,seconduser) print(currentthread) async def websocket_disconnect(self,event): print("disconnected",event) @database_sync_to_async def get_socket_users(self,event): first = self.scope['user'] second = model.objects.get(username=event['text']) return first,second @database_sync_to_async def get_current_thread(self,firstuser,seconduser): return thread.objects.get_or_create(firstuser,seconduser) Whenever i am trying to create a new thread between 2 users i am successfully getting it: for example my first user is root and second user is rusker. WebSocket HANDSHAKING /profile [127.0.0.1:35432] WebSocket CONNECT /profile [127.0.0.1:35432] connected {'type': 'websocket.connect'} received {'type': 'websocket.receive', … -
Issue on Updating a record in Django crispy Form
The issue is while editing the record its give DoesNotExist at /4/ > views.py from django.shortcuts import render,redirect from .forms import StudentForm,StudentForm_Timeline from .models import Student_details,Student_details_Timeline from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.contrib import messages from django.http import Http404 # Create your views here. # for student details @login_required(login_url='login') def student_list(request): student_details = Student_details.objects.all().order_by('id') paginator = Paginator(student_details,3,orphans =1) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'page_obj' : page_obj} return render(request, 'dashboard/student_list.html',context) @login_required(login_url='login') def student_form(request,id=0): if request.method == 'POST': if id == 0: form_student = StudentForm(request.POST) else: student = Student_details.objects.get(pk=id) form_student = StudentForm(request.POST,instance=student) messages.info(request,'Record Updated Successfully!') if form_student.is_valid(): form_student.save(force_update=True) return redirect('student') else: if id == 0: form_student = StudentForm() else: student = Student_details.objects.get(pk=id) form_student = StudentForm(instance = student) context = {'form_student': form_student} return render(request, 'dashboard/student_form.html',context) def student_delete(request,id): student = Student_details.objects.get(pk=id) student.delete() messages.info(request,'Record Deleted!') return redirect('list') # for student timeline @login_required(login_url='login') def timeline_list(request): student_timeline = Student_details_Timeline.objects.all().order_by('id') paginator = Paginator(student_timeline,5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'page_obj' : page_obj} return render(request, 'dashboard/timeline_list.html',context) @login_required(login_url='login') def timeline_form(request,id=0): if request.method == 'POST': if id == 0: form_timeline = StudentForm_Timeline(request.POST) else: student = Student_details_Timeline.objects.get(pk=id) form_timeline = StudentForm_Timeline(request.POST,instance=student) messages.info(request,'Record Updated Successfully!') if form_timeline.is_valid(): form_timeline.save(force_update = True) return redirect('timeline') else: if id == … -
How to stop django-html formatting to one line with tags
When I save my django-html file the following changes occur in auto formatting. {% extends 'base.html' %} {% block content %} {% if dice %} {% for die in dice %} <img src="{{die.image.url}}" alt="{{die.name}}" /> {% endfor %} {% endif %} {% endblock %} I want to have something like the following instead... {% extends 'base.html' %} {% block content %} {% if dice %} {% for die in dice %} <img src="{{die.image.url}}" alt="{{die.name}}" /> {% endfor %} {% endif %} {% endblock %} I have Beautify installed and my settings are as follows... "emmet.includeLanguages": { "javascript": "javascriptreact", "django-html": "html" }, "files.associations": { "**/*.html": "html", "**/templates/*/*.html": "django-html", "**/templates/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "beautify.language": { "html": ["htm", "html", "django-html"] }, -
Need help in Django templates
So I have a list named counts and it has a method times_used. I cannot use the method on the counts but it can be only used on each item in the list counts. The problem now is I cannot use counts[0].times_used in html template as it shows the error of not parsing. So I have used {% for count in counts %} <td>{{ count.times_used }}</td> {% endfor %} The problem here is all count.times_used is displayed for every item in counts. I want the count to be displayed only once per loop based on loop number (like counts[0],counts[1]....). How can I do this? -
django admin custom middleware password reset confirm issue
Code for Cutom Login Middleware: class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): modulename = view_func.__module__ user = request.user #Check whether the user is logged in or not if user.is_authenticated: if user.role_id == "3": if modulename == "user.adminViews": pass elif modulename == "user.adminViews" or modulename == "django.views.static": pass else: return redirect("home") else: return redirect("login") else: headers = request.META urlCheck = request.path in set({reverse("login"), reverse("doLogin"), reverse("schema"),reverse('password_reset'),reverse('password_reset_confirm',args=(uid64,token)),reverse('password_reset_complete')}) if headers.get('HTTP_TOKEN') or urlCheck or modulename == 'django.views.static': pass else: return redirect("login") Urls i have like : path("password_reset/", adminViews.password_reset_request, name="password_reset"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_confirm.html"), name='password_reset_confirm'), path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), After thi i am getting the mail where i am getting the password reset link like : http://127.0.0.1:8000/reset/MQ/advtup-241878a4d46ab73c5d381bf194fea697/ But when i click on this link it returning me the error like NameError at /reset/MQ/advtup-241878a4d46ab73c5d381bf194fea697/ name 'uid64' is not defined when i remove the ,reverse('password_reset_confirm',args=(uid64,token)) from my custom middleware .then it is redirecting me to login page instead of password changes screen can anyone please help me related this ?? i am stuck here . -
Pagination problems with filtering objects in Django
I'm trying to add the pagination functionality on my project that has a plog section. On this project I have different types of page that needs to display some content and to be more efficient I've mad a single model that hold all types of pages. On the page section I want to display just the pages that has the blog_post=True and apply a pagination. I've tried that on my class based view but the paginator is not working. It show me correct number of post per page, is showing the pagination buttons but when I try to acces another page, for example next page it give an error like this, but on the url I know that should display me something like blog/?page=2 but it displays me this "http://localhost:8000/blog/?page=%3Cbound%20method%20Page.next_page_number%20of%20%3CPage%201%20of%202%3E%3E" Class based view class BlogListView(generic.ListView, MultipleObjectMixin): model = Page template_name = 'pages/blog_list.html' paginate_by = 1 def get_queryset(self): return Page.objects.filter(blog_post=True).order_by('-created_dt') Models.py class Page(models.Model): class Meta: ordering = ['slug'] blog_post = models.BooleanField(_("Blog Post"), blank=False, default=False) title = models.CharField(_("Title"), blank=True, max_length=100, unique=True) slug = models.SlugField(_("Slug"), unique=True, max_length=100, blank=True, null=False) breadcrumb_title = models.CharField( _("Breadcrumb Title"), blank=True, max_length=100, null=False, default='') text = MarkdownxField(_("Text"), blank=True, null=False) description = models.TextField( _("Meta Description"), blank=True, null=False, default='') keywords = … -
Run Script inside Migration file - django
I have generated an empty migration file. from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0049_auto_20201125____'), ] operations = [ ] My goal is to run a script to update the username column of the table User if the username is equal to None. I have to generate a unique username and use it for the update. -
how to map nested json data in react js
how to map one nested json data in react js example i want to display the product images that i recived from api export class Planview extends Component{ constructor() { super(); this.state = { package: [], }; } componentDidMount() { const ProdID = this.props.match.params.ProductID fetch(`http://127.0.0.1:8000/api/plan/${ProdID}/`) .then(response => response.json()) .then(responseData => { this.setState({ package: responseData }); }) .catch(error => { console.log('Error fetching and parsing data', error); }); } render(){ return(<> <div className="container mar" > <h1 className="my-4">{this.state.package.title}</h1> <div className="row"> <div className="col-md-offset-2"> <div className="row" id="gradient"> <div className="col-md-6 img-responsive"> <img className ="img-main img" src={"http://127.0.0.1:8000"+this.state.package.thumbnail} alt="main" fluid ="True"/> </div> <div className="col-md-6" id="overview"> <h4>{this.state.package.code}</h4> <h5><small> {this.state.package.created_at}</small></h5 </div> <div className="row mt-4"> <h3><small></small></h3> <div className="row"> { this.state.package.image.map(function (person, index) { return ( <div className="col" key={index}> <img className={person.image} src="" alt="1"/> </div> )})} </div> </div> </div> <div className="row"> <h3 className="my-4">{this.state.package.description}</h3> </div> </div> </div> </div> </> ); } } export default Planview; and my json is like {id: 1, image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},…], title: "sample",…} code: "MAG0001" created_at: "2020-11-23" description: "college book" details: {age: 31, city: "New York", name: "John"} id: 1 image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},…] slug: "sample" thumbnail: "/media/plan_images/900-square-feet-home-plan.jpg" title: "sample" from the above json i want to display the image from the field image array it contains multiple images and also … -
Python Django heroku error “! [remote rejected] master -> master (pre-receive hook declined)” [closed]
Please help me....... Whenever I type command: git push heroku master $ git push heroku master Enumerating objects: 10320, done. Counting objects: 100% (10320/10320), done. Delta compression using up to 4 threads Compressing objects: 100% (6444/6444), done. Writing objects: 100% (10320/10320), 15.12 MiB | 4.10 MiB/s, done. Total 10320 (delta 2785), reused 10299 (delta 2778) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python-3.8.2) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: bb01b6d148aaa616f56e755b64cb0b783740d38c remote: ! remote: ! We have detected that you have triggered a build from source code with version bb01b6d148aaa616f56e755b64cb0b783740d38c remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku :main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: … -
AttributeError at /upload_to_vimeo/ 'TypeError' object has no attribute 'message'
while uploading videos to vimeo it throws this error following are codes views def upload_to_vimeo(request): token = 'xxxxx' if request.method == 'POST': form = VideoUploadForm(request.POST, request.FILES) if form.is_valid(): v = vimeo.VimeoClient( token=token, ) v.upload(request.FILES['video_file']) return HttpResponseRedirect(request.META.get("HTTP_REFERER")) else: form = VideoUploadForm() return render(request, 'forms/video_upload_form.html', {'form': form}) template <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="video_file"> <input type="submit" class="button inline-block bg-theme-1 text-white mt-5" value="Upload"> </form> Traceback: File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in __perform_tus_upload 143. with io.open(filename, 'rb') as fs: During handling of the above exception (expected str, bytes or os.PathLike object, not TemporaryUploadedFile), another exception occurred: File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/biju/Documents/mtenant/client_admin/views.py" in upload_to_vimeo 787. v.upload(request.FILES['video_file']) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in upload 71. return self.__perform_tus_upload(filename, attempt, chunk_size=chunk_size) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in __perform_tus_upload 152. raise exceptions.VideoUploadFailure( File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in init 93. super().init(response, message) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in init 30. self.message = self.__get_message(response) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in __get_message 23. message = getattr(response, 'message') Exception Type: AttributeError at /upload_to_vimeo/ Exception Value: 'TypeError' object has no attribute 'message' -
Saving dynamically added text box to database
First here is my view: def price_save(request): remarks = request.POST.get("remarks") current_user = request.user pah = PAH(remarks=remarks, created_by=current_user) pah.save() item1 = request.POST.getlist("item_code[]") item2 = request.POST.getlist("item_description[]") item3 = request.POST.getlist("uom[]") for item in item1: item_price = PAR(transaction_id=pah, item_code=item, item_description=item2, uom=item3) item_price.save() return HttpResponse("Saved!") with this I can save multiple rows with different values on item_code and same transaction id, but I dont know how to add item_description and uom in the for loop. -
How to foreign key to a foreign key
In class Model, brand is foreign key from Brand. In class Car, how do I foreign key the brand in class Brand? class Brand(models.Model): brand = models.CharField(max_length=200) def __str__(self): return self.brand class Color(models.Model): color= models.CharField(max_length=200) def __str__(self): return self.color class Model(models.Model): brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) model = models.CharField(max_length=200) def __str__(self): return self.model class Car(models.Model): brand=models.ForeignKey(Brand,null=True,on_delete=models.CASCADE)#it is wrong here, how do i fix it? model=models.ForeignKey(Model,on_delete=models.CASCADE) plate_number=models.CharField(max_length=200) -
Need help using placeholders for auth_views in django
I created a forgot password functionality using django.contrib.auth.views which is working fine. However the styling does not go with the rest of the site. I want to use only placeholders for the form fields. But since I am using the mentioned view, i don't know how. I want to remove the Email label here and write that as a placeholder This is the general theme of the site: For the login and register pages, I am mentioning the fields separately as shown in the figure: If i try do that for my forgot-password page, I get this result with no visible fields. If I try using form.password1 and form.password2, it doesn't work and I don't get the form fields at all. Here i use only the form option. I want to have the labels as placeholders(no labels). And the other stuff removed. Here are the views used in the urls.py file: Is the view using the second form? Also is there an option for a redirect here so I can just redirect my users to login page instead of a separate page? please help -
how to set djang logger to send email and save in file on AWS lightsail
Based on this SO question, I'm trying to implement error logging for my django project which is deployed on aws lightsail. my settings.py: DEBUG = False ALLOWED_HOSTS = ['XX.XXX.XXX.XXX'] # Email config EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ADMINS = ( ('myname', 'my email'), ) MANAGERS = ADMINS LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, }, } I user the logger in one of my apps' views.py as following: import logging def register(request): logger = logging.getLogger(__name__) ... if some_condition: logger.error('Something went wrong!') def mylogin(request): logger = logging.getLogger(__name__) if some_condition: logger.error('Something went wrong!') but I get no email at all. In addition to this, when I set file handler, my site gives internal error and don't come up at all. any idea how to do it? I need error logs to check the source of … -
Django returns only default image URL
I am new to Django and building a simple social media type app for adding and viewing posts. I am using admin side to upload profile images for users and it works well. I am yet to create a frontend to upload profile images. I am using PostgreSQL and I can query to see the correct URLs being saved in the table for profile images. But when I try to fetch these images and render, the default image (set in models.py) always renders. I am able to open the right images from admin side but Django only returns the default image. My frontend has Javascript in which I am using fetch API to get URLs of profile images. It works well except it returns only the default image. Please help me find out where I am going wrong or why only 'defaultpp.jpg' always shows up. I have tried using print statements in models.py and views.py and only see the URL for 'defaultpp.jpg' being returned. models.py def user_directory_path(instance, filename): return f'{instance.profile_user.id}/{filename}' class User(AbstractUser): def __str__(self): return f"User ID: {self.id} Username: {self.username}" class UserProfile(models.Model): profile_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) profile_picture = models.ImageField(upload_to = user_directory_path, blank=True, null=True, default='defaultpp.jpg') def __str__(self): return f"User: {self.profile_user} …