Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to move some code from post method to a separate method in Django views
I have a class that take some info from a form, make some changes to it. And than saves it into database At the moment all the logic is in the post method. And I want to make the code more structured and I want to put some part of it to a separate method. Is it possible? If so, how can I do it? here is my code: class AddSiteView(View): form_class = AddSiteForm template_name = 'home.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, { 'form': form }) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): site_instanse = form.save() url = request.POST.get('url', '') if url.endswith('/'): url = url + "robots.txt" else: url = url + "/robots.txt" robot_link = Robot( site = site_instanse, link = url, ) robot_link.save() pk = Robot.objects.get(site=site_instanse) return redirect('checks:robots', pk.id) return render(request, self.template_name, { 'form': form }) I want to make 2 changes to it: The 1st thing I want to do is to move this part of code to a separate method if url.endswith('/'): url = url + "robots.txt" else: url = url + "/robots.txt" And the 2nd thing I want to do is to move this part of code … -
how to generate list (about 10 instances) of random numbers by one click in the admin of Django?
I want to generate a list of random numbers that consists of 12 digits, from the Django Admin Dashboard, what is the best approach for this ? -
django save multiple foreign key values at the same time
I have been trying to save a multiple foreign key fields at the same time then I have been getting an error too many times, here is the error Exception Value: Cannot assign "<QuerySet [<Assign: Ahmed Nuur : DC : Data Communication>, <Assign: Ahmed Nuur : EC : Electrical Circuit>, <Assign: Ahmed Nuur : X : ElectricaL>, <Assign: Ahmed Nuur : X : ElectricaL>]>": "StudentRegisterCourse.assign" must be a "Assign" instance. if you can help me with that here is my models.py class StudentRegisterCourse(models.Model): assign = models.ForeignKey(Assign, on_delete=models.CASCADE, blank=True, null=True) student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=True, null=True) and also here is my forms.py class StudentCourseRegistrationForm(ModelForm): assign = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Assign.objects.all(), ) class Meta: model = StudentRegisterCourse fields = '__all__' and lastly here is my views.py def staff_student_course_registration(request): form = StudentCourseRegistrationForm() if request.method == 'POST': form = StudentCourseRegistrationForm(request.POST) if form.is_valid(): f = form.save(commit=False) for ass in f.assign: f.assign = ass f.student = f.student f.save() return redirect('staff_student_course_registration') -
Multiple ModelForms in one single CreateView in django
I have a multiple modelforms form multiple model. I want one single form for submitting all the values. It means I want one single view for posting all modelforms data. I dont know how to that. forms.py: class EmployeeAddModelForm(forms.ModelForm): """ Creates a form for employee invitations """ class Meta: model = Employee fields = [ 'e_id', 'first_name', 'last_name', 'gender', 'religion', ] class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] class EducationForm(forms.ModelForm): """ Creates a form for saving educational info of an employee """ class Meta: model = Education fields = [ 'institution_name', 'degree', 'passing_year', 'result',] I have three model forms from three models in form.py. I want that my createview inherits all this modelforms and create a single form for posting data. views.py: class EmployeeAddView(LoginRequiredMixin,CreateView): """ Creates new employee """ login_url = '/authentication/login/' template_name = 'employee/employee_add_form.html' form_class = EmployeeAddModelForm queryset = Employee.objects.all() def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) print(form.errors) if form.is_valid(): form.save() return redirect('employee:employee-list') return render(request, self.template_name, {'form': form}) -
Storing Django media files on Digitalocean/AWS doesn't work due to bad URL
I intend to store my static files on my production server and store media files (I run a blog) on a Digitalocean Space which runs on AWS3 bucket behind the scenes. I followed along this tutorial and can't make it run. It seems the url is the issue. So the tutorial basically suggests these settings: ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ AWS_ACCESS_KEY_ID = 'your-spaces-access-key' AWS_SECRET_ACCESS_KEY = 'your-spaces-secret-access-key' AWS_STORAGE_BUCKET_NAME = 'your-storage-bucket-name' AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'your-spaces-files-folder' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Which in my case translates to the following: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') AWS_ACCESS_KEY_ID = 'XXX' AWS_SECRET_ACCESS_KEY = 'YYY' AWS_STORAGE_BUCKET_NAME = 'stocksphere.blog.media' AWS_S3_ENDPOINT_URL = 'ams3.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'media' MEDIAFILES_DIRS = [ os.path.join(BASE_DIR, 'media'), ] MEDIA_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) MEDIAFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' When I now create a blogpost and upload the thumbnail, it returns the following: This is my Digitalocean/AWS bucket: -
How to save timer value in server-side using Django?
I have created a timer using javascript, to make sure that the timer doesn't reset everytime the user refresh the page, I pass the how much time have been passed since accessing the page in the server as the following: time_passed = (now - answer.created_at).total_seconds() time_passed = int(time_passed) seconds_left = 30 - time_passed answer.seconds_left = seconds_left completion_time = 30 -seconds_left answer.completion_time = time_passed answer.save() context = {'time_passed':time_passed} json_string = json.dumps(context) response = HttpResponse(json_string, content_type="application/json") return response Then I use the time_passed value in my JS timer and it works fine, except that on the time-out completion_time should be 30 seconds and seconds_left should be 0 seconds. but for some reason that doesn't happen where I keep getting completion_time = 29 and seconds_left = 1 function onTimesUp() { clearInterval(timerInterval); } function startTimer() { timerInterval = setInterval(() => { $.ajax({ type: "GET", url: server_url+ timerPath, success: function (context) { timePassed = context.time_passed; } }); timePassed = timePassed += 1; timeLeft = TIME_LIMIT - timePassed; document.getElementById("base-timer-label").innerHTML = formatTime(timeLeft) if (timeLeft === 0) { onTimesUp(); } }, 1000); } what am I missing ? -
django installation in ubuntu
while installig django to my ubuntu system i was following a youtube tutorial: https://www.youtube.com/watch?v=tX5ZBLNNcfE&t=148s All went well untill django was installed with a warning, WARNING: The script sqlformat is installed in '/home/bivek/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Therefore when i used command django-admin --version Its showing command not found try installing django again. How can I fix this issue? -
Django Validate Image or File With A Form Inside a Form
Hello I'm having trouble here with multiple image with same field. As far as I know in django tutorial they telling this. for f in request.FILES.getlist('files'): # do something (validate here maybe) in which I don't quite get it. Like do i do manual validation? If so why? Anyway there is another approach they give files = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True}) This one does not work in the way I want. It's self.cleaned_data['files'] only gives one output (There is a similar problem here) and django/multiupload was having a bug on my experience and sadly it was too slow to fix :(. What I want was to validate each file and give errors to each via ImageField because I like it was validating a file versus I code it myself. Thus I made a prototype code. forms.py class ImageForm(forms.Form): # validate each image here image = forms.ImageField() class BaseForm(forms.Form): # first form ping = forms.CharField() #images = SomeThingMultipleFileField that will raise multiple errors each validate image. # since no option I decided to do that. below. # so for decoration that images is required. images = forms.ImageField() def handle(self, request, *args, **kwargs): #custom function image_list = [] errors = [] # validate each … -
Django manage paginate_by with option menu
I I am trying to add to normal pagination one more choice. User should choice how many rows show for page. Here is my view code class ListaBoeView(ListView): model = DatiBoe testvar = 7 queryset = DatiBoe.objects.all() #DatiBoe.objects.filter(BACKSCATTER__gt= testvar)[:5] #DatiBoe.objects.all() context_object_name = 'boe_list' paginate_by = 3 template_name = 'filtri/boelista.html' # def get(self, request, *args, **kwargs): # new_signup = self.request.GET.get("paginate_by") # print(new_signup) def get_paginate_by(self, request, *args, **kwargs): try: paginate_by = self.paginate_by print(self.paginate_by) return self.request.GET.get("paginate_by", self.paginate_by) #return self.request.user.profile.paginate_by except Profile.DoesNotExist: return super().get_paginate_by(queryset) Here is my select code for paginate_by (method GET) <form method="GET"> <select name="paginate_by" id=""> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="50">50</option> </select> <input type="submit" value="Paginate"> </form> If I click the paginate button i have url formatted correctly (es: http://127.0.0.1:8080/filtri/boe_list/?paginate_by=10) but any time i click on next/prev button I back to default value paginate_by = 3 in my class. -
Multi Identity providers on the same Service provider
I'm using djangosaml2 package for SSO integration, Is there a way to connect with two identity providers? I mean i want to login on two different providers and my app is the service provider. -
Why is Django giving me this AttributeError?
Django is giving me this weird AttributeeError : 'Tour' object has no attribute 'check_if_requested_beds_are_avaliable' However, I have the method check_if_requested_beds_are_avaliable() in my Tour class of my model. The other method - set_new_number_of_beds() works fine. I have never experienced this with with Django, can anybody tell me what the solution is? This is the model : from django.db import models from django.urls import reverse class Tour(models.Model): destination = models.CharField(max_length=256) country = models.CharField(max_length=256) date_of_arrival = models.DateField() total_days = models.IntegerField() price = models.DecimalField(decimal_places=2,max_digits=6) available_beds = models.IntegerField() photo = models.ImageField(upload_to='photos',default='photos/def.png') description = models.TextField(blank=True) def set_new_number_of_beds(self,number_of_guests): self.available_beds -= number_of_guests return self.available_beds def check_if_requested_beds_are_available(self,numb_of_guests): if self.available_beds < numb_of_guests: return False else: return True def __str__(self): return f'{self.destination} , {self.country} , {self.total_days} days for $ {self.price}' class Client(models.Model): name = models.CharField(max_length=256) surname = models.CharField(max_length=256) email = models.CharField(max_length=256) number_of_guests =models.IntegerField() tour = models.ForeignKey(Tour,on_delete=models.CASCADE) total_price = models.DecimalField(decimal_places=2,max_digits=6,default=0) def get_total_price(self): return self.number_of_guests * self.tour.price def get_absolute_url(self): return reverse('tour_list') def __str__(self): return f'{self.name} {self.surname}, {self.tour}' and this is the view: from django.shortcuts import render from aplikacija.models import Tour,Client,ContactMessage from django.views.generic import ListView,DetailView,TemplateView,CreateView from aplikacija.forms import ClientForm,ContactForm def HomeView(request): if request.method=="GET": return render(request,'aplikacija/home.html') else: form= ClientForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] surname=form.cleaned_data['surname'] email=form.cleaned_data['email'] tour_id=form.cleaned_data['tour'].pk number_of_guests=form.cleaned_data['number_of_guests'] total_price=number_of_guests*form.cleaned_data['tour'].price tour_name=form.cleaned_data['tour'].destination client = Client.objects.create(name=name,surname=surname,email=email,number_of_guests=number_of_guests,tour_id=tour_id,total_price=total_price) client.save() tour=Tour.objects.get(destination=tour_name) … -
How to save multiple models with multiple modelForms in one django form-tools WizardView
Here's my scenario: I have two models: class Person(models.Model): # --- model fields --- class Qualification(models.Model): owner = models.ForeignKey(Person, on_delete=models.CASCADE) # --- other fields --- And Model forms: class PersonalForm(forms.ModelForm): class Meta: model = Person fields = ['first_name', 'last_name', 'email', 'id_number', 'date_of_birth'] class IsQualifiedForm(forms.ModelForm): class Meta: model = Person fields = ['is_qualified'] class QualificationForm(forms.ModelForm): class Meta: model = Qualification fields = ['level', 'course_name', 'attainment'] And finally my wizard view: class Wizard(SessionWizardView): template_name = 'demo/wizard_test.html' form_list = [ ("personal", PersonalForm), ("is_qualified", IsQualifiedForm), ("qualifications", QualificationForm), ] def get_form_instance(self, step): return self.instance_dict.get(step, None) def done(self, form_list, **kwargs): # What is the exact logic to be applied here to save the model forms concurrently? return redirect('home') I'm trying to save the form but I run into errors: When I try to call: for form in form_list: form.save() in the done() method, I get an error because the is_qualified is intercepted as null in the first step. Plus, how do I get to set the owner field's value to the currently created person? Any help would be appreciated. -
How to implement AJAX in Django generic view
I want to learn AJAX by implementing it to my present project. I cannot find good resources how to do this in my case. In my project user can rate movie from 1 to 10 once and change it by rating again. I would like to do this without refreshing the site. views.py class MovieDetailView(FormMixin, DetailView): model = Movie template_name = 'main/detail_movie.html' context_object_name = 'movie' form_class = RateForm def get_context_data(self, **kwargs): context = super(MovieDetailView, self).get_context_data(**kwargs) context['form'] = RateForm(initial={'movie': self.object}) context['my_rate'] = Rate.objects.filter( sender=self.request.user, movie=self.get_object()).first() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): Rate.objects.update_or_create( sender=self.request.user, movie=self.object, defaults={'choice': form.cleaned_data['choice']} ) return HttpResponseRedirect(self.get_success_url()) models.py class Rate(models.Model): class Meta: unique_together = (('sender', 'person'), ('sender', 'movie'),) choice = models.IntegerField(null=False, blank=False, choices=RATE_CHOICES) sender = models.ForeignKey(User, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True) movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True) forms.py class RateForm(forms.ModelForm): class Meta: model = Rate fields = ('choice',) urls.py path('movie/<slug:slug>/', MovieDetailView.as_view(), name='detail_movie'), Could you give me at least some tips, sources etc. how to do this? Any help will be appreciated. -
How to pass a value through django templating?
So I have this urlpattern where we could type a number on the address bar and it will render an html template which will display the entered number on the page, I decided to give it a little more functionality by piping an add:1 to a links href so that every time we click on the link it adds up to the previous number and then generate the response by displaying that number on the page, But I can't get it to work using django templating, Can anyone please help me with this? Here's is the url pattern which accepts an integer urlpatterns = [ path('home/<int:num>',views.index,name='index') ] Here's the HTML template <!DOCTYPE html> <html> <head> <title>Dynamic urls</title> </head> <body> <h1>Page no. {{num}}</h1> <a href="{url 'home/{{num|add:1}}' }">Change the page</a> </body> </html> -
How to show the post title in dynamic url routing
i am currently working on a web application project in django ,I want to display the post title in dynamic url routing in post detail page Now my url is like localhost/blog/detail/1 '1 is post id' i want to add the post title in the above url with dynamic url routing like localhost/blog/detail/name of the instance post/id views.py def blog_detail(request,id=None): instance=get_object_or_404(blogPost,id=id) args={"instance":instance} return render(request,'blog/blogDetail.html',args) url.py from django.conf.urls import url from . import views urlpatterns=[ url(r'^$',views.blog,name="blog"), url(r'^details/(?P<id>[-\w]+)/$',views.blog_detail,name="details"), ] models.py from django.db import models from django.urls import reverse # Create your models here. class blogPost(models.Model): postTitle=models.CharField(max_length=150) postContent=models.TextField(blank=False,default="Not found") category=models.CharField(max_length=50) author=models.CharField(max_length=100) updated=models.DateTimeField(auto_now=True,auto_now_add=False) timestamp=models.DateTimeField(auto_now=False,auto_now_add=True) def __unicode__(self): return self.postTitle def __str__(self): return self.postTitle def get_absolute_url(self): return reverse('details',kwargs={"id":self.id}) -
Unify multiple Djangp url prefixes by pattern to same page
I have the following Django urls patterns: urlpatterns += patterns('some.utils', url(r'^media$', logic0), url(r'^tickets$', logic1), url(r'^dogs$', logic2), url(r'^some-location-with-ending.png$', LOGIC3), url(r'^some-location-other-ending.svgh$', LOGIC3), url(r'^some-location-number-123$', LOGIC3), url(r'^some-location-5$', LOGIC3), ) Is there a simple way (regex?) to unify all the some-location prefixes in one line? Of course also for future patterns that will start at some-location -
How to restrict input length on form field using another field in same form
How can I change the max_length attribute of my text variable dynamically as the user inputs a value into text_max_length? I know there are many workarounds I could do to achieve this behaviour, such as splitting the form into two seperate forms but this seems messy. # forms.py from django import forms class ExampleForm(forms.Form): text_max_length = forms.IntegerField(label='Max Length', initial=20, max_value=40, min_value=0, help_text='(Between 0-40)') text = forms.CharField(label='Enter Text', widget=forms.Textarea, max_length=40) -
Any recommendations for creating a simple site builder?
I'm planning to create a secured, simple site builder for my school project, but not as complex as those which are drag and drop ones. I would say that I'm an average web developer, so far I know Flask and ASP.NET MVC for web development. Any recommendations on how I'd start this project or what frameworks to use? I don't know how WordPress works behind the scenes. I was thinking of something like where users have a main,central site to register. Then they login their account, choose a template, and modify it. Then after making changes, their website goes online, hosted, with a subdomain. Like, do I use a micro-framework for the user's hosted site then use a full framework for the main site, like Django or what? Because I don't think I should use Flask for the main site because it's not good for security features. I really dunno how to start this. -
Python requests in Django Vs Fetch API in JS
I am using an API created using Azure API service. 'Access-Control-Allow-Origin' header is not defined on the server. I am calling the API in two ways: Python Requests in Django: This works smoothly and gives expected response with a get request. Fetch API in JS: This gives the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <> (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). I couldn't understand why the CORS header is not required while using the requests library. Also, if get request works without CORS header in django, is there a way to make it work in JS as well? -
I want to apply group by to the list And I want the group by criteria to be dates. , ex)20200712,20200713,20120714,20200715
I want to apply group by to the list And I want the group by criteria to be dates. , ex)20200712,20200713,20120714,20200715 like this model is this class Todo(models.Model): title = models.CharField(max_length=50) content = models.TextField(blank=True) created = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now_add=True, blank=True, null=True) qeuryset is this qs = Todo.objects.filter(Q(author=self.request.user) & Q(elapsed_time__isnull=False)) db is this How do I change the query set? Thanks for letting me know -
Integration of django-oscar and django-cms
I want to build a django oscar ecommerce web app. A Required fearure in this app is a content management system, therefore I want to integrate django-cms in my app. After some research I found apphooks but there is no guide on google for integration of django-oscar and django-cms. Can anyone tell me the way to solve this issue? -
How to add additional url in Vue JS
Hi I am using django and Vue to make an webapp. I am rendering data using v-for and fetching the data from a restful API using XMLHttprequest This is my custom js file. I am not using Vue CLI I am using a CDN: $(document).ready(function () { function fetchData(){ Vue.component('postcontainer', { props:['obj'], template: `<div> <div v-for="data in obj" class="ui mt-3 card"> <div class="content"> <div class="right floated meta">{{data.date_posted}}</div> <img class="ui avatar image" src="https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_960_720.jpg"> {{data.author}} </div> <div v-if="data.image" class="image"> <img v-bind:src="[[data.image]]"> </div> <div v-if="data.video"> <video controls v-bind:src="[[data.video]]" class="embed-responsive"></video> </div> <div class="content"> <div v-if="data.title"> <a class="text-dark" :href="data.id"><h3 class="header">{{data.title}}</h3></a> </div> <div class="description my-2"> <div v-if="data.caption"> <a class="text-dark" :href="data.id"><p>{{data.caption}}</p></a> </div> </div> </div> <div class="extra content"> <span class="right floated"> <i class="heart outline like icon"></i> 17 likes </span> <a :href="data.id"><i class="comment icon"></i></a> </div> </div> </div> ` }) var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var app = new Vue({ el: '#postCard', component:['postconatiner'], data: { obj: JSON.parse(this.responseText), } }) } } xhr.open('GET', '/data/', true); xhr.LOADING xhr.send() } fetchData() }); I want add an additional url before data.id example - ":href = 'detail/data.id'". My problem is when I try to add this the url becomes 'localhost:8000/NaN'. Please … -
Django Heroku "No Module named site.wsgi" found
My Site Directory Structure for a Python-Django app I am trying to deploy on Heroku looks like this: my_site my_app app_files my_site __init__.py asgi.py settings.py urls.py wsgi.py my_db.sqlite3 manage.py venv Procfile Procfile.windows Below are the contents of my Procfile web: gunicorn fynd_imdb_site.wsgi.application --log-file - My settings.py has configuration as follows: WSGI_APPLICATION = 'fynd_imdb_site.wsgi.application' My Django version is 3.0.8 and python version is 3.7 When I deploy on heroku, I get below stack trace: Starting process with command `gunicorn fynd_imdb_site.wsgi.application --log-file -` 2020-07-12T07:47:20.220531+00:00 app[web.1]: [2020-07-12 07:47:20 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-07-12T07:47:20.221416+00:00 app[web.1]: [2020-07-12 07:47:20 +0000] [4] [INFO] Listening at: http://0.0.0.0:32926 (4) 2020-07-12T07:47:20.221563+00:00 app[web.1]: [2020-07-12 07:47:20 +0000] [4] [INFO] Using worker: sync 2020-07-12T07:47:20.226071+00:00 app[web.1]: [2020-07-12 07:47:20 +0000] [10] [INFO] Booting worker with pid: 10 2020-07-12T07:47:20.234019+00:00 app[web.1]: [2020-07-12 07:47:20 +0000] [10] [ERROR] Exception in worker process 2020-07-12T07:47:20.234020+00:00 app[web.1]: Traceback (most recent call last): 2020-07-12T07:47:20.234037+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-07-12T07:47:20.234038+00:00 app[web.1]: worker.init_process() 2020-07-12T07:47:20.234038+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-07-12T07:47:20.234038+00:00 app[web.1]: self.load_wsgi() 2020-07-12T07:47:20.234038+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-07-12T07:47:20.234039+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-07-12T07:47:20.234039+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-07-12T07:47:20.234039+00:00 app[web.1]: self.callable = self.load() 2020-07-12T07:47:20.234040+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-07-12T07:47:20.234040+00:00 app[web.1]: … -
Design problem with complicated validations in django
I have a pet project about sharing expenses among people from some group (e.g. roommates). I have some design issues with complex checks I have to make for some operations, which double number of database queries. I am wondering whether there are more elegant solutions. E.g. models can be defined differently, these checks could be moved to constraints in database an so on. Now I have 3 main models: Users, Sharelist, Credit and Debt. The logic is the following: Sharelist unites people into group to share expenses among. Credit model is created when someone paid for something and Debt is created for those who owes him money. Code is here and here is simplification: from django.db import models from django.contrib.auth.models import User class Sharelist(models.Model): name = models.CharField(max_length=30) users = models.ManyToManyField(User) class Credit(models.Model): name = models.CharField(max_length=30) datetime = models.DateTimeField() amount = models.DecimalField(max_digits=19, decimal_places=2) creditor = models.ForeignKey(User, on_delete=models.PROTECT) sharelist = models.ForeignKey(Sharelist, on_delete=models.PROTECT) class Debt(models.Model): debtor = models.ForeignKey(User, on_delete=models.PROTECT) credit = models.ForeignKey(Credit, on_delete=models.CASCADE, related_name='debts') amount = models.DecimalField(max_digits=19, decimal_places=2) The problem here is that I have to check that the user and his debtors are in the same sharelist all the time I do operations with them (here some examples). It creates overhead for … -
{{ domain }} becomes example.com on local pc
I am learning to send mails with django, but I get into this issue, that it returns http://example.com/ instead of http://127.0.0.1:8000/ The code that sends the mail and generate the link is following (I've added comments on the two lines I suspect being the reason): views.py # Send activation E-mail current_site = get_current_site(self.request) # Either this line mail_subject = 'Activate your Penge account.' message = render_to_string('emails/activation-mail.html', { 'user': user, 'domain': current_site.domain, # or maybe this line 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address') How would I correct this as the function should get the domain using. Ideally I'd be able to define this in settings.py for when I deploy my application. Thank you in advance.