Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the rationale of using properties instead of fields within the File model of django-filer
I tried to do filtering for the extension field, which is actually not a field at all as the following example suggests. For the sake of this example, let's imagine we have a running Django with django-filer installed and some file already uploaded. >>> from filer.models import File >>> File.objects.all()[0].extension 'some_ext' # just as example But when trying to filter: >>> File.objects.filter(extension='pdf') django.core.exceptions.FieldError: Cannot resolve keyword 'extension' into field. Choices are: _file_size, clipboarditem, description, downloadfilemodel, file, filer_image_file, folder, folder_id, has_all_mandatory_data, id, in_clipboards, is_public, modified_at, name, news_attachment, original_filename, owner, owner_id, polymorphic_ctype, polymorphic_ctype_id, sha1, uploaded_at This is because extension are not stored with the model but in fact are computed properties. My question: What's the rationale of not storing this meta data in the File Model. -
Adding languages dynamically through Django Admin
If I have a project which is using english language and I have all the string fields with translator helpers like this: from django.utils.translation import ugettext as _ from django.http import HttpResponse def my_view(request): output = _("Welcome to my site.") return HttpResponse(output) But I have potential users from other languages (which I dont know which languages are yet). Is it possible to add a new language like french, russian, etc from django admin without modifying django settings and adding the language there? -
Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'
I upgraded my Django version from 1.11.5 to 2.0 and I'm trying to solve different deprecated element. However, even if my CSS/bootstrap style sheet doesn't work, I don't overcome to log into my Django software. I have this issue : 'WSGIRequest' object has no attribute 'session' This is the entire Traceback : Environment: Request Method: POST Request URL: http://127.0.0.1:8000/Authentification/Login/ Django Version: 2.0 Python Version: 3.6.2 Installed Applications: ['Institution', 'django.conf.urls', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrapform', 'django_countries', 'chartit', 'Configurations', 'Home', 'Authentication', 'Identity', 'rest_framework', 'Fiscal', 'bootstrap4'] Installed Middleware: [] Traceback: File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Authentication/views.py" in Login 26. login(request, user) File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login 130. if SESSION_KEY in request.session: Exception Type: AttributeError at /Authentification/Login/ Exception Value: 'WSGIRequest' object has no attribute 'session' In my Authentification app : # views.py file #-*- coding: utf-8 -*- from django.contrib.auth import authenticate, login, logout from .forms import ConnexionForm from django.shortcuts import render, reverse, get_object_or_404, redirect from django.http import HttpResponseRedirect, HttpResponse from .models import LoggedUsers from API_GED import Logger import datetime from django.views.decorators.csrf import … -
TypeError: __init__() missing 1 required positional argument: 'on_delete' in remote server CentOS7.2
In my Mac I use PyCharm run my Django project very well. But in the remote server I use the same commands to run my project: python3 manage.py runserver 8001 The there comes the issue: File "/var/www/html/Qiyun02//user_admin_productmanage_cloudserver/models.py", line 3, in <module> from xxx.qiyun_admin_productconfig_cloudserver.models import ( File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 109, in <module> class Disk(models.Model): File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 110, in Disk diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks') # "SAS", "SSD" and so on TypeError: __init__() missing 1 required positional argument: 'on_delete' I know the on_delete error means. but I mean, in my Mac why there do not shows the error? whether this is related to django version? My local Mac Django version is 1.11.2. The remote server CentOS7.2 version is python-django-1.8.14-1.el7.noarch EDIT Please, I know the on_delete error in there, I mean, in my Mac, there is no the reminds, why I copy to the CentOS7.2 remote server there comes this issue? whether this is caused by django version? -
WSGIDaemonProcess, Etc. Causing Connection Timeout in Debian 9
I was previously running Debian 8 and hosting my Django app using the following setup: Django 1.11 mod-wsgi 4.5 apache 2.4 mysql Now that I have updated to Debian 9, and using mariaDB, I am having an issue using the following settings in my apache2.conf file: LoadModule wsgi_module "/root/.virtualenvs/user/local/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so" WSGIScriptAlias / /home/user/web/user.com/project/project/wsgi.py WSGIDaemonProcess user.com socket-user=user group=user processes=2 threads=25 WSGIProcessGroup user.com WSGIPythonHome "/root/.virtualenvs/user" <-- outside of virtual host I took each line out to see which was causing the issue, with LoadModule wsgi_module "/root/.virtualenvs/user/local/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so" being the only one that was allowed to be in there and not cause the site to hang. By taking out all of those lines, my site works (albeit, without static files) and is not running in Daemon mode... My error logs show nothing except the following: 2017/12/05 08:59:15 [error] 446#446: *80 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: X.X.X.X, server: website.com, request: "GET / HTTP/1.1", upstream: "http://X.X.X.X:8080/", host: "website.com" 2017/12/05 09:00:00 [error] 446#446: *80 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: X.X.X.X, server: website.com, request: "GET / HTTP/1.1", upstream: "http://X.X.X.X:8080/", host: "website.com" How do I fix this?? -
How to install HTTPS on django with python hendrix server?
Which is the best method to install https on a django project running on hendrix server ? Could you describe your favorite cooking recipe step by step ? (pip install ..., app to add, settings vars, middleware, hendrix configuration) -
NoReverseMatch error in rendering Django
Below is my views.py. After the POST, user gets a success page showing the 5 Items. At the same time I also want to show environment to the user. So I did something like below (passed environment as an argument). I get that while the redirect happens, it tries to find something like success and the environment argument match which it is not able to get. Probably I need right regular expression to handle this and I am not sure how to handle this. def order_create(request): cart = ItemObject.objects.all() if request.method == 'POST': ... environment = envi_dict1.difference(item_dict1) return HttpResponseRedirect(reverse('success', kwargs={'environment': environment})) else: form = ItemObjectCreateForm() return render(request, 'index.html', {'form': form}) def successView(request): return render(request, 'success.html', {'items': ItemObject.objects.filter(gp_code='Unknown')[:5]}) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^export_action/', include("export_action.urls", namespace="export_action")), url('^business-logic/', include('business_logic.urls')), url('^index/', views.order_create), url(r'^success/', views.successView, name='success') ] The error I am getting is this NoReverseMatch at /index/ Reverse for 'success' with keyword arguments '{u'environment': set([u'Test1'])}' not found. 1 pattern(s) tried: ['success/'] -
Django pdf viewer
views.py def pdf(request, lec_id): if not request.user.is_authenticated(): return render(request, 'Home/login.html') else: user=request.user lectu=get_object_or_404(Lecture,pk=lec_id) return render(request, 'Home/pdf.html', {'lectu':lectu,'user':user}) pdf.html <h1>start</h1> <iframe src="{{ lectu.PDF_file }}" width='800' height='800' frameborder='0'></iframe> end But it's show this [i want to open pdf file in pdf viewer like google pdf viewer with django but here is one problem in this image] -
Django Deep Linking render with #tag
I am trying to Deep Link tabs with Dango by adding the #panel1 at the end. This would be the template needed: template = "charts/chart1.html#panel1" return render ( request, template, context ) But obviously Django can not find that template once I add the hashtag. Is there a way to overcome this issue? Thank You. https://foundation.zurb.com/sites/docs/tabs.html -
Django forms.VaildationError not showing on a class based view
My forms.validationerror is not showing. Below is my form that I am using. The if statement works and it detects the issue, and prints out the content successfully. As a lot the existing errors on stackoverflow suggest, the content is not None as shown in the print statement. class PollItemMessageAddForm(forms.ModelForm): class Meta: model = Message fields = [ "content" ] labels = { 'content': 'Add your comment', } widgets = { 'content': Textarea(attrs={'cols': 10, 'rows': 5}), } def __init__(self, *args, **kwargs): # this line should be before a super call self.request = kwargs.pop('request', None) super(PollItemMessageAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', value='Post', css_class='buttonspace btn-success')) def clean_content(self): content = self.cleaned_data.get("content") if len(content) > 50: print content raise forms.ValidationError("Please limit your message to less the 50 characters") return content Below is my views.py post statement in my class based view, which skips the form.isvalid to be redirected to the same url where the error message should appear. I am using a detailview and formmixin in my class based view if it helps. I cant see where the issue is coming from in the absence of a traceback. Any help would be appreciated. def post(self, request, *args, **kwargs): url = … -
Comparing dates in Django does not work
I have a problem comparing dates in Django. I followed the hint How to compare dates in Django but it does not work. Maybe you can help me. My code: modelys.py class Customer(models.Model): last_updated = models.DateTimeField(auto_now_add=True) views.py @property def is_past_due(self): return (date.today() - self.date)> timdedelta(1) home.html {% if customer.last_updated.is_past_due %} <td class="table-danger">{{ customer.last_updated }}</td> {% else %} <td class="align-middle">{{ customer.last_updated }}</td> {% endif %} I am using Bootstrap, so when the difference between two dates has a more than one day I want a tablefield to become 'danger'-ous ;-), but nothing changes. Thanks in advance. -
Using django tag in a div ID
I am trying to generate dynamically an ID in my app using bootstrap dropdown menu but for some reason it does not appear .. <div class="dropdown"> <button class="btn btn-secondary btn-sm btn-canvas dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Compare with </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for i in team_list_pop %} <a class="dropdown-item" id="{{i.first_name}}" href="#">{{i.first_name}} {{i.last_name}}</a> {% endfor %} </div> </div> and the output when I do inspect in my browser <a class="dropdown-item" href="#">John Doe</a> with no traces of the ID. how can I get to hve an output <a id="john" class="dropdown-item" href="#">John Doe</a> thx you very much -
Many-to-many relationship with 'through' model returning error on migration
I'm trying to implement a system which allows for two Profile model objects to be a part of a Pair model object. Here is the Profile, followed by a Pair model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) pair = models.ManyToManyField('self', through='Pair', symmetrical=False, related_name='pair_to+') class Pair(models.Model): requester = models.ForeignKey(Profile, related_name='pairing_requester') accepter = models.ForeignKey(Profile, related_name='pairing_accepter') requester_learns = models.CharField(max_length=60, null=True) requester_teaches = models.CharField(max_length=60, null=True) The relationship between profiles should be symmetrical, such that (profile1, profile2) are a unique object and I should not expect a (profile2, profile1) to be created. So, per this article, I am trying to create the relationship. Upon makemigrations, I am receiving the error: ERRORS: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8>: (models.E022) <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8> contains a lazy reference to user_profile.pair, but app 'user_profile' doesn't provide model 'pair'. user_profile.Profile.pair: (fields.E331) Field specifies a many-to-many relation through model 'Pair', which has not been installed. What am I doing wrong? -
Django form is not displaying
I am new to django forms and while trying to design an HTML form, I notice that the django form blocks are not displaying. Below are the codes: <body> tag of index.html: <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="panel panel-login"> <div class="panel-heading"> <div class="row"> <div class="col-xs-6"> <a href="#" class="active" id="login-form-link">Login</a> </div> <div class="col-xs-6"> <a href="#" id="register-form-link">Register</a> </div> </div> <hr> </div> <div class="panel-body"> <div class="row"> <div class="col-lg-12"> {% block login_content %} {% endblock %} {% block register_content %} {% endblock %} </div> </div> </div> </div> </div> </div> </div> login.html which goes into the {% block login_content %} {% extends 'index.html' %} {% block login_content %} <form id="login-form" action="{% url 'authentication:user_login' %}" role="form" style="display: block;" method="POST"> {% csrf_token %} <label for="username">Username:</label> <input id="username" type="text" name="username" placeholder="Enter Username" tabindex="1" class="form-control"> <label for="password">Password:</label> <input id="password" type="password" name="password" tabindex="=2" class="form-control" placeholder="Password"> <button type="submit" class="btn btn-success">Login</button> </form> {% endblock %} register.html that goes into the {% block register_content %} {% extends 'index.html' %} {% block register_content %} <form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit" name="" value="Register"> </form> {% endblock %} On my UI, the {{ user_form.as_p }} and the {{ profile_form.as_p }} does … -
get dictionary from queryset
I have below query where I want to fetch 'specs' which is a dictionary but the type of envi_dict is a Queryset class. How do I fetch the dictionary from this queryset? Any help is much appreciated. envi_dict = Environment.objects.values('specs') Result <QuerySet [({u'CPU Model': u'Dell', u'RAM': 1000, u'CPU': 400},), ({u'CPU Model': u'Dell', u'RAM': 1000, u'CPU': 400},)]>, <class 'django.db.models.query.QuerySet'>, ) I tried Environment.objects.filter(title=item.title).values('specs') and also Environment.objects.get('specs') but I am still getting a queryset. -
How to handle special character in file path of a file in python
file_path : "/home/encoding/What Is A_ V Can?and Can't?It Offer Us_ (ABC) (720p_30fps_H264-192kbit_AAC).mp4" File exists in server but my python code unable to find file due to special characters. import os print os.path.isfile(file_path) This giving me False. -
Override url and view from reusable app
Please answer only for django 1.10+ where patterns() is removed. I want to override "inbox" from django-postman with custom url and custom view. For example I have url(r'^myurl/$', my_view, name='inbox'). How can I get my url from reverse('postman:inbox') instead of built-in url(r'^inbox/(?:(?P<option>m)/)?$', InboxView.as_view(), name='inbox')? I use this method, but it may be dirty: from postman.urls import urlpatterns as postman_urlpatterns merged = ([ url(r'^myurl/$', my_view, name='inbox') ] + [ u for u in postman_urlpatterns if u.name != 'inbox' ], 'postman') urlpatterns = [ url(r'^', include(merged)) ] Is there a cleaner method? -
Django-filters how to pass current user from view inside FilterSet?
I have a filter where I need to access the request.user. However, Django-filter does not pass it. I was able to figure out possible FilterSet configuration. But how to pass current user from view inside FilterSet? filters.py class TransationsListFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(TransationsListFilter, self).__init__(*args, **kwargs) transaction_date = DateFromToRangeFilter(widget=RangeWidget(attrs {'placeholder': 'DD/MM/YYYY'})) class Meta: model = Transations fields = ['transaction_date'] @property def qs(self): return super(TransationsListFilter, self).filter(user=user) views.py class TransactionsList(PagedFilteredTableView): model = Transations table_class = TransactionsTable filter_class = TransationsListFilter formhelper_class = TransationsFormHelper models.py class Transations(models.Model): transaction_date = models.DateField(default=datetime.now, blank=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default = 0 ) -
django using angular 4 in apache server static files cannot be loaded
I am using angular 4 for frontend for django application. I used "ng build --target=production --environment=prod --aot=false" for building dist and collectstatic to put files in static folder. It is working fine while running on a port but while running on apache server is not working because of the relative paths of bundle js and css files. Any help is greatly appreciated. -
how to convert django models into dictionary representation
i want to convert my django base database models into dictionary objects. Note: I need only dictionary(json) representation of my model classes not data. -
Django: Track changes in models
I want to track changes in the model, basically log every function in views.py.. so that whatever changes are made to the model are reflected in the log file. views.py def func_detail(func): @wraps(func) def func_wrapper(*args, **kwargs): logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) print("Inside wrapper. Calling method %s now..."%(func.__name__)) r = func(*args, **kwargs) logging.getLogger(__name__) return r return func_wrapper class UsersViewSet(viewsets.ViewSet): @func_detail def update(self, request, pk=None): users = get_object_or_404(Mytable, name=pk) serializer = CheckSerializer(users, data=request.data) if serializer.is_valid(): serializer.save() logging.info("Updated required data") return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) **models.py** class Mytable(DjangoCassandraModel): name = columns.Text(primary_key=True) email = columns.Text() password = columns.Text() creation_date = columns.DateTime(default=datetime.datetime.today()) modified_on = columns.DateTime(default=datetime.datetime.now) For example: If I make changes to my "name" field from 'abc' to 'xyz', it should reflect that changes has been made to the "name" field from 'abc' to 'xyz'. I don't have to use any third party packages. Only add few lines of code in 'def func_detail' that would dynamically track changes and update. if anybody has nay idea then please help. Thanks in advance. -
How would I implement a "unique_together" constraint going both ways?
I'm seeking unique_together functionality with two fields that goes both ways. Say, if I had two fields like this: class Pair(models.Model): requester = models.ForeignKey(Profile, related_name='pairing_requester') accepter = models.ForeignKey(Profile, related_name='pairing_accepter') class Meta(): unique_together = ('requester', 'accepter') How can I make sure that not only is one combination of two Profiles (requester=a, accepter=b) unique, but the other way around as well? (requester=b, accepter=a). I don't mean to create two Pair objects. I mean one pair would make sure that the two Profiles cannot be created in another pair with the roles exchanged. -
Django translations RTL langauage
I am trying to set my django project to support arabic language , but i am still not getting anything right . my settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] USE_I18N = True LANGUAGES = ( ('ar', _('Arabic')), ('en', _('English')), ) LANGUAGE_CODE = 'en-us' LOCAL_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) my index.html {% trans "Hello and welcome" %} <p>{% blocktrans %} hello dear friends, i would be very happy if you can help!! {% endblocktrans %}</p> </br> {{ request.LANGUAGE_CODE }} urls.py urlpatterns += i18n_patterns( url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), ) after that to make the .po file i used the command : python manage.py makemessages -l 'ar' and after i get the .po file , i have added my translations in 'msgstr', then used the following command to compile the translated string : python manage.py compilemassages then i logged in , and changed the language code to 'ar', in the url(127.0.0.1:8000/ar) , but still i am getting the english strings , and not its translation , so any idea about what is that i am doing wrong . Thanks -
How to implement logout in django in template?
This is my views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import os # Create your views here. @csrf_exempt def index(request): if('loggedIn' in request.session): id = request.session['uid']; return render(request,"index.html",{'uid':id}); else: return render(request,"index.html",{}); urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index) ] This is the first time I am doing a Django project. I was able to log in and now see the index page. Now I have a logout button as Logout So, what can I need to do to log out from the system.. Please I am not getting idea behind the same.. It will be great If, somebody helped me. -
R Shiny vs. Python (Django, Flask, etc.) for web application development
I could not find a comprehensive resource listing out the potential pros/cons of choosing Python over R (or vice-versa) for building a large-scale web application. To my knowledge, R's flagship product for this purpose is R Shiny, while Python's is Django and Flask. Since both programming languages are extremely popular for data science, it would make sense to at least weigh the pros/cons of choosing one language over the other before setting out to build a great web app. I've seen a lot of useful R vs. Python discussions (but also flame-wars) across various sectors (machine learning, natural language processing (NLP), etc.) but have yet to see constructive discussion/criticism applied to building web applications in one or the other language. Note that I am not asking for when to choose one language over another for a specific field/purpose (e.g., deep learning, NLP, etc.), nor am I interested in using both languages together within the same web app (e.g., using R's reticulate package or Python's rpy2 package). I am merely interested in the considerations I should think about before choosing R or Python as my primary language for web app development, since I can always use the other language to supplement …