Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the avg time between dates on 2 separated querysets
I have a parking place spot app finder built in Django and Flutter, and I want to make an API call where I can get the average time of all reservations done until today, being the average time (end_time - init_time) / total_reservations I have 2 querysets, one for all the init_time and the other for all the end_time whick are the following: qs1 = Reservation.objects.values('init_time_reservation') qs2 = Reservation.objects.values('end_time_reservation') Is there a way to make that? I'm using Django for all my backend. -
Gunicorn HTTPs certificate and keys
To use ssl with django I use the following command: python3 manage.py runsslserver xx.8x.x3.x4:443 --certificate /etc/letsencrypt/live/callservps.online/fullchain.pem --key /etc/letsencrypt/live/callserv.com/privkey.pem To run gunicorn with that certificate and key: gunicorn --bind xx.8x.x3.x4:443:443 -certfile=/etc/letsencrypt/live/callserv.online/fullchain.pem -keyfile=/etc/letsencrypt/live/callserv.online/privkey.pem callservps.wsgi But, it give me error. Can't connect to (xx.8x.x3.x4:443:443) I think the problem is that the certificate and the key have a .pem extension. But I'm not sure how to implement this correctly to run gunicorn with https and those certificates and keys -
Django admin super_user and normal user permissions
I made a view to show all the Transactions model in the admin page. So basically i added a button in admin page which will redirect me to a custom html view with all Transactions . my views.py def pdfs(request, *args, **kwargs): transactions = Transaction.objects.all() template_path = 'report.html' context = {"transactions":transactions} response = HttpResponse(content_type='Application/pdf') response['Content-Disposition'] = 'filename="reportss.pdf' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('we had some errors' + html ) return response models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11) group = models.OneToOneField(Group,on_delete=models.CASCADE,null=True) def __str__(self): return str(self.chp_reference) @property def print_pdf(self): if self.complete: view_link = reverse('pdfss') mark_safe_param = '<a href= {} target="_blank" >Print Report</a>'.format(view_link) return mark_safe(mark_safe_param) return 'Insufficient Info.' and here is my html but i will keep it short {% for transaction in transactions %} {% if transaction.complete %} <th style="color:#3531FF">Report For Tenant ( {{ transaction.chp_reference }} )</span> <tr> <td class="tg-0pky" colspan="9">CHP Reference</td> <td class="tg-0pky" colspan="3">{{transaction.chp_reference}}</td> </tr> <tr> <td class="tg-0pky" colspan="9">Rent Effective From (dd/mm/yyyy)</td> <td class="tg-0pky" colspan="3">{{transaction.rent_effective_date}}</td> </tr> <tr> <td class="tg-0lax" colspan="9">CRA Fortnightly Rates valid for 6 months from</td> <td class="tg-0lax" colspan="3">{{transaction.cra_rate_from}}</td><hr> </tr> <tr> <td class="tg-0lax" colspan="9">Market Rent of the Property</td> <td … -
Create last seen for user in django 2.2 and check if user online or not
ajax request every 1 min update user last seen if last seen > 3min : user is offline and display timesince if last seen < 3min : user is online and display as online -
Django crispy forms inline label and input field
I have a django ModelForm containing 3 fields: name, lastname, email. What I want is to adjust the crispy form to have each field along with it's label in one line, so the form will look like this: Name: <input name> Lastname: <input lastname> Email: <input email> <button Submit> I tried with FormHelper and Layout and bootstrap inline attribute but all I achieved was having all elements in the form in one line. I'm really bad at frontend and I've been stuck for hours with such relatively simple thing. I would appreciate any help. -
Django login with cognito
Login function takes request and user (with type django.contrib.auth.models.User). But pycognito.authenticate gives return value of pycognito.UserObj type. from django.contrib.auth import authenticate, login, logout, get_user_model,models from pycognito import Cognito u = Cognito(user_pool_id='',client_id='',client_secret="",username) u.authenticate(password=password) user = u.get_user(attr_map={"given_name":"first_name","family_name":"last_name"}) login(request, user) -
Proper way of handling two forms on the same page in Django with one having a Foreign Key
In the database I'm using, the general information on a user is stored in one table, then additional information is stored in another table with the entry linked by a ForeignKey. I've been trying to implement this as a form in Django, so that I can take the general information on part of the page with one model form, and if they select to fill out the additional information the next form appears on the same page using jQuery. I've been running into trouble, finding a proper way to submit both of these forms at the same time with Django without breaking the built-in browser form validation. I'm new to Django, and would prefer to use as few external libraries to solve my problem. Thank you in advance. -
How to make Python programme for making journal entries in books of account [closed]
As I'm a student of commerce faculty but I love coding (mostly in python) so I thought of making a software which will help to journalise the entry in the books of account. So in want your recommendations and help to make it. strong textAnd alsonif anyone know about django-accouting plz tell me more about it. -
Django, saving FK for formset
I have this model: class OrderItems(models.Model): ID = models.AutoField(primary_key=True) Item = models.ForeignKey('Products', on_delete=models.DO_NOTHING) Quantity = models.IntegerField('Quantity') Price = models.DecimalField('Price', max_digits=10, decimal_places=2) OrderNo = models.ForeignKey('Orders', on_delete=models.DO_NOTHING) def __str__(self): return str(self.ID) and created a formset because I have multiple items to save but I need to save the FK from OroderNo and does this in the view: instances = Formset.save(commit=False) for instance in instances: instance.OrderNo = edit_order_id instance.save() but the forms will not be saved I can see that rest of the values are filled out of the form and form errors are empty. Did I missed something? regards Christopher. -
Hi, I use Django and I'd like to know How to avoid return to a Questionarie after sending it? Thank u so much
After I click on the button to send my Form (when I make a POST request), I want the users to not be able to return to the Form. Any Idea is Welcome. Thank u so much :) -
Django: Could not resolve URL for hyperlinked relationship using view name
Adding an entry to color works but adding one to temperature trows: Could not resolve URL for hyperlinked relationship using view name "light_analysis:temperature-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field I tried several options using namespaces and things like that. I have only defined the temperature model. Nothing else from it. urls.py (project) ... router = routers.DefaultRouter() urlpatterns = [ ... path('', include('light_analysis.urls')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] urls.py (app) from django.urls import include, path from . import views from something_web.urls import router router.register(r'light', views.LightViewSet) urlpatterns = [ path('', include(router.urls)), ] models.py ... class Light(models.Model): color_id = models.ForeignKey(Color, on_delete=models.CASCADE) temperature = models.CharField(max_length=63) temperature_id = models.ForeignKey(Temperature, on_delete=models.CASCADE) views.py from rest_framework import viewsets from common.models import Light from .serializers import LightSerializer class LightViewSet(viewsets.ModelViewSet): queryset = Light.objects.all() serializer_class = LightSerializer serializers.py from rest_framework import serializers from common.models import Light class LightSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Light fields = '__all__' -
Django: Adding review/comment form to get_context_data
I want to add a review/comment form to my post detail view so users can add reviews/comments to the post. I have created a model for reviews/comments and I can display them on a page but for now, you can add comments just from the Django administration(admin panel)but I want that any user can add a comment through the form. So my question is how can I include a from inside my detail view. models.py class Reviews(models.Model): recept = models.ForeignKey( Recept, related_name="reviews", on_delete=models.CASCADE) user = models.ForeignKey( User, related_name="reviews", on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) stars = models.IntegerField() datum = models.DateTimeField(default=timezone.now) views.py class PostDetailView(DetailView): model = Recept def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) # graba recept na katerm smo get_recept = get_object_or_404(Recept, id=self.kwargs['pk']) fav = bool if get_recept.favorites.filter(id=self.request.user.id).exists(): fav = True total_likes = get_recept.total_likes() total_likes2 = get_recept.total_likes2() # pokliče functions liked = False if get_recept.likes.filter(id=self.request.user.id).exists(): liked = True if get_recept.likes.exists(): last_like = get_recept.last_like() context['last_like'] = last_like else: context['last_like'] = 0 context['total_likes'] = total_likes context['total_likes2'] = total_likes2 context['liked'] = liked context['fav'] = fav return context forms.py class CommentForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'rows': '4', })) class Meta: model = Reviews fields = ('content',) I have watched some tutorials on youtube but can't find a … -
django data empty ajax post request
I'm using ajax to send data to my view, the goal is to post comments without refreshing the page the problem is that the form always returns false when checking if valid or not, I cant find the problem hope you can help me when i submit the form it return result:"" because the form is invalid so I printed comment_form.errors and it looks like the data is empty <ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li><li>question<ul class="errorlist"><li>This field is required.</li></ul></li></ul> my View def question_detail(request, slug): question = get_object_or_404(Question, slug=slug) allcomments = question.comments.all() comment_form = CommentCreateForm() return render(request, 'question/question_detail.html', {'question': question, 'form': comment_form, 'comments': allcomments}) def add_comment(request): if request.is_ajax() and request.method == 'POST': comment_form = CommentCreateForm(data=request.POST) print(comment_form.is_valid()) if comment_form.is_valid(): print('hi') user_comment = comment_form.save(commit=False) result = comment_form.cleaned_data.get('content') user = request.user user_comment.author = user user_comment.save() return JsonResponse({'result': result, 'user': user.username}) else: print('anything') return JsonResponse({"result": ''}) my template <form id="commentform" data-question="{{question.slug}}" class="commentform" method="POST"> <legend class="border-bottom fw-bold">Add a Comment</legend> {% csrf_token %} <select name="question" id="id_question" class="d-none"> <option value="{{question.id}}" selected="{{question.id}}"></option> </select> <label>{{form.parent.label}}</label> {{form.parent}} {{form.content}} <button type="submit" value="commentform" id="newcomment" class="newcomment btn btn-primary col-12 mt-1">Post</button> </form> $(document).on('click', '#newcomment',' #newcommentinner', function(e){ e.preventDefault(); let button = $(this).attr("value"); // let slug = $('#commentform').attr("data-question") let csrftoken = $('[name="csrfmiddlewaretoken"]').val(); // let patch = "{% … -
Why Django select_related is not using my custom model manager?
Please see the example below: class ModelBManager(models.Manager): def get_queryset(self): return self.super().get_queryset().annotate(foo=Value("bar", output_field=models.CharField()) class ModelB(models.Model): objects = ModelBManager() class ModelC(models.Model): z = models.ForeignKey(ModelB) c = ModelC.objects.select_related('z').get(pk=42) print(c.z.foo) # model has no attribute foo ModelBManager is never used in this sitation, is this intended ? I cannot find any info on this in the doc. Thanks, -
How to access the files present in the MEDIA_ROOT in Django
I have a file named "user_001.txt" in the MEDIA_ROOT directory. I am trying to get the file name from a View and print it on the console. -
How can customize django filter_horizontal left side list?
Basically i want if suppose some items selected then select items not showing in left side avilable list for one object. But i want this for all objects. -
How to move the product details to a new component when clicked from product list component in angular
I am currently trying to develop an Angular and Django shopping application. I have the products coming through from the Django API into the angular products list component but I want to be able to click a product and view the details of that product in a new component. What I currently have is the list component and when you click a product it will display the details on the same component but I want to replace the list view with the details of the product the user clicks on a specific product. My Angular project structure is as follows: App Module > Main Module > Product Details Component, Products List Component > Product Item Component I am new to angular so if this looks like bad a project Structure I'm sorry! Here is the code: product-list.component.ts import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { CookieService } from 'ngx-cookie-service'; import { ApiService } from '../../api.service'; import { Product } from '../../models/Product'; import { Router } from '@angular/router'; @Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit { productList: Product[] = []; selectedProduct = null; constructor( private cookieService: CookieService, private apiService: ApiService, private … -
Email conflict while login by different socials
I have python-django backend, that allows u to sign in through fb, apple, email, google. My email field is unique, so I can't have more than one user with single email. When user sign in with socials I take his email and create new user. Problem is, if u have two socials with single email, u can't use both of them to sign in. It works like: We have Facebook and appleId with same email Sign in with apple -> I create user with appleId, name, email -> user press logout -> user press sign in with Facebook -> I can't create new user because I have that email in db already. So the question is, what should I do and where I can find examples of it. Details: I have custom Django User and I have to take email in any case. I can't use Django-social. I think on the last step I should give user profile, that was made in second step, but I don't know how to google this problem and how its done common practice -
How to retract objects by date
I'm trying to retract lessons which are/were held during the given dates via raw sql(I know,that's better done by ORM,but I need to use sql),but the query does't work(doesn't give any data) though in sql server itself the query works here is my function in views: def profile(request): if request.method == 'POST': fromdate = request.POST.get('from') todate = request.POST.get('to') cursordate = connection.cursor() cursordate.execute( 'SELECT * FROM Lesson WHERE (StartDateTime BETWEEN Convert(datetime, %s, 120) AND Convert(datetime, %s, 120))', [fromdate, todate]) data1 = dictfetchall(cursordate) return render(request,'personal.html',{'data1':data1,'fromdate':fromdate,'todate':todate}) else: cursor1 = connection.cursor() cursor1.execute('SELECT * FROM Lesson') data1 = dictfetchall(cursor1) return render(request, 'personal.html', {'data1':data1}) and here is the template: <form method="POST" class="container mb-5"> {% csrf_token %} <label for="inputDate">Enter the date:</label> <div class="row"> <div class="col-3"> <div class="row"> <div class="col-1 mr-2">From:</div> <input class="col-10" type="date" class="form-control" name="from"> </div> </div> <div class="col-3 ml-3"> <div class="row"> <div class="col-1 mr-3">To:</div> <input class="col-10" type="date" class="form-control" name="to"> </div> </div> <div class="col-4"> <input type="submit" value="search"> </div> </div> </form> {% for lesson in data1 %} {{lesson.Name}} {% endfor %} I checked on the website and in sql server the same dates, sql server retracts lessons, django does not Can't figure out where the problem lies as the query is absolutely the same... -
How to use send_mass_mail() by gettting data from serializer for a DRF API
I am trying to make a django rest framework Api to send mail to multiple people. Here's my model.py from django.db import models # Create your models here. class EmailRecipients(models.Model): recipient_email= models.CharField(max_length=100) def __str__(self): return self.recipient_email And a serializer for the same in serializers.py from rest_framework import serializers from .models import EmailRecipients class EmailRecipientsSerializer(serializers.ModelSerializer): class Meta: model = EmailRecipients fields = '__all__' In my apiviews.py I have a view for displaying and posting a list of recipient emails But i want to define a function that is capable of getting this list and using the send_mass_mail() method in django to send it to all the above. from .models import EmailRecipients from rest_framework import generics from .serializers import EmailRecipientsSerializer class EmailRecipientList(generics.ListCreateAPIView): queryset= EmailRecipients.objects.all() serializer_class = EmailRecipientsSerializer def sendmail(request): serializer = EmailRecipientsSerializer(data=request.data) email = 'abcd@gmail.com' if serializer.is_valid(): serializer.save() email = serializer.data['recipient_email'] subject = 'Welcome to the microservice' message = 'Try more' recepient = email send_mail(subject,message,EMAIL_HOST_USER,[recepient],fail_silently=False) return HttpResponse('sent successfully') I tried to code for sending to a single recipient but this doesnt work either. Also I'm not sure what serializer = EmailRecipientsSerializer(data=request.data) would contain. Please help, just getting started with DRF. -
is there a method to display fields in the same div in django forms?
in my forms.py class Form(forms.ModelForm): check = forms.BooleanField( label='Actif', required=False, widget=forms.CheckboxInput( attrs={'class': 'styled'} ), initial=True ) check_2 = forms.BooleanField( label='Actif_2', required=False, widget=forms.CheckboxInput( attrs={'class': 'styled'} ), initial=True ) in models.py class myModel(models.Model): check = models.BooleanField(default='True') check_2 = models.BooleanField(default='True') in html : <div class="panel-body"> <form action="." method="post"> {% csrf_token %} {% crispy form %} </form> </div> like this i have in output form : # check # check_2 i wanto to display "check" and "check_2" in the same div : check in the left and check_2 in the right : # check # check_2 -
tzinfo argument must be None or of a tzinfo subclass, not type 'datetime.datetime'
I am building a BlogPost Webapp and I am stuck on an Error. When i try to check browser then it is keep showing tzinfo argument must be None or of a tzinfo subclass, not type 'datetime.datetime' models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') time = models.DateTimeField(auto_now_add=True) @property def age(self): current_datetime = datetime.now(tz=timezone.now()) return (current_datetime - self.time).days I have no idea, What is causing that Error. Any help would be Appreciated. Thank You in Advance -
Django filter ManyToMany with contains
I'm creating the typical search field for a WebPage. I've been able to filter by all the fields but not by the ManyToMany field. It's giving me the following error. Related Field got invalid lookup: icontains I have the next two models class category(models.Model): name = models.CharField(max_length = 20) class image(models.Model): title = models.CharField(max_length = 20) image = models.ImageField(upload_to = "galery") description = models.TextField(max_length=60, null = True, blank = True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) categories = models.ManyToManyField(category) And the next filtering in my Views.py class searchResultsView(ListView): model = blog template_name = '...' def get_context_data(self, **kwargs): query = self.request.GET.get('q') context = super(searchResultsView, self).get_context_data(**kwargs) context['images'] = image.objects.filter(Q(title__icontains = query) | (Q(categories__icontains = query) return context How could i filter the ManyToMany field with contains/icontains? Thanks in advance -
How to filter many to many field in django form
I have a model Election that has a 'candidates' field which is in many to many relationship with the Candidate model and a 'region' field which has one to many relationship with the Region model. Also Candidate model also has a region field which also has one to many relationship with the Region model. Now I created a model form of model Election. My problem is how can I filter candidates which is specific to a particular region Here are my models and form class Region(models.Model): region_name = models.CharField(max_length=200, null=True) region_id = models.CharField(max_length=20, null=True, unique=True) def __str__(self): return self.region_name class Candidate(models.Model): region = models.ForeignKey(Region, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200, null=True) party_name = models.CharField(max_length=200, null=True) candidate_id = models.CharField(max_length=10, null=True, unique=True) def __str__(self): return self.name class Election(models.Model): admin = models.ForeignKey(Admin, null=True, on_delete=models.SET_NULL) region_name = models.ForeignKey(Region, null=True, on_delete=models.SET_NULL) region_id = models.CharField(max_length=200, null=True) date_created = models.DateField(null=True) candidates = models.ManyToManyField(Candidate) winner = models.CharField(max_length=200, blank=True) class NewElectionForm(forms.ModelForm): class Meta: model = Election exclude = ['winner'] def __init__ (self, *args, **kwargs): super(NewElectionForm, self).__init__(*args, **kwargs) self.fields["candidates"].widget = forms.widgets.CheckboxSelectMultiple() #below query is for testing #region = Region.objects.get(region_name='Mumbai') self.fields["candidates"].queryset = region.candidate_set.all() Every region has a admin which is going to post this form. Since region_name is variable here I cannot … -
How to display Json items in Django templates?
I want to display my Json data in a table form. But when I try, it looks same with json format. my json data {'Financial Ratios': 'Ratios', 'Unnamed: 1': 'Formula ', 'Unnamed: 2': '2013', 'Unnamed: 3': 2012.0, 'Unnamed: 4': 'Point', 'Unnamed: 5': 'Max Score for the Ratio', 'Unnamed: 6': 'Weighted Score'} {'Financial Ratios': 'Activity Ratios', 'Unnamed: 1': None, 'Unnamed: 2': None, 'Unnamed: 3': None, 'Unnamed: 4': None, 'Unnamed: 5': None, 'Unnamed: 6': None} {'Financial Ratios': 'Total Asset Turnover Ratio', 'Unnamed: 1': ' S ....... views.py def test_view(request): # Financial Ratios fr = pd.read_excel('media/test.xlsx', usecols='A:G', skiprows=lambda x: x < 0 or x > 42, sheet_name='Scoring') json_fr = fr.to_json() ... data = json.loads(json_fr) index_key_mapping = {index: key for index, key in enumerate(data.keys())} formated_data = [{ index_key_mapping[index]: value for index, value in enumerate(ord_pair) } for ord_pair in zip(*[ dictionary.values() for key, dictionary in data.items() ])] context = { 'formated_data': formated_data, } return render(request, 'json_test.html', context) template.html* {% for item in formated_data %} <li> {{ item }} </li> {% endfor %} For example, I want "Financial Ratios" to be a column name and "Ratios" and "Activity Ratios" in the data to be the elements (td) of this column but I don't know how to …