Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to convert formset to dict and json
In DJango how to convert formset to dict and later to JSON. I want to render it in reactjs later. -
How to use access django template variable in a separate js file rather than inlcuding small script block in same html file?
I am not able to access template variables passed from views.py file in django. I coudldn't find any answer on stackoverflow yet. I have tried everything like converting the variable to json object and parsing it in the separate js file. How to access the template variable from views.py in a separate .js file ?? -
Deep-learning on an Auction project
Deep learning is still something I would like to experiment, and I was waiting a little project to start with, something that would have a lot of data. But now that I have it, I still don't know if deep learning is the way to go for this task.. The concept is still blurry in my mind. So I need advise from some people more experienced in this field. I have lot of data, downloaded from a REST API (Blizzard, WoW, Auction House). Everything is going into a local Django project, formatted and inserted into a database. It's working like a charm. But now I would like to filter a bit those data to make them more readable. An auction model looking like this : class Auction(models.Model): auc = models.IntegerField(primary_key=True) item = models.IntegerField() owner = models.CharField(max_length=12) ownerRealm = models.CharField(max_length=20) bid = models.IntegerField() buyout = models.IntegerField() quantity = models.IntegerField() timeLeft = models.CharField(max_length=9) # SHORT(<30mn), MEDIUM(30mn-2h), LONG(2h-12h), VERY_LONG(12h-48h) lastModified = models.DateTimeField(blank=True) # Basically I have a Celery task running, that will update the database every 15 minutes. So lastModified field would be updated if auction already exist, and timeLeft too. Would it be possible to train a neural network to give me … -
How to add multiple tags to URL in Django and Taggit
I have this model here, where I pass the tags using TaggableManager. class Post(models.Model): title = models.CharField(max_length=120) content = models.TextField() date_published = models.DateField(auto_now_add=True) tags = TaggableManager() slug = models.SlugField(max_length=40, blank=True) And this is how I view the data: class TagView(ListView): model = Post template_name = 'tagview.html' paginate_by = 10 def get_queryset(self): return get_list_or_404(Post, tags__slug = self.kwargs.get('tag')) def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['tag'] = self.kwargs.get('tag') return context This works as per 1 tag, but I want to include multiple tags, I've searched a lot but couldn't think of how to implement it. This is my urls.py - path('tag/<slug:tag>/', views.TagView.as_view(), name='tagview'), -
Django - gunicorn - Nginx cache problem, rendered view does not reflect change when I add new data
Hello I deployed video Django website to digital ocean recently. I am using Django 2.08, gunicorn and nginx. I am showing videos as grid with thumbnails, when I publish new videos, returning visitor does not see added videos, visitors see last cached version of website. I am using django only a few months so I might have serious issue somewhere, I am not sure what is causing this behavior, if problem is in Nginx, gunicorn or django. Below you can find my source files. Can somebody tell me why I don’t see fresh version with new data? When I want to see fresh website I have to refresh page once more again, then it is visible. My settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'supersecretkey' DEBUG = False ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainSite', 'django_cleanup', 'debug_toolbar', 'django.contrib.sites', 'django.contrib.sitemaps', 'axes' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, 'axes_cache': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } AXES_CACHE = 'axes_cache' AXES_FAILURE_LIMIT = 5 AXES_IP_WHITELIST = "127.0.0.1" AXES_COOLOFF_TIME = 1 AXES_BEHIND_REVERSE_PROXY = True AXES_REVERSE_PROXY_HEADER = 'HTTP_X_REAL_IP' AXES_META_PRECEDENCE_ORDER = ('HTTP_X_REAL_IP','HTTP_X_FORWARDED_FOR',) ROOT_URLCONF = 'video.urls' TEMPLATES = … -
Django queryset contains
My code is queryset = Product.objects.filter(category=2) for i in queryset: for j in Windows_system_apps: if i.name in j: i.app_type = 1 i.save() pattern = ["alpha123", "delta1", ... ] For the products model, I have to check if the names of the products contain a pattern, where pattern is of type list. My question is can I implement above logic using __contains and __in filters? -
Django 2.1 Why project`s __init__.py called twice?
In a Django project I modified __init__.py in the directory with the settings.py file because I need to execute some of my own code before the Django project starts. There is a print(True) in this __init__.py file When I run python3 manage.py runserver the console output two True, why? I want to know why there are two outputs, and what can I do to display only one? -
Django Rest Browsable API available at different url
Is there any way to access Django Rest user interface in different address than api url itself? E.g somwhere in Django admin ( exampleUrl.com/admin.api ) I've tried to extend admin template end add {% extends 'rest_framework/base.html' %} but it returned following error: 'NoneType' object has no attribute 'items' Any idea how to solve this? -
Could not import settings: cannot import name _uuid_generate_random
I am trying to set up my project and environment in a different machine, and ran into some trouble with the settings files. When trying to run any manage.py with any settings file I am always getting the same error: ImportError: Could not import settings 'mysite.settings.mysettings' (Is it on sys.path?): cannot import name _uuid_generate_random This is the output of sys.path: C:\WINDOWS\SYSTEM32\python27.zip C:\Python27\DLLs C:\Python27\lib C:\Python27\lib\plat-win C:\Python27\lib\lib-tk C:\Python27 C:\Python27\lib\site-packages When I run python mysettings.py there is no problem, so the import error should not come from there. -
Multiprocessing with django
I have to generate a report of some data and it sometimes gets huge and take up to 20 minutes to finish. Using celery just for this won't justify the costs so I'm stuck starting a thread to perform the processing in the background. I read about multiprocessing with django and it turns out I should close all connections manually, otherwise I would end up with active connections duplicated over to the thread. I'm not sure if this is still a thing but I will do it anyways. Currently I'm just calling the close_all method and the django seems to reestablish them in both the parent and child thread. db.connections.close_all() thread = threading.Thread(target=build_export_method) thread.setDaemon(True) thread.start() Is this enough to prevent unwanted db connections to linger? -
Checking if package is older than 24 hours with bash
I would like to check if my last file is older than 24 hours or not. (project in django) I have many zip packages in directory so I have to 'filter' the last one with this part of code: ls -1 | sort -n | tail -n1. My code in .sh file: #!/bin/bash file="$HOME/path_directory ls -1 | sort -n | tail -n1" current=`date +%s`; last_modified=`stat -c "%Y" $file`; if [ $(($current-$last_modified)) -gt 86400 ]; then echo "File is older that 24 hours" | mailx noreply@address -s "Older than 24 hours" me@mailmail.com else echo "File is up to date."; fi; Here is an error, that I got: stat: invalid option -- '1' Try 'stat --help' for more information. /path_directory/imported_file.sh: line 9: 1538734802-: syntax error: operand expected (error token is "-") If somebody made something similar, please some hint. -
Why does nginx randomly throw "403 - Forbidden" errors?
I configured Nginx, uwsgi and Django with help of this tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html. But I'm not using a socket, a wsgi ini file, a system wide installation or the emperor mode. The problem that occurs is a 403 - Forbidden. But this error seems to occur randomly across machines and browsers. For example I can connect to the website via Edge with no problem, but Firefox on the same machine throws a 403 (I use a win home 64 bit machine). Firefox on my Iphone 5 connects with no problem as well as Safari. I red that this error may occur with wrong permissions but I set the permissions recursively like this: chown -R kltc:kltc /home (axample) chmod -R ug+r /home (example) The only change I made to Nginx (/etc/nginx/nginx.conf) was uncommenting the 'server_names_hash_bucket_size 64'. How is this possible ? -
Django and python memcached and session engine
I have a question about setting cache with memcached in a django project. in settings.py file i have: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 120 } } it works but the default session_engine in django is django.contrib.sessions.backends.db but when i change the setting to django.contrib.sessions.backends.cache i have the following error: The request's session was deleted before the request completed The version of django that i use is django 1.11 i searched the community about similar questions but i couldn't figure out a solution -
Django got error cannot import name AppRegistryNotReady while importing session_security
I am facing one error on django1.5.12 while importing session_security.middleware. Got bellow message File "/opt/.virtualenvs/lottostar/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 51, in load_middleware raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) ImproperlyConfigured: Error importing middleware session_security.middleware: "cannot import name AppRegistryNotReady" Can please someone advice if you have? Thanks in advance. -
Django admin customization(w/o using themes like jet,suit)
Can you please help me out, with django admin customization, on which I require the filter panel to be placed at top of the page. Can we also update the other templates as well in some fashion. I have read the official docs for django admin. But i am unable to implement as I am new to django and frontend. Thanks in advance! God bless y'all ! :) -
How to filter records by range of date in django?
Can I filter records by range of date given by the user? I want to create a Daterange form(it will contain start date and end date) in django where the user will give their specific dates and it will filter the objects based on that dates given by the user... Can I perform this in Django? -
how to use datetime-local input in Django
I am using datetime-local in input field but if i use that my form was not valid so in this case what should i do? <input class="form-control pmd-z-depth-1 shadow-demo" id="updateend_date" type="date" name="end_date"> Output 2018-01-01T01:00 Expected Output 2018-01-01T01:00Z -
using django authentication password_reset_confirm error
I have an error with password reset. If I attempt to reset using an invalid email I get the password reset sent notice. If I use a valid email I get NoReverseMatch error message from django.conf.urls import url from django.contrib import admin from . import views from django.contrib.auth import views as auth_views from django.urls import reverse, reverse_lazy, resolve # Password URL's ################################################################################################### url(r'^change-password/$', views.change_password, name='change_password'), url( r'^password_reset/$', auth_views.PasswordResetView.as_view( template_name="registration/password_reset.html", email_template_name="registration/password_reset_email.html", success_url=reverse_lazy("partners:password_reset_done"), # might be required ), name='password_reset' ), url(r'^password_reset_done/', auth_views.PasswordResetDoneView.as_view( ), name='password_reset_done' ), url(r'^password_reset_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', auth_views.PasswordResetConfirmView.as_view( template_name="registration/password_reset_confirm.html", success_url=reverse_lazy("partners:password_reset_complete"), # might be required ), name='password_reset_confirm' ), url(r'^password_reset_complete/$',auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), ] Please see my screen grabs for my project structure and the error message project structure error message received {% block head %} <meta charset="UTF-8"> <title>Welcome ! You can login here !</title> {% endblock head %} {% block body %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm-6 col-md-3"> <h3>Password Reset Email</h3> <p>Provide your registered email address </p> {% autoescape off %} To initiate the password reset process for your {{ user.get_username }} TestSite Account, click the link below: {{ protocol }}://{{ domain }}{% url 'partners:password_reset_confirm' uidb64=uid token=token %} If clicking the link above doesn't work, please copy and paste the URL … -
how to use datetime-local in input field in django
I am using datetime-local in input field but if i use that my form was not valid so in this case what should i do? <input class="form-control pmd-z-depth-1 shadow-demo" id="updateend_date" type="date" name="end_date"> Output 2018-01-01T01:00 Expected Output 2018-01-01T01:00Z -
django export csv issue while reading foreignkey field
here is my models.py class RegistrationOTP(models.Model): country = models.ForeignKey(Country,on_delete=models.CASCADE, related_name='otp_country', default=1) phone_number = models.CharField(max_length=13)#, unique=True, validators=[phone_regex], otp = models.PositiveIntegerField() created_date = models.DateTimeField(auto_now=True) is_verified = models.CharField(choices=YES_OR_NO, default='no', max_length=10) def __unicode__(self): return '%s : %s'% (self.phone_number, self.otp) here is my admin.py class RegistrationOTPResource(resources.ModelResource): class Meta: model = RegistrationOTP fields = ('id','phone_number','otp','created_date','is_verified','country') def to_representation(self, instance): rep = super(RegistrationOTPResource, self).to_representation(instance) rep['country'] = instance.country.name return rep class RegistrationOTPAdmin(ExportMixin, admin.ModelAdmin): resource_class = RegistrationOTPResource admin.site.register(RegistrationOTP, RegistrationOTPAdmin) In my csv country field is showing country id instead of country name. how can i show country name.. please have a look into my code -
Django admin return query results to my change_list template
In my django project i would to display results of my ORM query in my personalized change_list.html template. I do this: in admin.py: class temp_libraryAdmin(admin.ModelAdmin): list_filter = ('main_id__descr', 'l_type') def change_list(self, request, extra_context=None): #Here we'll write ORM query, now test dict extra_context = { 'cc': '123', } return super(temp_libraryAdmin, self).changelist_view(request, extra_context=extra_context) well, now in my footer block on change_list page: {% block footer %} <div id="footer-main"> <p>FOOTERR</p> {% for lf in extra_context %}{{ lf.cc }}{% endfor %} </div> {% endblock %} but nothing is shown on my page. How can i display data from a query in my admin page? thanks in advance -
Mix VueJS data and django include tag
Let's consider this include tag {% include 'snippets/template.html' with first_name=first_name %} I want to set the first_name parameter with a vue value (this.first_name) Setting the vue variable inside the include tag does not work. How can I retrive my vue data in my include tag? -
Django AdminDateWidget only appearing once on form
I'm fairly new to using the django framework and I'm putting together a site using the AdminDateWidget. With the help of another post I've got the widget working but it's only appearing once on the form when I've defined two fields. If I comment out either of the fields it will appear on the other but I'm unable to get it to appear on both at the same time. Code from my forms.py class CertForm(forms.ModelForm): class Meta: model = cert #fields = ('title','created_date') fields = '__all__' widgets = { 'created_date': AdminDateWidget(), 'expiry_date': AdminDateWidget(), } Any suggests? Thanks -
Adding DateTime Lookup on a Django FilterSet
with the new django-filter v2 coming out. I was wondering how i could replicate the below functionality with it. Before my filterset was as so class PostFilterSet(filters.FilterSet): date = filters.DateFilter( name='date', lookup_expr=DATETIME_LOOKUPS, method='filter_date') class Meta: # Meta Options here def filter_date(self, queryset, name, value): # filter logic What this would essentially let me do on the api is make filter request like this 'https://example.com/api/post/?date__gt=exampledate' but with the latest update i can no longer keep the list of DATETIME_LOOKUPS and have to use the Lookup choice filter which changed the request to 'https://example.com/api/post/?date=exampledate&date_lookup=exact' is there a way to make it work like it did before in a painless way ? -
Django - Import .txt file to populate data
I'm trying to create a Django web app with data on transactions between salespersons and customers. The source of the data is a .txt file and I was wondering if there is a more efficient way to import all the data without manually adding them from the admin page. I have a html template for a form that allows a file upload, but i can't seem to get the file through request.file CSV-Upload.html {% load static %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <button type="submit">Upload</button> </form> {% endblock %} views.py @permission_required('admin.can_add_log_entry') def data_upload(request): template="CSV_upload.html" if request.method == "GET": return render(request, template) txtfile = request.FILES['file'] stripped = (line.strip() for line in txtfile) lines = (line.split(",") for line in stripped if line) with open('log.csv', 'w') as out_file: writer = csv.writer(out_file) writer.writerows(lines) for line in txtfile.readline(): row = line.split(',') _, created = Transaction.objects.create( TrxnNo=row[0], DocRef=row[1], AcCrIsMinus1=row[2], CxNo=row[3], AcCurWTaxAmt=row[8], HomeWTaxAmt=row[9], ProjNo=row[10], LocNo=row[11], SalesNo=row[12], ) _, created = Document.objects.update_or_create( DocRef=row[1], DocDate=row[0], ) _, created = Customer.objects.update_or_create( CxNo=row[3], CxName=row[4], Postal=row[5], CxContact=row[6], AcCur=row[7] ) _, created = Project.objects.update_or_create( ProjNo=row[10], ) _, created = Location.objects.update_or_create( LocNo=row[11], ) _, created = SalesPerson.objects.update_or_create( SalesNo=row[12], SalesName=row[13], SalesContact=row[14] ) context = {} return render(request, template, …