Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
Django Paginator doesnt work properly, how can i resolve
the django paginator data I use in my project does not work properly in sorting, for example, although I have records dated 2021 in my records, when I sort by date, it only sorts records dated 2020, here is my codes: views.py; gmembers_list = gunluk.objects.all() paginator = Paginator(gmembers_list, 1000000000000000) page = request.GET.get('page') try: gmembers = paginator.page(page) except PageNotAnInteger: gmembers = paginator.page(1) except EmptyPage: gmembers = paginator.page(paginator.num_pages) return render(request, 'gunlukistakibi.html', {'gmembers': gmembers}) html for listing; <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> Günlük İş Takibi <a class="btn btn-sm btn-success" href="{% url 'gcreate' %}" style="padding: 8px; float: right; background-color: green; color: white;">EKLE</a> </div> <div class="card-body"> <div class="table-responsive "> <table class="table table-striped table-bordered text-center dataTable no-footer align-center align-middle " id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Tarih</th> <th>Ad Soyad</th> <th>Vardiya</th> <th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Açıklama&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th> <th>İncident</th> <th>Alınan</br>Aksiyon</th> <th>Ulaşılamayan</br>Ekip</th> <th>Ulaşılamayan</br>Bilgisi</th> <th>Action</th> </tr> </thead> <tbody> {% for gmember in gmembers %} <tr> <td>{{gmember.tarih|date:"d-m-Y"}}</td> <td>{%if gmember.adsoyad2 == null%} {{ gmember.adsoyad}} {%else%} {{ gmember.adsoyad}} - {{ gmember.adsoyad2}} {%endif%}</td> <td>{{ gmember.vardiya }}</td> <td>{{ gmember.aciklama }}</td> <td>{{ gmember.incident }}</td> <td>{{ gmember.alinanaksiyon }}</td> <td>{{ gmember.ulasilmayanekip }}</td> <td>{{ gmember.ulasilmayanbilgisi }}</td> <td> <a class="btn btn-sm btn-warning" href="gedit/{{ gmember.id }}"> <span class="fa fa-edit"></span> </a> <a class="btn btn-sm btn-danger" href="gdelete/{{ gmember.id }}"><span class="fa fa-trash"></span> </a> </td> </tr> -
NoReverseMatch at post when I add href link
I am building a "game" website where clues are given and individuals will make guesses. I have added home.html, new_game.html, game_detail.html, base.html, and now edit_game.html. All is working correctly to create a new, list (in home.html), and display details. Now I am adding the function to edit the game in edit_game.html. When I add the html link `Edit Game in game_detail.html, I get the error (below) when I click on any of the games in the list, which should display the game_detail page. In other words, it will not display the game_detail.html. Here is the error: NoReverseMatch at /post/2/ Reverse for 'edit_game' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/edit/$'] It is clearly passing the ID of the post. But it is not picking up the "/edit/". Here is the detail page code: <!-- templates/game_detail.html --> {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{object.title}}</h2> <p>{{ object.body }}</p> </div> <a href="{% url 'edit_game' post.pk %}">Edit Game</a> {% endblock content %} Here is the urls code: from django.urls import path from .views import ( GameListView, GameDetailView, GameCreateView, GameUpdateView, ) urlpatterns = [ path('post/<int:pk>/edit/', GameUpdateView.as_view(), name='edit_game'), path('post/<int:pk>/', GameDetailView.as_view(), name='game_detail'), path('post/new/', GameCreateView.as_view(), name='new_game'), path('', GameListView.as_view(), name='home'), ] The Views code: … -
Using Django Json field to reduce migrations issue
I am new to Django Json Field. I have been creating models and migrating them for now. Now I am introduced to Jsonfield. What I have heard is, it is the best way to mitigate the migrations issue because of jsonfield. It is because, if we had to add fields or remove fields from the model after populating the fields (if we have used other regular fields like chafield and emailfield) in production, there may arrise migration issue which we can avoid if we use jsonfield becaue we can just pass any json data with any number of fields in the jsonfield. So, is this the best way to avoid migration issue?? I am seeking expert advice here, because there is no one I can ask and that is what I have heard. It seems like this. class Example(models.Model): data = models.JSONField(null=False, default=dict) So, instead of creating two models named Contacts and Feedback for saving the data of contact form and feedback form, I can simply use this same example model and validate to accept any data of many such forms existing in the frontend. -
VS code not using auto import function?
In django project, I want to import this from django.http import httpresponse but VS code is not giving me http and httpresponse as auto import feature. I manually have to type it. Though for other module the auto import feature is working. What can be the reason of it ? I only have ABC suggestions.