Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form action not working to redirect in django v2
The form action is not redirecting from home.html to password.html in Django 2 even I recheck everything including URL pattern Below I am sharing the basic code. My apologies if it's a basic question as I am very new to Django that's why I may not able to detect the issue. urls.py code from django.urls import path from generator import views urlpatterns = [ path('', views.home), path('password/', views.password), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, 'generator/home.html') def password(request): return render(request, 'generator/password.html') home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> <h1>Password Generator</h1> <form action="password" method="get"> <select name="length"> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select> <input type="button" value="Generate Password"> </form> </body> </html> password.py <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Password</title> </head> <body> <h1>Password page</h1> </body> </html> Error Log File Structure -
How to extact all value instance of a model in django views.py
Hy Guys, I have a question for you. I have the following model: from djmoney.models.fields import MoneyField class Totale_Vendite(models.Model): totale_vendite = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_dalle_vendite = models.CharField(max_length=100, editable=True) ricavi_01 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_02 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_03 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_04 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_05 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_06 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_07 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_08 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_09 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_10 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_11 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_12 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) Each instance rappresents the income on the month utilizing the djmoney app. In my views.py I want to extract for each instance ( ricavi_01, ricavi_02) the "amount" value (not currency). For the moment I have tried only the following way, that is to extract the value individually for each month: def ricavi_dalle_vendite(request): queryset = Totale_Vendite.objects.all() labels = ['Gen','Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'] data = [] for entry in queryset: data.append(str(entry.ricavi_01.amount)) .... how could solve it following the DRY principles??? -
How to redirect to a new id page after submitting a form in Django?
I wanted to redirect to a page that is newly created with the submission of the form. I tried and got a NoReverseMatch error instead. Here's the exception raised: Reverse for 'receive' with keyword arguments '{'id': 15}' not found. 1 pattern(s) tried: ['receive/(?P[0-9]+)$'] Here's the my views: def new_receive(request): """The page for adding a new receive.""" if request.method != 'POST': form = ReceiveForm() else: form = ReceiveForm(data=request.POST) if form.is_valid(): new_receive = form.save(commit=False) new_receive.save() return redirect('imsapp:receive', id=new_receive.id) context = {'form':form} return render(request, 'imsapp/new_receive.html', context) def receive(request, receive_id): """The page for viewing a receive.""" receive = Receive.objects.get(id=receive_id) receipt_no = receive.receipt_no date = receive.date context = {'receive':receive, 'receipt_no':receipt_no, 'date':date} return render(request, 'imsapp/receive.html', context) -
Django forms, iteration over different types of fields with bootstrap css
I looking for method to iterate over fields with bootstrap css. I have two form fields and one should have drop down list and second one is date. If I iterate using {{ field }} I receive what I want. But if I want to use bootstrap field styling i have blank fields. <div class="container"> <form method="POST"> <div class="form-group"> {% csrf_token %} <br> <a class="btn btn-primary btn-sm" href="{% url 'dodaj_ph' numer %}" role="button" name="dodaj_ph">Dodaj PH</a> <br> {% for field in form %} <label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label> <input class="form-control" type="{{ field }}"> {% endfor %} <button type="submit" class="btn btn-primary" name="button">Wypożycz</button> </div> </form> </div> class testerForm(forms.ModelForm): class Meta: model = Tester fields = ('phandlowy', 'data_wypozyczenia') labels = {'phandlowy' : 'Przedstawiciel handl'} ''' ''' class Tester(models.Model): numer_seryjny = models.IntegerField(primary_key=True) licencja_car = models.BooleanField(default=True) licencja_hd = models.BooleanField(default=True) dhandlowiec = models.ForeignKey(DHandlowiec, null=True, on_delete=models.SET_NULL) phandlowy = models.ForeignKey(Phandlowy, null=True, on_delete=models.SET_NULL, blank=True) wypozyczony = models.BooleanField(default=True) data_wypozyczenia = models.DateField(blank=True, null=True) problemy = models.CharField(max_length=2000, default="Brak problemów") history = HistoricalRecords() ''' -
Celery Task Running number of server times
I am having one issue with Celery tasks which are running a number of server times. I am using Django and Tastypie for building APIs and I am using Celery and Elaasticache Redis for periodic tasks. version details are as below: Django==1.9.4 celery==3.1.20 django-celery==3.1.17 So the main issue which I am facing right now is my periodic tasks are running number or server times as we have auto-scaling enabled. so for example, there are 3 servers after auto-scaling then the same periodic tasks are running parallelly. I am registering periodic tasks through djcelery admin panel. so can someone please help me with the above issue? any help would be highly appreciated. let me know if you need more details on same issue. thanks. -
Django button menu & generic page for product
I would like to know how to display other bikes by clicking on the button "urbain" for example here is my piece of code: <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <div class="filter-control"> <ul> <li class="active">Pliable</li> <li>Urbain</li> <li>Route</li> <li>VTT</li> </ul> </div> <div class="product-slider owl-carousel"> {% for velo in pliable %} <div class="product-item"> <div class="pi-pic"> <img src="{{ velo.image }}" alt=""> </div> <div class="pi-text"> <div class="catagory-name">{{ velo.slogan }}</div> <a href="#"> <h5>{{ velo.model }}</h5> </a> <div class="product-price"> {{ velo.prix }} </div> </div> </div> {% endfor %} </div> </div> </div> </div> enter image description here I have a second problem which resembles the first. I have a generic page for my products and I would like when I click on the button "VTT" it sends me back to this page with only "VTT", I already have a piece of code but I cannot pass him the query <li class="active"><a href="{% url 'index' %}">Accueil</a></li> <li><a href="{% url 'shop' %}">Vélo</a> <ul class="dropdown"> <li><a href="{% url 'shop' %}" name="Urbain">URBAIN</a></li> <li><a href="{% url 'shop' %}" name="Route">ROUTE</a></li> <li><a href="{% url 'shop' %}" name="VTT">VTT</a></li> <li><a href="{% url 'shop' %}" name="Trekking">TREKKING</a></li> <li><a href="{% url 'shop' %}" name="SpeedBike">SPEED BIKE</a></li> <li><a href="{% url 'shop' %}" name="pliant">PLIABLE</a></li> </ul> </li> my views.py def shop(request): product = … -
Using the object id in django forms
Why can't I access the object id in the def clean(self)? I get the error `'CheckInForm' object has no attribute 'id'. forms.py from django import forms from .models import Student from django.core.exceptions import ValidationError class CheckInForm(forms.ModelForm): class Meta: model = Student fields = ['room', 'name'] widgets = {'room': forms.TextInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), } def clean(self): cleaned_data = super(CheckInForm, self).clean() new_room = cleaned_data.get('room') if Student.objects.filter(room=new_room).count() > 3: print(Student.objects.filter(room=new_room).count()) if not Student.objects.filter(room=new_room, id=self.id): raise ValidationError('The room is full') models.py class Student(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, db_index=True) room = models.CharField(max_length=8, db_index=True, blank=True) -
What is the best way to display the value of a model function in a Django ModelAdmin change form view?
I have a model, say MyModel, represented by a few fields, and a function that I can display the output of on the model's change list page as follows: models.py class MyModel(models.Model): my_field = models.CharField(max_length=1000) def my_function(self): return 'Hello world' my_function.admin_order_field = 'hello' my_function.allow_tags = True my_function.short_description = 'Hello!' admin.py class MyModelAdmin(admin.ModelAdmin): model = MyModel fields = ['my_field', 'hello'] list_display = ['my_field', 'hello'] This works fine for the change list page, but when I view the change form I get AttributeError: 'MyModel' object has no attribute 'hello'. What's the best way of making the output of the model's function visible on the change form page? -
can't get the POST parameters in django
I am trying to make a login-page using django, I am facing troubles in getting POST parameters login view: def ProcLogin(request): if request.method == 'POST': account_name = request.POST.get('username','') password = ToMd5(request.POST.get('password','')) if not account_name or not password: return HttpResponse("invalid input") template code: <form method="post" action="{% url 'Main:login' %}" class="login_form"> {% csrf_token %} <div class="form-group text-right"> <label for="username">User name:</label> <input id="username" type="text" class="form-control box_shadow"> </div> <div class="form-group text-right"> <label for="password">Password: </label> <input id="password" type="password" class="form-control box_shadow"> </div> <button type="submit" class="login_btn"></button> </form> Output when testing it: [invalid input][1][1]: https://i.stack.imgur.com/N6A9a.png everything is supposed to be correct except the results aren't. Thank you. -
Django xhtml2pdf Invalid color value 'initial'
In my django application i use xhtml2pdf for convert an html template in pdf file. This is the part of my html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta charset="UTF-8"> <title>Documento senza titolo</title> <style type="text/css"> body {margin:0;padding:0;background-color:#FAFAFA;font:8pt "Tahoma";} * {box-sizing:border-box;-moz-box-sizing:border-box;} table, th, td {border:1px solid black;border-collapse:collapse;} .page {width: 21cm; min-height: 29.7cm;padding: 1cm; margin: 1cm auto;border: 1px #D3D3D3 solid;border-radius: 5px; background: white;box-shadow: 0 0 5px rgba(0, 0, 0, 0.1)} p {margin:0;padding:0;line-height:1.4em} .column-50-left {width:49.5%;display:inline- block;vertical-align:top;padding-right:15px} .column-50-right {width:49.5%;display:inline-block;vertical-align:top;padding-left:15px} .invoice {font-size:6pt} .invoice td {height:50px;vertical-align:top;padding:5px;} .destinatario td {height:120px;vertical-align:top;padding:5px;font-size:6pt} .description th {height: 30px} .description td {height: 360px} .top-10 {margin-top:10px} .top-15 {margin-top:15px} .top-20 {margin-top:20px} .padding-top-4 {padding-top:4px} .padding-bottom-15 {padding-bottom:15px} .padding-bottom-30 {padding-bottom:30px} .border-top {border-top:1px solid #000000} @media print { html, body {width:210mm;height:297mm;padding:0px;margin:0px} .page {margin:0;border:initial;border-radius:initial;width:initial;min-height:initial;box-shadow:initial;background:initial;page-break-after:always;padding:0px;margin:0px} } when i run code and pdf was created i get error: Invalid color value 'initial' i found 'initial' values in @media print directive. How have i to use instead the 'initial' for print my document? so manu thanks in advance -
how can make Personality Test with Django? [closed]
I am building a site through django. I want to create various functions related to psychology. It is considered the simplest of them, but there are some that have yet to be found. It's the personality test app. I think it's really simple, but I don't know how to implement it. For example, personlality test question is: Do you get angry easily? (1 to 7 points) Are you good at keeping your temper? (1 to 7 points) **when user press the button, it save the score of each question. and according to the internal formula , value is caculated [for example, (No. 1 Score + 8 - No. 2 score)}/2] , I want to show score for user visually. (User's score vs. Average of existing studies / graph or something else)** If you have any tips, please help me! Thank you for reading -
Why is django rest framework throwing a 406? (php and python/django)
my php script that calls the api: $api = new CoindRPC(); $txninfo = $api->gettransaction($argv[1]); error_log('=== WALLETNOTIFY ==='); error_log('txninfo: '. print_r($txninfo,true)); $url = 'https://redacted.com/api/register_domain_name'; foreach($txninfo['details'] as $id => $details) { $data = array( 'txid' => $txninfo['txid'], 'tot_amt' => $txninfo['amount'], 'tot_fee' => $txninfo['fee'], 'confirmations'=> $txninfo['confirmations'], 'comment' => $txninfo['comment'], 'blocktime'=> $txninfo['blocktime'] ? $txninfo['blocktime']:$txninfo['time'], 'account' => $details['account'], 'address' => $details['address'], 'category' => $details['category'], 'amount' => $details['amount'], 'fee' => $details['fee'] ); } $options = array( 'http' => array( 'header'=> array( 'Authorization: Token redacted\r\n', 'Accept: application/json\r\n', 'Content-type: application/json' ), 'method'=> 'POST', 'content'=> http_build_query($data), ), ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); and here is my (python/django) drf api view: @api_view(['POST']) @permission_classes((IsAuthenticated,)) @authentication_classes((TokenAuthentication,)) @ensure_csrf_cookie @renderer_classes((JSONRenderer,)) def register_domain_name(request): if request.method == 'POST': data = request.POST address = data.get('address', False) tot_amt = data.get('tot_amt', False) blocktime = data.get('blocktime', False) txid = data.get('txid', False) user = User.objects.get(userprofile__zeal_address=address) last_dri = DomainRegistrationItem.objects.filter(user=user).order_by('-registration_date')[-1] if tot_amt == last_dri.get_total_price: domain_name = last_domain_reg_item.domain domain = Domain.objects.create(name=domain_name, created_by=user) domain_name_order = DomainNameOrder.objects.create( from_address=address, price=tot_amt, blocktime=blocktime, txid=txid, domain_registration_item=last_dri, domain_item=domain, years=last_dri.years, ) last_dri.purchased = True last_dri.save() return Response({'status': 'success'}) else: return Response({'status': 'failed'}) Does anyone know what might be wrong? Any help is appreciated. Removing the Accept header (in the php script) gives me a 415. I have JsonRenderer … -
LDAP vs LDAPS for Django authentication
So one of the servers that we use LDAP to authenticate against has gone down and we were told to use a different website/server if our project supports LDAPS. So we put that new link into the server line in our settings.py like so (changed some words so I don't leak info!): LDAP_SETTINGS = { 'base_dn': 'dc=central,dc=server,dc=local', 'account_suffix': 'central.server.local', 'servers': ['new.server.edu'], 'staff_groups': ['aux-jr-admins', 'aux-rsrc-reports-centraldesk-checkins'], 'superuser_groups': ['aux-admins','aux-jradmins', 'aux-to-webadmin', 'aux-dept-to-developers'] } ...and that didn't work, it just failed. I can't find anything on Google pertaining to LDAPS and Django, but when I look up LDAP vs LDAPS, I can see that they are different. More specifically, LDAPS has encryption? So my question is, is LDAPS compatible with Django? And if so, how would I implement it within my settings.py file and how would I authenticate? Would I have to decrypt information? -
Virtualbox - access to website which is hosted on virtualbox
I have a Django website, which is running on VirtualBox 6.1 with Linux Mint Cinnamon. The Virtualbox is running on a desktop with Windows 7. Internet on the VirtualBox is accessible. How can I get access to this website from Browser on my desktop? On which port should I run Django in this case? In development mode I start it as follows: python3 manage.py runserver 5000. Thank you -
How can I lookup at a TextField with Djongo? Mongodb connector for Django
Admin.py Models.py Example of a post (document) at my Mongodb: My entire code: https://github.com/mtrissi/news_site_project So, I'm trying to develop an app with Django and with a Mongodb database. I'm using Djongo as the connector. All seems to work fine, except the search at the attribute 'content' of my model 'Post'. It should work fine with a simple posts = Post.objects.filter(content__icontains=r_search). But it does not. My views.py are like this: The commented lines at my search_view() are working, they search for 'author' and 'title' attributes. But the line where I search for the 'content' attribute does not work. How can I perform a search at the 'content' attribute? -
Model Choice Field doesn't save in database-django-form
Have a model that inherit from other model. I have no problem while saving data from django admin. But when I use Model Choice Field to save from form. The form simply goes to else statement instead of going it into if form.is_valid section. forms.py class CourseForm(forms.ModelForm): class Meta(): model = Course fields = '__all__' departments = forms.ModelChoiceField(queryset=Department.objects.all().order_by('name'), required=True) views.py def addcourse(request): if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): form.save(commit=True) messages.success(request, 'The course is added successfully.') return redirect('addcourse') else: messages.error(request, 'Subject ID already exists.') return redirect('addcourse') else: form = CourseForm() return render(request,'add_course.html', {'form':form}) When I run this code it results in Subject ID already exists irrespective of any inputs. -
How to eliminate duplicate data using if condition in django template?
Is it okay to use if condition in template views to eliminate duplicate data? Note: I have already distinct cores in my views but since i have 2 loops in 1 < tr > it duplicates some data. this is my html {% for core in cores %} {% for behavior in behaviors %} {% if core.Grading_Behavior__Grading_Behavior__Name == behavior.Grading_Behavior__Grading_Behavior__Name %} <tr> <td rowspan="2" colspan="4" class="tblcoretitle">{{core.Grading_Behavior__Grading_Behavior__Name}} 1</td> {% if core.Grading_Behavior__Grading_Behavior__GroupName == behavior.Grading_Behavior__Grading_Behavior__GroupName %} <td colspan="4" class="tblcore"> {{behavior.Grading_Behavior__Grading_Behavior__GroupName}} </td> {% else %} {% endif %} <td class="tblcore">1</td> <td class="tblcore">2</td> <td class="tblcore">3</td> <td class="tblcore">4</td> </tr> <tr> {% if core.Grading_Behavior__Grading_Behavior__GroupName == behavior.Grading_Behavior__Grading_Behavior__GroupName %} {% else %} <td colspan="4" class="tblcore">{{behavior.Grading_Behavior__Grading_Behavior__GroupName}} </td> {% endif %} </tr> {% endif %} {% endfor %} {% endfor %} this is my views.py cores = StudentsBehaviorGrades.objects.filter(Teacher=teacher) \ .filter(Students_Enrollment_Records__in=Students.values_list('id')).values('Grading_Behavior__Grading_Behavior__Name','Grading_Behavior__Grading_Behavior__GroupName').distinct('Grading_Behavior__Grading_Behavior__Name')\ .order_by('Grading_Behavior__Grading_Behavior__Name') behaviors = StudentsBehaviorGrades.objects.filter(Teacher=teacher) \ .filter(Students_Enrollment_Records__in=Students.values_list('id')).filter().values('Grading_Behavior__Grading_Behavior__Name','Grading_Behavior__Grading_Behavior__GroupName').distinct('Grading_Behavior__Grading_Behavior__GroupName')\ .order_by('Grading_Behavior__Grading_Behavior__GroupName') this is my current result this is i want result -
Which Python scheduler is the best?
Currently I am using a APScheduler for organizing recurrence tasks. For the beginning of application that was really good option but now it gives more cons than pros. I found a Celery as a good replacement. It's scalable a not like APSCheduler. Needs more resources and probably works much more efficient. But it have a one really big disadavantage. You can't add new tasks in runtime. So to summrize it, could you recommend any really good scheduler which will be scalable, async, able to add tasks in runtime and should works with python / django application? -
permissions in django with dispatch method
i'm trying to restrict users to view only the todos they have created using the dispatch method but i tried te below approach but still i'm seeing all todos appear under a user that did not create them custom user model from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): profession = models.CharField(null=True, blank=True, max_length=30) todo model from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Todo(models.Model): title = models.CharField(max_length=120) description = models.TextField(max_length=320) to_be_done = models.DateTimeField(null=False) date_posted = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('todo_detail', args=[str(self.id)]) listview for todos class TodoListView(LoginRequiredMixin, ListView): model = Todo template_name = 'todo_list.html' login_url = 'login' def dispatch(self, request, *args, **kwargs): objects = self.objects.filter(user=self.request.user) for obj in objects: if obj.user != self.request.user: raise PermissionDenied return super().dispatch(request, *args, **kwargs) any ideas on how i can adjust to implement above said task -
In Django, how do you get a count of the records in the through table that relate back to an object?
How do you get the count of the records in a table through a through table that relate backwards? My models class Player(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @property def appearances(self): return self.player_appearances.count() @property def runs(self): return self.players_batted_in_appearances.count() @property def rbis(self): pass # How do you get this? class Appearance(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='player_appearances') players_batted_in = models.ManyToManyField( Player, related_name='players_batted_in_appearances') rbis is a count of the records in the through table that relate back to the appearances for this player. The SQL query is: SELECT COUNT(*) as rbis FROM appearances_appearance_players_batted_in WHERE appearance_id IN (SELECT id FROM appearances_appearance WHERE player_id = 1) An analogous example An analogous example that might be more understandable to non-baseball fans: class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @property def books(self): # number return self.author_books.count() @property def times_critiqued_by_others(self): return self.authors_critiqued_books.count() @property def times_critiqued_others(self): pass # How do you get this? class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author_books') authors_critiqued = models.ManyToManyField( Author, related_name='authors_critiqued_books') How do you find out the number of times an author has critiqued other authors? -
Retrieve Financial Year data from table in django/python
I want to retrieve data from a table based on timestamp filed. If current month is Jan, Feb or Mar retrieve data from the table where timestamp falls between [(current year-1)-04-01,current year-03-31] and if current month is in between Apr to Dec retrieve data from the table where timestamp falls between [current year-04-01,(current year +1)-03-31]. I have written code something like as below, however I want to keep year dynamic and don't want this to be hard coded, it should be taking the current year as reference for defining timestamp__range as this will keep changing every year. if datetime.now.month in (1,2,3): received_points_history = ABC.objects.select_related('receiver', 'award') \ .filter(timestamp__range=["2019-04-01","2020-03-31"])\ .values('timestamp','receiver', 'award') else: received_points_history = ABC.objects.select_related('receiver', 'award') \ .filter(timestamp__range=["2020-04-01","2021-03-31"])\ .values('timestamp','receiver', 'award') -
Django admin: Dynamic multi database django admin
I'm trying to solve something that is being quite difficult for me and uis getting me too much headache. I want to have a single django admin with multiple databases. All databases should work with all models defined in models.py (complete django admin project). Database should be selected from url If solution does not require reboot server avery time we add a new db... much better. Example: www.domainname.com/customerA --> Complete Django admin with Database A www.domainname.com/customerB --> Complete Django admin with Database B www.domainname.com/customerC --> Complete Django admin with Database C For now, trying to make a first approach, I have a middleware.py file with this: request_cfg = threading.local() class MyProjectMiddleware: def __call__(self, request): request_cfg.URL_MAIN_WORD = request.build_absolute_uri().split("/")[3] response = self.get_response(request) return response class MyProjectDatabaseRouter(object): def _default_db( self ): if hasattr( request_cfg, 'URL_MAIN_WORD' ): return request_cfg.URL_MAIN_WORD else: #this will be an error throwing situation. return 'default' def db_for_read( self, model, **hints ): return self._default_db() def db_for_write( self, model, **hints ): return self._default_db() Then, in urls.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^customerA/' , admin.site.urls), url(r'^customerB/' , admin.site.urls), url(r'^customerC/' , admin.site.urls) ] This more or less works, but.... all links on django … -
Django generate pdf from a template with xhtml2pdf
I try to generate a pdf file from an html template in my django app. First i install library: pip install --pre xhtml2pdf then i create in my project folder an utiils.py file with this function: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None i create my html template and then in my views.py file i create the class: from yourproject.utils import render_to_pdf #created in step 4 class GeneratePdf(View): def get(self, request, *args, **kwargs): data = { 'today': datetime.date.today(), 'amount': 39.99, 'customer_name': 'Cooper Mann', 'order_id': 1233434, } pdf = render_to_pdf('pdf/invoice.html', data) return HttpResponse(pdf, content_type='application/pdf') at this point in my urls.py i add the url for start pdf creation from idocuments.views import GeneratePdf ... url(r'^fatt_doc/(?P<fat_num>\w+)/$', GeneratePdf), but when i start my app and open the link i get an error: init() takes 1 positional argument but 2 were given I think the problem is in my urls.py but someone can help me to know how i can call the function for generate pdf from an url? So many thanks … -
Python removing duplicated images
I'm trying to return random but distinct images from a given directory. I have written a function that will return a random image from a directory but I need it to return distinct images, at the moment it returns images but some of them are duplicated. What is the best way to do this? Any help would be appreciated. random_image.py def random_image(image_dir): valid_extensions = ['.jpg', '.jpeg', '.png', '.gif'] rand_dir = '/static/app_pickfeel/images/' # print(rand_dir) files = [f for f in os.listdir(settings.BASE_DIR + '/app_pickfeel/static/app_pickfeel/images') if f[f.rfind("."):len(f)] in valid_extensions] print(random.choice(files)) return rand_dir + random.choice(files) -
Django admin, add model instance across generic foreign key
I am trying to allow users to add a model instance over a generic foreign key. i.e. when a content type is selected there should be an option to add an instance of that model much like when a regular foreign key is used. This is an example model. class MenuItem(models.Model): ... content_type = models.ForeignKey( ContentType, related_name="%(app_label)s_%(class)s_content_type", on_delete=models.PROTECT, null=True, blank=True ) object_id = models.PositiveIntegerField(null=True, blank=True) content = GenericForeignKey("content_type", "object_id")