Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin and Multi-table inheritance: Show parents data in child list
like in the title i have two models: Company and PartnerCompany, the later of the two inheriting from the first model. Now, I already have a lot of saved companies that I can see in it's admin page. There is some way to show the same companies in the PartnerCompany (that inherit from Company) in it's admin page? models.py class Company(models.Model): ... ... class PartnerCompany(Company): ... admin.py class CompanyAdmin(admin.ModelAdmin): inlines = [ ... ] list_display = ('name', ...) search_fields = ['^name'] fieldsets = ( (None, { 'fields': ( ('name',...) ) }), ) class PartnerCompanyAdmin(CompanyAdmin): ... -
Django- Stuck and cannot get data to display on webpage
Here’s my issue. I can display data from one of my other tables (the stats table that I don’t show here) on my stats page and home page. That was the first time I was able to get it to work, (I am new to Django). Then I made another table in my database (the Alstandings table) and I made an app for that was well because I want a standings page. For some reason I cant get the data from my Alstandings table to display on the standings page. As far as I know I thought I replicated the process but maybe I’m missing something I don’t know about. Yes, I have registered the app in my settings. I’m not getting any errors right now. Please, if anybody has valuable input on how to get this to work, please respond. Your help will be greatly appreciated. Thank You. Standings/models from django.db import models class Alstandings(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. team = models.CharField(db_column='TEAM', max_length=30, blank=True, null=True) # Field name made lowercase. w = models.IntegerField(db_column='W', blank=True, null=True) # Field name made lowercase. l = models.IntegerField(db_column='L', blank=True, null=True) # Field name made lowercase. pct = models.DecimalField(db_column='PCT', max_digits=4, … -
Django: Custom Permission without Model
I have a reusable django app which does not have any model. This app is an optional module for a bigger project. This app has no models, but it should provide a custom permission. According to the docs you need a model to create a custom permission: See: https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#custom-permissions Of course I could create a useless empty model ..... but it feels like being on the wrong track. How to create a custom permission if the app has no models? -
Restric django developers access to models from other apps
What are the best practice to manage developers permissions on a Django project (in a Linux environment)? Let's assume I have a project with the following architecture: my_project/ manage.py my_project/ app_1/ models.py views.py urls.py app_2/ models.py views.py urls.py How can I allow someone to develop app_2 content without being able to access app_1 content? Especially the models. At the moment I manage files access via Linux permissions but my main concern is that you can import models from app_1 in the views from app_2 for example. This is actually needed in most of cases but is there a way to restrict that? What is there is confidential data in the tables from app_1 models that should not be accessible from app_2 developers? I'm not talking about basic django users permissions here, I would like to restrict how people can do import app_1.models from app_2/views.py for example. I'm probably missing a whole concept here and some best practice. -
how to get request.user in UpdateView django
I want to restrict the updateview to specefic user.How do I know which user requested the update view.I am new to django.Thanks in advance -
Emailing a Django SimpleUploadedFile without saving in a FileField
I have been struggling to email a file am generating,would love to be able to be able something like this. How do you email directly without saving the file in my model object.Getting this error 'str' object has no attribute 'read pdf_file = HTML(string=rendered_html, base_url=settings.MEDIA_ROOT).write_pdf() certificate = SimpleUploadedFile( 'Certificate-' + '.pdf', pdf_file, content_type='application/pdf') attachment = certifcate.read() msg.attach_file(attachment, 'application/pdf') -
help_text for username and email fields always output in browser
I have this model: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( _('email address'), max_length=150, unique=True, help_text=_('Required. 150 characters of fewer. Must be a valid email address.'), error_messages={ 'unique':_("A user with that email address already exists."), }, ) this form class: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username','email','password'] this view class: class UserFormView(View): form_class = UserForm template_name = 'workoutcal/register.html' def get(self, request): print("Hi again") form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('workoutcal:calendar') return render(request, self.template_name, {'form': form}) and this url: url(r'^register/$', views.UserFormView.as_view(), name='register') So when I go to /workoutcal/register, I see this: The "help text" is always shown in the browser. Is this default Django behaviour, or is it due to some error I have made? Also, how do I make the text only show up if the user has entered bad data into the respective fields? -
How to make dict always available to a particular template with Django/Jinja2?
I have a template (using jinja2) that is used in lots of views (via {% include %} statements). The template will always require (amongst other data that changes, and will be passed in via the context) a dict, that is a constant. It would be cumbersome to add the dict to the context in every view that will potentially use the template. I could add the dict as a global variable in the jinja2 env.globals, but that doesn’t seem like a particularly good idea either. It is only needed in one template in one app, not the entire project. The Jinja2 documentation mentions template globals specific to a particular template, but I can’t figure out how to implement this with Django. Any help appreciated, thanks :) -
Nginx receive post request from client server then pass request and client ip to backend specific url
I'm receiving post request from client server where it comes in with some post data and then be saved to database after being passed to my server which is running nginx, I don't know exactly how to configure Nginx to receive those request and foward them to application backend using specific url where I will be able to save them in database. I would like nginx to give the client ip address and the posted request. Thank you, Im still learning how to use Nginx properly. Here is what i have tried to do but no success server{ listen 80; server_name my_server_ip; error_log /var/log/nginx/error.log; # proxy_pass_header Server; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; } location /user/user_request/{ if ($request_method != 'POST'){ return 405; } return 200; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; keepalive_requests 10; keepalive_timeout 75s; proxy_pass http://my_server_ip$request_uri; } } -
Print as you type in Ajax using python
Problem Statement: As we type in the text box it has to display exactly the same text in the index.html file that is entered in the text field without clicking submit button using Ajax To do this I have coded in this way shown below: Index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head><title>Submit after typing finished</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> function myFunction() { var x = document.getElementById("search-input"); x.value = x.value.toUpperCase(); $('#search-input').keyup(function (event) { var query =($('#search-input').val()); if (query != '' || query != ' ') { $.ajax({ type: 'GET', url: "/ajaxmssql/XViews.py", data: { 'q': query }, dataType: "html", success: function(data) { var params = $(html).filter(function(){ return $(this).is('p') }); params.each( function() { var value = "<li>" + $(this).html() + "</li>"; $("#main-results").append( value ); } ); }, error: function(request, ajaxOptions, thrownError) { $("#debug").html(request.responseText); $("#debug").html("Could Not Print"); } }); } }); } </script> </head> <body> <h1>Print This List...</h1> <input type="print" onkeyup="myFunction()" id="search-input" placeholder="Type to Print Here ..."/> <div id="main-results"></div> <div id = "debug"></div> </body> </html> XViews.py #!C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/python.exe import cgi import cgitb cgitb.enable() def print_header(): print("""Content-type: text/html\n <!DOCTYPE html> <html> <body>""") def print_close(): print ("""</body> </html>""") def display_error(): print_header() print ("<p>An Error occurred parsing the parameters passed to this … -
django javascript value match
In the template i have following {{ form.attributes.value }}'.split(',').toString() this has value as Cluster_1_Liferay,Cluster_4_Liferay result[key] has the follwing value ji,1,Cluster_1_Liferay,Cluster_2_Liferay,Cluster_3_Liferay which comes one by one like for loop ji 1 Cluster_1_Liferay Cluster_2_Liferay Cluster_3_Liferay Now i want to put a if condition if ('{{ form.attributes.value }}'.split(',').toString().match(/result[key]/)) { alert('yes');} I should get two 'yes'. But getting non . Can anybody help . -
Any resource that explain python oop using Django source code? [on hold]
Any one knows good resource to unleash some python oop technics used in django framework? thanks. -
Transform a dictionary in a list in Python
I would like get data from id property and transform in a list queryset = [{"id":1,"name":"John"},{"id":2,"name":"John"}] Expected result ('1','2') ## ID PROPERTY -
Creating Django User object for each user in backend
I'm writing a custom backend for authenticating users by their email address instead of username. I've already written a custom User model that inherits from AbstractUser: class User(AbstractUser): email = models.EmailField( _('email address'), max_length=150, unique=True, primary_key=True, help_text=_('Required. 150 characters of fewer. Must be a valid email address.'), error_messages={ 'unique':_("A user with that email address already exists."), }, ) As you can see, I've made the email-field unique, and also, a primary key. I'm following the docs for how to write the backend, and I've read this: The Django admin is tightly coupled to the Django User object. The best way to deal with this is to create a Django User object for each user that exists for your backend (e.g., in your LDAP directory, your external SQL database, etc.) You can either write a script to do this in advance, or your authenticate method can do it the first time a user logs in. It says that I should create a Django User object (which I'm guessing is the default User object django.contrib.auth.models.User) for each user in my backend. Question 1: If a backend is a class that implements get_user(user_id) and authenticate(request, **credentials) (this is said in the docs), how … -
Django fire signal user_logged_out on browser close
I'm working on a django application with a chat for users. Therefore I need to present the status logged in or logged out to the other users. To accomplish this I used the signals environment of django. As long as the users are using the log out button everything works well. In case they are jut closing the browser or the tab there's no way to detect the status switch to offline. What is the best way to fire the user_logged_out signal, when the browser or tab gets closed? -
Where does user_id in get_user(user_id) come from?
I've read that an authentication backend needs to implement the methods get_user(user_id) and authenticate(request, **credentials). Now, user_id in get_user(user_id) must, according to the docs, be a primary key of the user model, and the method must return the user object corresponding to the user_id. My question is, where does the user_id argument come from? Is it the username/email/whatever that is entered by the user upon authentication? And if so, why does it have to be a primary key? Why can't I be free to find the intended user in any way I see fit, inside of my get_user() method? -
I'm trying to "print" and oracle query in django
I'm trying to print the result of a query in a HTML page on django. I have everything set but I don't know what to put in the HTML file to print the query. For example, my view is -
django get a full-size image per click Translated with www.DeepL.com/Translator
I use django cms, but django is very flexible. I would like to know how to get a full-size image that displays to the web user when he clicks on it. I can't find a Django application that does this, but it must certainly excite. If not, what is the best way to implement this feature? Thank you -
ImportError: No module named urls while importing urls
in urls.py i am trying to import urls but it shows error from django.conf.urls import * """ImportError: No module named urls""" -
Pluralize choices of a Model's Field and translate them
I am using Django's i18n mechanisms to translate an app in several languages. Situation I have a Model with a Field takings choices: from django.utils.translation import ugettext_lazy as _ class Offer(models.Model): WEEK = 'week' MONTH = 'month' YEAR = 'year' DURATION_CHOICES = ( (WEEK, _('week'), (MONTH, _('month'), (YEAR, _('year'), ) duration = models.CharField(choices=DURATION_CHOICES, max_length=5, blank=True, null=True, \ verbose_name=_("offer's duration"), help_text=_("Duration for which an offer, once subscribed, stays valid") If I want to display this field in a template: {{ counter }} remaining {{ offer.get_duration_display}}{{ counter|pluralize}} Where counter is an integer, offer an Offer object. Here it works well enough because plural forms for ('week', 'month', 'year') are ('weeks', 'months', 'years'), same words with an 's' ending. Problem Now let's say I want to translate my app to French. This gets tricky, because the corresponding translations are ('semaine', 'mois', 'année') and their plural forms are ('semaines', 'mois', 'années'): the translation for 'month' is the same in singular and plural forms. So what I would like to do is defining custom plural forms for each choice in the duration Field. Sure enough, I could use if statements, but this is not elegant nor practical. So I tried to find a DRY solution. … -
'NoneType' object is not iterable Error
I'm trying to find the Answer views by a user. Here's what i'm trying in view, def answer_views(request): if request.user.answer_set.all: views = Answer.objects.filter(user=request.user).aggregate(Sum('hits')) else: views = 0 return ... views Here's the hits field in model, hits = models.IntegerField(default=1) But it's raising an error, TypeError: 'NoneType' object is not iterable How can I fix that? Thank You . . . -
Django tag within URL tags
I would like to use dynamic images based on a a pk of the page. To be clearer I have a survey app, using one question per page .. which mean that the user is presented a question he answers and is redirected to the next question. Each question has a different id and I would like to attach to each question an image. Right now I have a static image lik that : <div class="col-5"> <img src="{% static 'images/RightSpeech.jpg' %}" class="img-fluid" alt="Responsive image"> </div> but I would like to make it dynamic.. I tried something like that with no success: <div class="col-5"> <img src="{% static 'images/image{{question.pk}}.jpg' %}" class="img-fluid" alt="Responsive image"> </div> any idea ? -
Django parallel are fialing if tests need to access files
I have a Django app that has many tests and it's taking a long time to finish testing, I'm thinking to run those tests on parallel, I tried but there is a problem with tests that need to access files, some tests are creating files and check if these files are created and exists in a path. For example, we have a test that will check-in a git repository and check if the git repository exists in the path. How to fix this issue? -
File lock in django
In my web application,created using django. I am reading a file from different instance and displaying the file with few editable text boxes. Once we edit it, when the save is clicked the file is written on the instance from where it is read. Now I have to lock the file once an user opens the file and edits it and tell other users to wait(but still they should be able to view the file only save cannot be done). I tried django-lock, simple Filelock. But did not get a clean example and got stuck. Note: There are no Models created. Users are created through the admin page. I read many docs where it is mentioned about models. If models are the only option how should i use it in my application. -
Django Connection Timed Out
I have installed a Django server on my home computer which is accessible from internet. The user can upload a file which is processed and than is redirected to another web page from where can download the result. The duration of input file handling can take between 30 secs to ~ 10 minutes depending of it's size. If I access the website from my home network, everything is working fine but when I access it from internet, I can only use small input files which can take up to max 30 seconds to process. If I wait for the result for more than 30 seconds, I get "Connection Timed Out" on my browser. Which would be the simplest solution to overcome this problem, either a timeout parameter config or making Django to send keep alive messages to user? Thank you