Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a comment box in Django for a single page, not a collection of blogs
With the help of Google I have learnt to make a comment system for my Blogs application. But I've few other pages in a separate app and all these pages have some set of tools, I need to get comment system for all these pages as well. I modified my Blogs App code as follows and getting a error. models.py class Page(models.Model): pass #Something more needs to be done here I guess, like some sort of reference to my page class Comment(models.Model): page = models.ForeignKey(Page,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) views.py from .models import Page from .forms import CommentForm from django.shortcuts import render, get_object_or_404 def atool(request): if request.method == 'POST': page = get_object_or_404(Page) comments = page.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = page new_comment.save() else: comment_form = CommentForm() return render(request, 'atool/atool.html', {'page': page, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) else: context= {'somedata': 'data'} return render(request, 'atool/atool.html', context) admin.py from django.contrib import admin from .models import Comment @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', … -
DB credentials for Hasura on Heroku
I've deployed hasura on heroku, how can I get the DB credentials of the same. I would like to use those credentials in a django app --Thx. -
ModuleNotFoundError when trying to use mock.patch on a method
My pytest unit test keeps returning the error ModuleNotFoundError: No module name billing. Oddly enough the send_invoices method in the billing module is able to called when I remove the patch statement. Why is mock.patch unable to find the billing module and patch the method if this is the case? billing.py import pdfkit from django.template.loader import render_to_string from django.core.mail import EmailMessage from projectxapp.models import User Class Billing: #creates a pdf of invoice. Takes an invoice dictionary def create_invoice_pdf(self, invoice, user_id): #get the html of the invoice file_path ='/{}-{}.pdf'.format(user_id, invoice['billing_period']) invoice_html = render_to_string('templates/invoice.html', invoice) pdf = pdfkit.from_file(invoice_html, file_path) return file_path, pdf #sends invoice to customer def send_invoices(self, invoices): for user_id, invoice in invoices.items(): #get customers email email = User.objects.get(id=user_id).email billing_period = invoice['billing_period'] invoice_pdf = self.create_invoice_pdf(invoice, user_id) email = EmailMessage( 'Statement of credit: {}-{}'.format(user_id, billing_period), 'Attached is your statement of credit.\ This may also be viewed on your dashboard when you login.', 'no-reply@trevoe.com', [email], ).attach(invoice_pdf) email.send(fail_silently=False) return True test.py from mock import patch from projectxapp import billing @pytest.mark.django_db def test_send_invoice(): invoices = { 1: { 'transaction_processing_fee': 2.00, 'service_fee': 10.00, 'billing_period': '2020-01-02' }, 2: { 'transaction_processing_fee': 4.00, 'service_fee': 20.00, 'billing_period': '2020-01-02' } } with patch('billing.Billing().create_invoice_pdf', '/invoice.pdf') as p1: test = billing.Billing().send_invoices(invoices) assert test … -
adding detail information to django listview object in template
I have a listview in which I'm hoping to insert additional details about the object (activity duration and average power) in the same row as the link to the object detail (the best way to describe it would be that I want some detailview attributes inserted into the listview). At the moment, the best I can achieve is a separate context dictionary listed below the object_list, as shown in this screen shot: And the following is my listview: class RideDataListView(LoginRequiredMixin, ListView): model = RideData context_object_name='object_list' template_name='PMC/ridedata_list.html' def get_queryset(self): queryset = super(RideDataListView, self).get_queryset() return queryset def get_context_data(self, *args, **kwargs): model = RideData context = super(RideDataListView, self).get_context_data(*args, **kwargs) records = list(RideData.objects.all().values()) actdict2={} id=[] ap=[] actdur=[] for record in records: actdf=pd.DataFrame.from_dict(record) id.append(actdf['id'].iloc[0]) ap.append(actdf['watts'].mean()) actdur.append(str(timedelta(seconds=len(actdf['time'])))) actdf2=pd.DataFrame() actdf2['id']=id actdf2['ap']=ap actdf2['actdur']=actdur actdict2=actdf2.to_dict('records') context['actdict']=actdict2 context['actdur']=actdur return context What I haven't been able to nail down in my research is if there is a way to either a) annotate the queryset with stuff from context or b) loop through the context dictionary 'actdict' within the object_list loop (doesn't seem possible based on some attempts) or c) include individual lists (ap and actdur as additions to to query. Just curious for some additional leads to add some more object … -
I can't filter django by average
I am trying to learn django database transactions, my aim is to get the average of the price based on the month_year value, but all the values in the price column are coming from .models import Arabam from django.db.models import Sum,Avg,Count def pie_chart(request): queryset1= Arabam.objects.annotate(fiyat_ort=Avg('fiyat')).filter(marka="Skoda",model="Rapid",motor="1.6 TDI GreenTec Style ",yeni="90000.0") labels = [] data = [] for city in queryset1 labels.append(city.month_year) #x ekseni data.append(city.fiyat_ort) # y ekseni return render(request, 'verigorsellestirme.html', { 'labels': labels, 'data': data,}) -
Django-How do i get the HTML template to show data from the two models?
So i'm creating a to-do app. How do I get the html view to show the tasks? I tried to show the name of the tasks but it's blank. So far, it only shows the board name and the user who created it. Here is my code so far: Models.py class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board") name = models.CharField(max_length=200) class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField(default=False) assigned_to = models.CharField(max_length=30) views.py def board_post_detail(request, board_id): obj = get_object_or_404(Board, id=board_id) taskobj= Task.objects.filter(board=obj) context = {"object": obj, "tasks": taskobj} return render(request, 'boards/board_post_detail.html', context) board_post_detail.html {% block content %} <h1>{{ object.name}}</h1> <p> {{tasks.text}}<p> <p>Created by {{object.admin.username }}</p> {% endblock %} -
Django forms and GeoDjango LeafLets
For my application I'm trying to put locations on the map. Per location I have a latitude and a longitude in my model. Displaying these on a map is piece of cake. models.py class Toursteps(models.Model): tour = models.ForeignKey(Tour, related_name='toursteps', on_delete=models.CASCADE) step = models.IntegerField() title = models.CharField(max_length=50) location = models.CharField(max_length=100) description = models.CharField(max_length=1000) audiotext = models.TextField() latitude = models.FloatField() longitude = models.FloatField() radius = models.FloatField() image = models.ImageField(upload_to=upload_tour_step_image, blank=True, null=True) class Meta: db_table = 'tourSteps' verbose_name_plural = "tourSteps" unique_together = ('tour_id', 'step',) ordering = ('tour_id', 'step',) def __str__(self): return str(self.tour) + "|" + str(self.step) But I have no idea how I can integrate this in my Create-Form and Update-Form. What I want to achieve. toursteps_form.html {% extends 'tour_admin/admin_base.html' %} {% load crispy_forms_tags %} {% load leaflet_tags %} {% leaflet_js plugins="forms" %} {% leaflet_css plugins="forms" %} {% block content %} {% if user.is_authenticated %} <div class=""> <h1>Step:</h1> <form enctype="multipart/form-data" class="tour-form" method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% else %} <h1>Not authorised!</h1> {% endif %} {% endblock %} forms.py from leaflet.forms.fields import PointField from leaflet.forms.widgets import LeafletWidget class TourStepForm(forms.ModelForm): class Meta(): model = Toursteps exclude = ('tour',) views.py class CreateTourStepView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = … -
Django uncaught exception when file upload request canceled
I have an async file uploader using Dropzone.js and everything works fine except for a strange server error that appears from time to time when I cancel an upload request. The error is inconsistent, sometimes I get the expected result after canceling the upload request and other times the error shows up in Identical conditions. Please note that I'm using chrome's network throttling so I can cancel uploads before the upload finishes. This is the file upload view : @login_required def media_upload(request): if request.method == 'POST' and request.FILES.getlist('media'): file = request.FILES.getlist('media')[0] fs = FileSystemStorage() try: img = Image.open(file) img.verify() except Exception as exp: return HttpResponse(exp, status=400) # Converting and saving media img = Image.open(file) media_prefix = ('evnt_u' + str(request.user.id)) media_ext = '.jpg' if img.format != 'JPEG': img = img.convert('RGB') buffer01 = BytesIO() img.save(buffer01, format='JPEG') file = InMemoryUploadedFile( buffer01, None, (media_prefix+media_ext), 'image/jpeg', buffer01.tell, None) media = fs.save((media_prefix+media_ext), file) return HttpResponse(media, status=200) else: return HttpResponse(status=400) I receive POST /media/upload/ HTTP/1.1" 400 0 correctly with the code above but that's not consistent. the other times I receive the appropriate response followed by a chain of uncaught exceptions: Bad Request: /fa/media/upload/ [05/Apr/2020 18:36:51] "POST /fa/media/upload/ HTTP/1.1" 400 0 Traceback (most recent call last): File … -
How to return django modal objects through httpresponse?
def search_car(request): if request.method == 'POST': a=request.POST['search_name'] scn=Car.objects.filter(name__icontains=a) In the above defined view I want return the variable scn through the function HttpResponse().So for that I should just return it like: return HttpResponse(scn) Or is there any better and appropriate way is there for doing so?? Also I want receive the sent variable in the template using javascript and that doing this: var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } would be correct or is there any better way for doing that?? -
name suggestions while updating data base from another table in django models
I am working on a leaderboard webapp with django. i have created a four teams each having their own own table in sqlite databse. i have another table pointshistor, so whenever i want to update the points of a player i only have to make a new entry in this table. the classes declaration are as below. class team1(models.Model): member_name = models.CharField(max_length=100) employee_id = models.CharField(max_length=40) unique_id = models.CharField(max_length=40) member_type = models.CharField(max_length=50, choices=[('Team Lead, 'Team Lead'), ('Member', 'Member')]) points = models.IntegerField() class team2(models.Model): member_name = models.CharField(max_length=100) employee_id = models.CharField(max_length=40) unique_id = models.CharField(max_length=40) member_type = models.CharField(max_length=50, choices=[('Team Lead', 'Team Lead'),('Member', 'Member')]) points = models.IntegerField() class pointshistory(models.Model): team_name = models.CharField(max_length=40, choices=[('team1', 'team1'),('team2','team2')]) member_name = models.CharField(max_length=100) activity_name = models.CharField(max_length=100) points = models.IntegerField() so what i want to do is when i select team from the team_name choice in the add pointshistory in django/admin and then start typing the name it should give suggestions of the name available in the particular team_name. and if one can help is there a simple way to update the points of the particular member. currently i am updating it by fetching the last entry from pointshistory table and adding the value to points by python script. main objective is … -
How to model an financial accounting system in Django?
The Django application I'm developing for a taxi company has following modules, Trips Customers (who buy products) Vehicles Drivers Each trip is constituted by selecting a customer, a vehicle and a driver along with a few other parameters. I will be recording every single trip, and the revenue generated because of it. I also would like to assign this revenue generated to the individual customer who took the vehicle, and to the vehicle which was used in the trip. Since I would like to have a deeper understanding of the customer's spending and the revenue generated by vehicles. I need to have an Accounts Receivables and a Received statement for each trip. Is there a standard way to achieve this? I believe the similar approach is used in typical e-commerce systems. Any and every help is appreciated. -
Django rest framework, field that is a choice or text
Is there a way to create a field which is A text field, but, with choices. that the choices are the field existing objects? And if the word passed in is not in the existing data, add it? I've looked across all the internet for a field like this or example of it, either in Django or the rest framework, but could not find one. My use for it, for example, would be: class Point(models.Model): location_name = models.TextField(verbose_name="Location name", unique=True, # This would include the existing names. choices=, ) latitude = models.FloatField(name="GDT1Latitude", verbose_name="GDT 1 Latitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="GDT1Longitude", verbose_name="GDT 1 Longitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) So, It could be used when making a post request instead of already typing the latitude, longitude It would be fetched from the exsiting object. -
Count events types per day for different timezones using Django ORM
We have a table that holds multiple events and when they were added. The default timezone used for storing the events is UTC. Eg : class Events: event_type = models.CharField(max_length=45, null=False) date_added = models.DateTimeField(auto_now_add=True) Now, we want to get a per day count of different event types between two dates - start_date and end_date. Eg : for start_date = "2020-03-1" and end_date = "2020-03-31", output should be - [{ "date" : "2020-03-1", "event1" : 200, "event2" : 606, "event3" : 595 }, { "date" : "2020-03-2", "event1" : 357, "event2" : 71, "event3" : 634 }, { "date" : "2020-03-3", "event1" : 106, "event2" : 943, "event3" : 315 }, { "date" : "2020-03-4", "event1" : 187, "event2" : 912, "event3" : 743 }, . . . . { "date" : "2020-03-31", "event1" : 879, "event2" : 292, "event3" : 438 }] Since the users are in different timezones (America, Europe, Asia, etc), we want to convert the timezone as per user before counting the events. Counting in UTC will have wrong counts per day in the user's timezone. Eg : an event created on 3 March, 1:30 am in IST will be shown on 2 March, 8 pm in … -
Django - posts.Post.None
I am working on a django project and I have 2 models that look like this: class Playlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='playlist_user') name = models.CharField(max_length=120) image = models.ImageField(upload_to=upload_image_path) genre = models.CharField(max_length=120,null=True,blank=True) track = models.ManyToManyField('Post',related_name='playlist_track') class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_image_path) audiofile = models.FileField(upload_to=upload_image_path,null=True) genre = models.CharField(max_length=120,null=True,blank=True) and this view: def userprofileview(request): own_tracks = Post.objects.filter(user=request.user) playlist_ = Playlist.objects.filter(user=request.user) context = { 'own_tracks':own_tracks, 'playlist_':playlist_ } return render(request,'userprofile.html',context) but when I try to query the posts from the playlist like this: {% for object in playlist_ %} {{ object.track }} {% endfor %} I get: posts.Post.None Thank you for any suggestions -
Upgrading Django 1.11 to 2.2 - Crispy form troubles
I've recently upgraded a project from Django 1.11 to 2.2, alongside upgrading all the necessary packages and python 3.5 to 3.7. I've managed to fix everything that needed to be changed to upgrade to 2.2 django. Among other packages I've also upgraded django-crispy-forms from 1.6 to 1.9 to be compatible with Django 2.2. The problem I am facing is that, my SplitDateTimeWidget I am using in all crispy forms across the project is not displaying properly. It is not utilizing bootstrap3 style as display below: Has anyone else faced with this issue when upgrading and what are the workoarounds? Thank you! -
TypeError at /accounts/register save() missing 1 required positional argument: 'self'
my error code is: save() missing 1 required positional argument: 'self' the exception loader shows the following message: E:\coding\fyp\travel\accounts\views.py in register, line 23 my views.py looks like: from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): print("usernmae taken") return redirect('/') elif User.objects.filter(email=email).exists(): print("email taken") return redirect('/') else: user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) line 23:- User.save() print("user created") return redirect('/') else: print("passwords not matching") return redirect('/') else: return render(request,'register.html') -
Django-rest-framework {"detail": "Authentication credentials were not provided." } using django-rest-knox
This is the code I am using for Login My Model: class User(AbstractBaseUser): STUDENT = 'STU' SCHOOL = 'SCH' INSTITUTE = 'INST' TUTOR = 'TUT' ACCOUNT_TYPE_CHOICES = [ (STUDENT, 'Student'), (SCHOOL, 'School'), (INSTITUTE, 'Institute'), (TUTOR, 'Tutor'), ] account_type = models.CharField( max_length=4, choices=ACCOUNT_TYPE_CHOICES, default=SCHOOL, ) name = models.CharField(max_length=255) email = models.EmailField(unique=True,max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','account_type'] objects=UserManager() def __str__(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True @property def is_staff(self): return self.is_admin My serializers: from rest_framework import serializers from .models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'account_type', 'name', 'email') # Login Serializer # I guess the validate function is not working . class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): user = authenticate(request=None,**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") My Views: from rest_framework import generics, permissions,authentication from rest_framework.response import Response from knox.models import AuthToken from knox.views import LoginView as KnoxLoginView from .serializers import UserSerializer, RegisterSerializer, LoginSerializer from django.contrib.auth import authenticate,login # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer # authentication_class=[authentication.BasicAuthentication] def post(self, request, *args, … -
Avoid circular reference when two columns in one table point to primary key in another table
I have two tables. First is Users table and second is Referrals table. Referrals table looks like this: | Referrals table columns | Points to | ----------------------- | --- | new_customer_id | user table's primary key | referred_by | user table's primary key The requirement is that if Person B (ID: 2) is referred by Person A (ID: 1), we should not be able to insert the other way around. In other words, the table should not have data like this: | new_customer_id | referred_by | | --------------- | ----------- | | 2 | 1 | <-- OK | 1 | 2 | <-- Both people refering each other should not be allowed Is it possible to check this during insert on database level. I'm using mysql. I read a bit about mysql CHECK constraint here, but cannot figure out how to implement this. I'm using django ORM and here is what I have tried but failed. class Referrals(models.Model): customer = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, db_index=True) referred_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, db_index=True) class Meta: constraints = [ models.CheckConstraint(check=models.Q(customer__lt=models.F('referred_by')), name='referrer_should_come_before_referee') ] If it is not possible with Django ORM but possible in database level with some query, that's fine also. However, +1 for django … -
Django form get_or_created with 3 different variable
I'm trying to created or update a django form. There's 3 unique identifier in that form, NRIC, MRN or Passport. User can fill any or all of them. the problem is how do I check with the database whether I need to create or update an existing one. so my code is like this: if request.method == 'POST': form = PatientForm(request.POST) if form.is_valid(): nric = form.cleaned_data['nric'] mrn = form.cleaned_data['mrn'] passport = form.cleaned_data['passport'] try: if nric: #if user filled in nric, check database by nric patient = Patient.objects.get(nric=nric) patient.nric = nric if mrn: patient = Patient.objects.get(mrn=mrn) patient.mrn=mrn if passport: patient = Patient.objects.get(passport=passport) patient.passport = passport patient.name = form.cleaned_data['name'] patient.save() except Patient.DoesNotExist(): form.save() The problem start when user filled another 1 of those 3 unique identifier, eg: there's already a record with Passport = 34234234, then user filled another MRN with new value..so 2 of 3 fields now have values, it will fail the check because of object.get(mrn=mrn). any ideas on how can I solve this? Thanks -
Multiplayer game using Django
I'm trying to know if it is possible or not to create an online multiplayer game using Django framework, python socket for TCP connection and Javascript for the animations. Is it possible to handle different server for each game launched? Write the functional script in python and using it with Javascript? I read a lot about Node.JS and this seems to be a much more suitable solution however I didn't use it yet. If this is the best solution, how many time do you think it will take to learn the basics of this framework? Thanks a lot for your help it is very appreciated. :) -
Extract image tag from content of database using django
I have this type of content stored in the database. This is saved via ckeditor. There are two ways to invoke the API: Sending HTTP requests and parsing the responses. Using........................................ What I want is to display the image only, in somewhere else in the same Django project. Is there any way to extract image only and display in my view file or what will be the best solution? Can I extract the path of image and display it ? So, how to extract the image tag from the content? It will be appreciated if someone helps. I am new to Django. -
Does fetch api in javascript send a get request if the post request fails
I was trying to build a Django app with javascript in the frontend. The POST request from the fetch API was failing if I did not add the CSRF token in the headers. However, it sent a GET request instead. When I added the CSRF token, it worked normally. But in the future, I want to avoid sending GET requests in case the POST fails. It is the default behavior? How do I prevent it? -
Django - Login required for specific user type
I extended the user login from Django with AbstractUser like this: class User(AbstractUser): pass class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) money = models.IntegerField(default=0) def __str__(self): return str(self.user) I would like now to create a view and a form that can only be access by the "Seller" user, like this in views.py: @login_required def account(request): return render(request= request, template_name='main/account.html', context = {}) Any idea on how can I do it? Thank you -
Django. Language prefix in URL patterns
Language prefix in URL patterns I have done Translation of the website in 2 languages. It reads the language setting of the browser and automatically switches to the correct language. I want to add a language menu to the website and language prefix in URL patterns. Sorry, I have here difficulties and earnestly speaking do not understand what needs to be changed in the main urls.py. I am talking about this application only app_name = 'rsf' Please help. main urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('auswertung/', include('auswertung.urls')), path('rsf/', include('rsf.urls')), path('admin/', admin.site.urls), ] local urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'rsf' urlpatterns = [ path('f_size_water/', views.f_size_water, name = 'f_size_water'), path('f_size_water_fin/', views.f_size_water_fin, name = 'f_size_water_fin'), ] Thank you -
error while installing virtual environment
I'm following official django tutorial on their webpage. When I run command "py -m pip install virtualenvwrapper-win", I get the the following errors. Please see the screenshot. I have Anaconda installed. The same error occurs on my other computer where I have only Python installed. What am I missing? Thanks