Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to process multiple Objects at once (using Django)
I used Ajax to send data (list type -> ex: ['4', '6', '10', '11']) to 'study/add_teacher' url page. So, it was successful until I got the data from the page. In the next step, problem is not resolved, The data of request.POST.getlist obtained through Ajax are 'id' of Student model. So I want to add the currently logged in user name (request.user.first_name) to the teacher field of these objects. It looks like views.py needs to be edited, is there a way to process objects all at once? [urls.py] path('study/add_teacher/', views.add_teacher, name='add_teacher'), [views.py] def add_teacher(request): if request.method == 'POST': ids = request.POST.getlist('chkArray') ---> chkArrary = ['4', '6', '10', '11'] Student.objects.filter(id__in=ids).update(teacher=request.user.first_name) return HttpResponseRedirect(f'/research/supporting/') -
a different chat appearance/look for both side
I'm trying to implement a chat room with websockets, everything works fine but the problem is how can I differentiate the look for both sides, I want the current user to have a blue message background and other participants have different colors, for example black, how can I do that, any suggestions will be appreciated. Here is what I got And here’s what I want it to be -
Cannot resolve keyword 'author' into field
Here is the issue.I am trying to delete the tags related to my model. I can create them but whenever i try to use HTTP DELETE on ExampleModelTags, i face with the following issue. Error: Cannot resolve keyword 'author' into field. Choices are: id, examplemodel, examplemodel_id, tag, timestamp I can't understand what is the issue, i can create them so the algorithm works. The tags can connect to their parent model . But whenever i try to do HTTP DELETE on ExampleModelTags, i get that issue. Where is the problem that i don't see? Model.py class ExampleModelTag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tag = models.CharField(max_length=35,null=True,blank=True) examplemodel = models.ForeignKey(ExampleModel, on_delete=models.CASCADE,null=True,blank=True, related_name='examplemodeltags') timestamp = models.DateTimeField(auto_now_add=True) class ExampleModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='examplemodels') examplemodel = models.CharField(unique=False,max_length=100,null=True,blank=True) timestamp = models.DateTimeField(unique=False,auto_now_add=True) Serializer.py class ExampleModelTagSerializer(serializers.ModelSerializer): class Meta: model = ExampleModelTag fields = ("id","examplemodel","tag","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs['examplemodel'].author.id != self.context['request'].user.pk: raise ValidationError('Unauthorized Request') return attrs class ExampleModelSerializer(serializers.ModelSerializer): examplemodeltags_set = ExampleModelTagSerializer(source='examplemodeltags',required=False,many=True) class Meta: model = ExampleModel fields = ("id","author","examplemodel","examplemodeltags_set","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id != self.context['request'].user.pk: raise ValidationError('Unauthorized Request') return attrs -
trigger a function after a while django python
I use django for a project. Users can make exchanges. If one user places an order with another and the second user accepts. I would like that after 24 hours if the order is not processed by the seller it is canceled. How can I do this? -
How can I make this sql query in django orm?
I have 2 tables in django. I have related_name in timeline tables. I want to implement this sql query: SELECT * FROM ( SELECT DISTINCT ON (film_id) * FROM public.lavel_timeline JOIN public.level_torrent ON public.lavel_timeline.film_id = public.lavel_torrent.id ORDER BY film_id, date DESC ) t ORDER BY date DESC I tried Torrent.objects.all().order_by('film_timeline__film_id', F('film_timeline__date') .desc(nulls_last=True)).distinct('film_timeline__film_id') I got: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON (film) "core_torren... Django 2.2 python 3, postgresql -
Heroku doesnt migrate models on Django
I just deploy my Django app to Heroku but I cant migrate my migrations to heroku. First I run : heroku run python manage.py migrate all the migrations list as OK but when I showmigrations, none of them is migrating (all blank [ ]). Then I try heroku run bash and migrate from there, everything seems ok even showmigrations from bash showing all of the migrations is working. I even manage to create a superuser. But when I open my admin page and log in with superuser it shows 'account.account' table does not exist and when I check showmigrations again all of the migrations are gone. I have been repeating this migration over and over and still can't figure this out. Anyone know what I am doing wrong here? -
How to print a receipt using a template on the site?
I am developing a site in django, but my knowledge of javascript and python is still very mediocre. On the site, users enter some data, which is subsequently stored in the database, and I need to add to the site the function of printing data from the database based on the template. In the future, it may be necessary to give users the ability to change this template to suit their needs (and so that each user has its template applied) On other sites, I saw how through TinyMCE on the site there was a form in which a template for printing was written, (with tags in those places where it was necessary to substitute data), with the possibility of changing it, and when you click on the "print" button, substitute data from the database into the appropriate fields in this template. I can write a print page based on the jinja template engine, and make a separate view for it, but I do not understand how I can send data from one page to another (on which only print will be typeset), and how to edit it all. -
Method Not Allowed: /registration/ [10/Oct/2021 15:54:09] "POST /registration/ HTTP/1.1" 405 0
urls.py path( 'registration/' , views.CustomerRegistrationView.as_view( ), name="customerregistration"), views.py class CustomerRegistrationView(View): def get(self, request): form = CustomerRegistrationForm( ) return render(request, 'app/customerregistration.html', {'form' : form}) def post(self, request): form = CustomerRegistrationForm(request.post) if form.is_valid(): form.save() return render(request, 'app/customerregistration.html', { 'form' : form}) ''' html <form action="" method="post" novalidate class="shadow p-5 text-white" style="border-radius:5px; background-color: #132623;"> {% csrf_token %} {% for fm in form %} <div class="form-group mb-3"> {{fm.label_tag}} {{fm}} <small class="text-danger">{{fm.errors | striptags}}</small> </div> {% endfor%} <input type="submit" value="Submit" class="btn btn-primary"> <br> please tell me the mistake -
TypeError at /auth/jwt/refresh decode() got an unexpected keyword argument 'verify' using Djoser
I have got this error while trying to refresh a JWT with Djoser using the JWT endpoints. I need your help please. I have followed all the settings as they are in the DOCS. -
Images at cPanel is not Displaying in Django
I have deployed my Django project on a Shared Hosting. I am using subdomain for that. My Project is working fine in my localhost. And also I am able to get the media file but in my Shared Hosting, i am not able to get the media file. Shows error: Not Found The requested resource was not found on this server. My Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') And my urls.py: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) The console error is looking like this . -
Fixing No Reverse Match in a Django Project
I am getting the following error: Reverse for 'order_pdf' with arguments '('',)' not found. 1 pattern(s) tried: ['business_plan/(?P<id>[0-9]+)/pdf/$'] I am not sure exactly what is the reason for it. Here is the model: class Info(models.Model): logo = models.ImageField(default='report-cover.jpg', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) name = models.CharField(null=True, blank=True, max_length=100) Here is the views.py def order_pdf(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/pdf.html', {'info': info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="{}-Business Plan.pdf"'.format(info.businessName) weasyprint.HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '\css\\report.css')], presentational_hints=True) return response Here is the urls.py app_name = 'businessplan' urlpatterns = [ path('<str:info_id>/pdf/', order_pdf, name='order_pdf'), ] Here is the template: <a href="{% url 'businessplan:order_pdf' Info.id %}"> I have tried changing the info_id to id it didn't work. What is the reason for this error? -
how to use a media file in a django view, in other words, how do i get the address of the media file in a view
I have Included the following in my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is the model whose FileInput i have to store: class Clip(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=False) audio = models.FileField(upload_to='audio/') class Meta: db_table = 'Audio_store' My modelForm: class AudioForm(forms.ModelForm): class Meta: model = Clip fields = ['audio'] And finally the view where i need the address of this file: form = AudioForm(request.POST, request.FILES or None) try: instance = Clip.objects.get(owner=request.user) instance.delete() except Clip.DoesNotExist: instance = 0 if form.is_valid(): instance = form.save() else: return render(request, self.template, { 'form': AudioForm(), }) result = function_name("""destination of the audio file in media directory""") Now as you can see to get the value of result, i need to feed the address of the file to the function. Now i am confused what should i put in the function. i have a media directory in which i have created a subdirectory 'audio'. But i can't figure out how do i put in the exact address with the file name to this function. (This is the only way i can use this function) Please help me out here Thank You -
LEFT OUTER JOIN with 'field IS NULL' in WHERE in some cases returns no results
Today I've faced some unexplainable (for me) behavior in PostgreSQL — LEFT OUTER JOIN does not return records for main table (with nulls for joined one fields) in case the joined table fields are used in WHERE expression. To make it easier to grasp the case details, I'll provide an example. So, let's say we have 2 tables: item with some goods, and price, referring item, with prices for the goods in different years: CREATE TABLE item( id INTEGER PRIMARY KEY, name VARCHAR(50) ); CREATE TABLE price( id INTEGER PRIMARY KEY, item_id INTEGER NOT NULL, year INTEGER NOT NULL, value INTEGER NOT NULL, CONSTRAINT goods_fk FOREIGN KEY (item_id) REFERENCES item(id) ); The table item has 2 records (TV set and VCR items), and the table price has 3 records, a price for TV set in years 2000 and 2010, and a price for VCR for year 2000 only: INSERT INTO item(id, name) VALUES (1, 'TV set'), (2, 'VCR'); INSERT INTO price(id, item_id, year, value) VALUES (1, 1, 2000, 290), (2, 1, 2010, 270), (3, 2, 2000, 770); -- no price of VCR for 2010 Now let's make a LEFT OUTER JOIN query, to get prices for all items for year … -
Django Rest Framework, Docker, nginx - Base url for mediafiles
I am trying to set up my Django Rest Framework application. Unfortunately I still can't manage to get the media files url right. I tried adding the lines from this answer to my nginx configuration ending up with "Bad Request (400)": Django Rest framework swagger base url The application is running on my-domain.com. https://my-domain.com/user/ { "count": 1, "next": null, "previous": null, "results": [ { "id": "512e0f9f-f08a-4a2d-8e1d-b933a16c0a1f", "date_joined": "2021-10-10T11:41:05.077828Z", "name": "Maxine Mustermann", "user_picture": "**http://127.0.0.1:8337**/mediafiles/images/usr1.jpeg" } ] } Expected: https://my-domain.com/mediafiles/images/usr1.jpeg (Eventhough the picture can be accessed with this url) Returned: http://127.0.0.1:8337/mediafiles/images/usr1.jpeg docker-compose file: version: "3.8" services: db: image: postgres:13-alpine volumes: - postgres_data_staging:/var/lib/postgresql/data/ env_file: - ./.env.staging.db expose: - 5432 web: build: context: ./api dockerfile: Dockerfile.staging command: gunicorn config.wsgi:application --workers 3 --bind 0.0.0.0:8000 volumes: - static_volume_staging:/home/api/web/staticfiles - media_volume_staging:/home/api/web/mediafiles expose: - 8000 env_file: - ./.env.staging depends_on: - db nginx: build: ./nginx volumes: - static_volume_staging:/home/api/web/staticfiles - media_volume_staging:/home/api/web/mediafiles ports: - 8337:80 depends_on: - web volumes: postgres_data_staging: static_volume_staging: media_volume_staging: nginx.conf: upstream ae_backend { server web:8000; } server { listen 80; client_max_body_size 75M; server_name $DOMAIN www.$DOMAIN; location / { proxy_pass http://ae_backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /staticfiles/ { alias /home/api/web/staticfiles/; } location /mediafiles/ { alias /home/api/web/mediafiles/; } } Server configuration nginx/sites-enabled/my-api: server { server_name … -
Put request Set and Push in one request Django MongoEngine MongoDB
I want to send a put Request and update the Project(Document) name field and attendees field in one put request. But I don't want the full attendees of the Project(Document) to be replaced I want String Fields to be replaced with the new value and List fields to be pushed to the Array/ List. How could I achieve that? At the moment I always need multiple requests (one for every single list field) which is really tedious as my real model has much more fields to update. And I think giving the front end the full Project and controlling the list fields over there (by pushing it in the frontend) wouldn't be safe. You don't want the front end to be able to change them. I also want the timestamp to be automatically added to the Attendee if an attendee was added to the list / array. Models class Attendee(EmbeddedDocument): full_name = fields.StringField() datetime_added = fields.DateTimeField( auto_now_add=True, default=datetime.datetime.utcnow) class Project(Document): name = fields.StringField() tags = fields.ListField(fields.StringField()) attendees = fields.ListField(fields.EmbeddedDocumentField(Attendee)) Views class ProjectViewSet(viewsets.ModelViewSet): """ List all projects or create, update or delete project. """ permission_classes = [ # Set authentication # permissions.IsAuthenticated permissions.IsAdminUser # permissions.AllowAny ] lookup_field = 'id' queryset = … -
celery with Django
I am building a app and I am trying to run some tasks everyday. So I saw some answers, blogs and tutorials about using celery, So I liked the idea of using celery for doing background jobs. But I have some questions about celery :- As mentioned in Celery Documentation that after setting a celery task , I have to run a command like celery -A proj worker -l INFO which will process all the tasks and after command it will run the tasks, so my question is , I have to stop the running server to execute this command and what if I deploy Django project with celery on Heroku or Python Anywhere. Should I have to run command every time Or I can execute this command first then i can start the server ? If I have to run this command every time to perform background tasks then how is this possible when deploying to Heroku, Will celery's background tasks will remain running after executing python manage.py run server ? Why I am in doubt ? :- What I think is, When running celery -A proj worker -l INFO it will process (or Run) the tasks and I … -
render class overiding the class method in apiview
I am a bit confused I want to render HTML or JSON by checking the accept header of the client but as I have specified the default render class,it is still rendering as per render class regardless of what Accept header is class HomeView(APIView): template_name = 'blog_app/home.html' renderer_classes = [TemplateHTMLRenderer] def get(self,request): context = os.getcwd() print(request.headers['Accept']) if 'text/html'in request.headers['Accept']: return Response({'dir':context},template_name=self.template_name) else: return Response({'dir':context},content_type='json') -
No idea what SpatiaLite is, and how to get it
I'm trying to get SpatiaLite, because I need it for this https://pythonrepo.com/repo/caioariede-django-location-field--python-django-utilities I have read this, but no idea what all that stuff means. How do I install SpatiaLite on MacOS? -
FieldError at /favourites/ Cannot resolve keyword 'favpost' into field. Choices are: author, author_id
I have error FieldError at /en/account/profile/favourites/ Cannot resolve keyword 'favpost' into field. Choices are: author, author_id This spanning can be as deep as you’d like. It works backwards, too. While it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model. This example retrieves all Post objects which have at least one favPost whose user=request.user class Post(models.Model): title = models.CharField(max_length=250) excerpt = models.TextField() class favPost(models.Model): post = models.ForeignKey(Post, related_name='postfv', on_delete=models.CASCADE, default=None, blank=True) user = models.ForeignKey(User, related_name='userfv', on_delete=models.CASCADE, default=None, blank=True) vote = models.BooleanField(default=True) publish = models.DateTimeField(auto_now_add=True) def __str__(self): return self.post def favourite_list(request): new2 = Post.objects.filter( favpost__user=request.user ) return render(request, 'accounts/favourites.html', {'new': new2 } ) -
'ManyRelatedManager' object has no attribute - Django
Very new to Django - I apologise in advance for the poor description! I have two django models: class Suite(models.Model): slug = models.SlugField() client_name = models.ForeignKey(Client, blank=True, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=120) def __str__(self): return self.title def get_absolute_url(self): return reverse('courses:detail', kwargs={'slug': self.slug}) @property def lessons(self): return self.portfolioupdate_set.all().order_by('position') class PortfolioUpdate(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) suite = models.ForeignKey(Suite, on_delete=models.SET_NULL, null=True) # suite = models.ManyToManyField(Suite) position = models.IntegerField() video_url = models.CharField(max_length=200) thumbnail = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse('courses:lesson-detail', kwargs={ 'course_slug': self.suite.slug, 'lesson_slug': self.slug }) I am rendering the list of Portfolio Updates in the following way: class PortfolioUpdateListView(LoginRequiredMixin, ListView): def get(self, request, course_slug, *args, **kwargs): user = self.request.user suite = get_object_or_404(Suite, adviser__user=user, slug=course_slug) context = {'object': suite} return render(request, "courses/lesson_list.html", context) I would like to have the 'suite' field, as a ManyToManyField, rather than a ForeignKey, so that a portfolio update can relate to many suites, rather than a portfolio update relating to a single suite. When I change this in models, and try to render the page, I get 'ManyRelatedManager' object has no attribute 'slug'. Is what I have described possible, and if so how would I render this? Thanks very much in advance. -
Unable to call a class using Django
Hello I don't understand why I cannot call a class in my models using django. For instance if I do that : from myapp import models User.objects.first() I got that error : NameError : name 'User' is not defined whereas if I do that import myapp myapp.models.User.objects.first() it works I don't understand at all why I have that problem Thank you very much for your help ! -
Django set user is_active to false when creating an employee separation
I have an extended User model that is related to the employee Separation model and I would like to set that User as inactive with the SeparationCreateView. It's like when an employee leaves the company, it is recorded with this separation view and it is disabling employee access to the app automatically. class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Separation(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) Separation create view is working but it is not setting the user is_active to false class SeparationCreateView(LoginRequiredMixin, CreateView): model = Separation form_class = SeparationForm template_name = 'coreHR/separation.html' success_url = reverse_lazy('corehr:separations') def form_valid(self, form): separation = form.save(commit=False) separation.employee.user.is_active = False separation.save() return super().form_valid(form) What am I doing wrong here? Any help is highly appreciated. -
how to turn off l10N for one value
I use {% load l10n %} and it works great. But it formats Money('55652.69924091', 'USD') into 55652.70 USD, which is generally ok, but in one place i need to get 55652.6992 USD (decimal places increase to 4). I tried {% localize off %}{{ object.value }} {% endlocalize %} but no effect. I can do it with .amount, but this is ugly. -
Django change password link is not active?
I am learning an authentication in Django. Today I am stuck with this problem and I am not able to figure out how can I solve it. I want to make a form for password change. but the change form link is not active and I don't know how to fix it. here is my views.py @login_required def user_change(request): current_user = request.user form = UserProfileChange(instance = current_user) if request.method == 'POST': form = UserProfileChange(request.POST,instance = current_user) if form.is_valid(): form.save() form = UserProfileChange(instance = current_user) form = UserProfileChange(instance = current_user) return render(request, 'App_Login/change_profile.html', context={'form':form}) @login_required def pass_change(request): current_user = request.user form = PasswordChangeForm(current_user) if request.method == 'POST': form = PasswordChangeForm(current_user, data = request.POST) if form.is_valid(): form.save() return render(request, 'App_login/pass_change.html', context = {'form':form}) here is urls.py file from django.urls import path from . import views app_name = 'App_Login' urlpatterns = [ path('signup/', views.signup, name = "signup"), path('signin/', views.login_page, name = 'signin'), path('logout/' , views.logout_user, name = "logout" ), path('profile/' , views.profile, name = "profile" ), path('change-profile/' , views.user_change, name = "user_change" ), path('password/' , views.pass_change, name = "pass_change" ), ] -
I want to calculate the total price of a customer's purchase from my code in django
I am trying to calculate the total price of items when a user types in the rate and quantity of an item purchased, but I'm getting this error: "can't multiply sequence by non-int of type 'tuple'" My model is below; it includes where I'm performing the operation of getting the total price. from django.db import models from django.db.models import fields from django.db.models.deletion import CASCADE # Create your models here. class Items(models.Model): item_name = models.CharField(max_length=100) def __str__(self): return self.item_name class Payment_Method(models.Model): payed_by = models.CharField(max_length=20) def __str__(self): return self.payed_by class Daily_Sales(models.Model): customer_name = models.CharField(max_length=100) item_purchased = models.ManyToManyField(Items) quantity = models.IntegerField() rate = models.IntegerField() total_price = models.IntegerField(default=0) date_purchased = models.DateTimeField(auto_now_add=True) payment_method = models.ManyToManyField(Payment_Method) have_paid = models.BooleanField(default=False) date_paid = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Daily_Sales' def __str__(self): return self.customer_name def save(self, *args, **kwargs): self.total_price = self.rate * self.quantity super(Daily_Sales, self).save(*args, **kwargs) Thus the error; can't multiply sequence by non-int of type 'tuple'