Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a HttpResponse in a permission custom decorator?
I'm creating a decorator for 5 views I have. That decorator redirects the user in case he's not authenticated or has no permission. But in case the user is authenticated and has permission, he should get the page. The problem is that I get a 'The view myapp.views.wrapper didn't return an HttpResponse object. It returned None instead' How can I use a return HttpResponse ... to redirect the user to the view he tried to access? This is the code: def ask_permission(func): def wrapper(request, *args, **kwargs): if not request.user.is_authenticated: return redirect('login') if not (request.user.groups.filter(name__in=["group_1", "group_2", "group_3"]).exists()): return redirect('access_denied') # redirect HttpResponse should be here return wrapper What's the code for redirect HttpResponse I'm missing? -
internal server error while deploying django app
I am getting an internal server error while deploying a django app to aws. Can someone please help me to fix the issue ? ]2]3]4 -
Where the views functions are invoked?
Suppose such a quick example of Django project, When I issue request http://127.0.0.1:8001/ from the browser, will get response of article/index.html The views.py def index(request): block_info = Block.objects.order_by("id") return render(request, "article/index.html", {'blocks':block_info}) The urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^$", views.index, name="index"),] What confused me is that during the process, function index(request) was not invoked explicitly. like def index(request): block_info = Block.objects.order_by("id") return render(request, "article/index.html", {'blocks':block_info}) index(request) Where the views functions are invoked? -
Django email attaches attachments as text to the bottom of the email
I'm using django to send an email, using django's built in from django.core.mail import EmailMultiAlternatives. It is supposed to be attaching a number of .eml files, and a couple of CSVs. The CSVs attach as expected, but the .eml files do two things: they attach, but they also appear, in full, in the body of the email. I assume that this is because they are .eml files, but is there a way to stop them from doing so? For example, the email arrives looking like this: Body of email Full content of foo.eml Full content of bar.eml Attachments: foo.eml, bar.eml, x.csv I would like the full content of foo.eml and bar.eml not to appear in the actual body of the email. The attachment command is msg.attach_file(attachment.name, attachment.path) -
TemplateSyntaxError with static django 2
I have this code: HTML {% load static %} <!--[if lte IE 8]><script src="{% static game_reviews/css/ie/html5shiv.js %}"></script><![endif]--> settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'game_reviews',] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',] STATIC_URL = '/static/' i had a folder inside my app called static/game_reviews, and inside have multiple folder (js, css, etc.). and i getting this error : TemplateSyntaxError at /game_reviews/ Could not parse the remainder: '/css/ie/html5shiv.js' from 'game_reviews/css/ie/html5shiv.js' Any help?. Thanks in advance. -
Django pt-br translation works on development but not in production
I added a Portuguese translation to my django application. At first it didn't work because it turns out that the folder has to be name pt_br, even though the language code in settings should be pt-br. I fixed this part and it works fine in development (I can see the translation). However, in production, all the translations work except the Portuguese one. I suspect that the fact that I first tried with a pt-br folder instead of pt_br messed it up somehow and now I can't get the app to discover the translation. Any idea what could cause this? -
dictionary update sequence element #0 has length 1; 2 is required when loading page
i saw multiple same topics but non of them solved my problem . I just created a django project , build an app called News. when i try to load page i got this error : dictionary update sequence element #0 has length 1; 2 is required Here is first urls: from django.contrib import admin from django.urls import path from django.conf.urls import url,include urlpatterns = [ path('admin/', admin.site.urls), url(r'',include('News.urls')) ] And Here is News urls : from django.conf.urls import url from . import views urlpatterns = [ url(r'', views.LoadHome.as_view, 'home_page') ] And finally my view : class LoadHome(generic.TemplateView): template_name = 'index.html' Whats the problem ? -
Is there way a to pass URL values in html files in django templates using constant substitution?
This is Django problem. I am a newbie to this. This is my url.py file from django.urls import path from splunkAutomation.logic.Constants import Constants from . import views app_name = 'splunkAutomation' urlpatterns = [ path(Constants.URL_FOR_SEEING_ALL_SPLUNK_QUERIES,views.viewForSeeingAllSplunkQueries, name=Constants.NAME_OF_URL_FOR_SEEING_ALL_SPLUNK_QUERIES), ] I want to be able to reference this name "Constants.NAME_OF_URL_FOR_SEEING_ALL_SPLUNK_QUERIES" in html template. The following is the snippet from the html file <ul class="actions"> <li><a href="{% url 'splunkAutomation:splunkQuerySpecific' query.id %}" class="button special">Check</a></li> </ul> Basically I want to use the constant substitution instead of {% url 'splunkAutomation:splunkQuerySpecific' query.id %} Is there a way to use this ? -
Using Django Admin panel object creation functionality with Multiple-to-Multiple models
I am trying to use django admin board functionality to be able to insert data within admin panel into tables with one-to-multiple and multiple-to-multiple relations. I used __str__ functionality (Python 3.6) in order to create understandable strings in admin panel instead of "Testcase object(1)" like description to be able to select proper testcase id and testrun id for executedtests model. But it looks like admin panel during executedtest object creation instead of testcase id value and testrun id value tries to set foreign int keys to a corresponding text value. I miserably fail with error: tc = Testcases.objects.get(pk=self.testcase_id) ... TypeError: int() argument must be a string, a bytes-like object or a number, not 'Testcases' Models: class Testcases(models.Model): name = models.CharField(max_length=30) def __str__(self): return f"Testcase: {self.name}" class Testruns(models.Model): starttime = models.TimeField() endtime = models.TimeField() def __str__(self): return f"Testrun: {self.starttime} - {self.endtime}" class Executedtests(models.Model): testcase_id = models.ForeignKey("testcases", models.CASCADE) testrun_id = models.ForeignKey("testruns", models.CASCADE) teststart = models.TimeField(blank=True, null=True) # This field type is a guess. testend = models.TimeField(blank=True, null=True) # This field type is a guess. def __str__(self): tc = Testcases.objects.get(pk=self.testcase_id) tr = Testruns.objects.get(pk=self.testrun_id) return f"{tc}(tr), Start: {self.teststart}, End: {self.testend}" Inside app admin.py I just register all those models. The select tag of the … -
Display SVG for New Content in Django
I want to display an SVG for any new content created in the past 2 days. I'm just wondering how I'd do this. views.py: def short_story_list(request): shorts = models.Short.objects.filter(is_live=True).order_by('-created_at') return render(request, 'stories/short_story_list.html', {'shorts': shorts}) short_story_list.html: {% for short in shorts %} <div class="block"> <h3><a href="{% url 'short-detail' short.slug %}">{{ short.title }}</a></h3> {% if short.created_at %} <img src="{% static 'svg/outline-fiber_new-24px.svg' %}"> {% endif %} <br> </div> {% endfor %} How do I make sure that only the SVG is displayed? -
Django Viewflow: From where to send email to user on task assignment?
I need to email owner when task is assigned to them. I tried following ways: Assign accepts a callable function which should return task owner. We can send email in this callable function. But if you read source code, you will find that this callable method is called multiple times, by calc_owner function. Hence if we email user here, multiple emails will be send Create a new Node method like EmailUser and call it after Assign and before Next. But the issue is, it should also be thorough some callable like Assign for it to be called for each Process. But where to call this callable function This seems like very general use-case, with a very difficult solution. Or am I missing something? -
how can i get in my template a queryset which show me relationated object from database
Well this is my views.py def movieO(request, id): moviee = Movies.objects.get(id=id) moviee = { 'moviee':moviee, } return render(request, 'moviesingle.html', contexto) and my urls: re_path(r'^movies/(?P<id>\d+)/$', movieO, name='moviesweb') I want to show in this view all the objects in my database that are similar to the object sent or presented on the page through the id, for example, someone is in the view of the movie skyfall, I would like to show all the movies related to skyfall according to some keywords that will be added in my field tags. this is my models.py class Movies(models.Model): titulo = models.CharField(max_length=50) Cover = models.ImageField(upload_to='static', height_field=None, width_field=None, max_length=100) fecha_de_lanzamiento = models.DateField() director = models.CharField(max_length=30) reparto = models.CharField(max_length=200) genero = models.CharField(max_length=20) pais = models.CharField(max_length=20) sinopsis = models.CharField(max_length=400) puntuacion = models.DecimalField(max_digits=5, decimal_places=1, blank=True, null=True) links = models.TextField(blank=True, null=True) ACCION = 'ACC' DRAMA = 'DRA' CIENCIA_FICCION = 'SC' SUSPENSO = 'SUS' TERROR = 'TER' CRIMEN = 'CRI' TAGS_CHOICES = ( (ACCION, 'Acción'), (DRAMA, 'Drama'), (CIENCIA_FICCION, 'Ciencia Ficción'), (TERROR, 'Terror'), (SUSPENSO, 'Suspenso'), (CRIMEN, 'Crimen'), ) tags = MultiSelectField(choices=TAGS_CHOICES, blank=True) class Meta: verbose_name_plural = "Películas" def __str__(self): return self.titulo and tags is the field that i wanna use to relate the different movies -
How to calll a django consumer from a django view in django channels?
So basically I've got a middleware server and it uses rest to send a post request to a data cluster. If the data cluster is on and the record was done successfully it returns OK. But in that case I would like to send this piece of data to the client through WebSocket. Thus I have to set some sort of communication between my django view and the django consumer. How do I do that? I'm not sure I'm doing it the right way though.... -
Django - how to test sending JSONs by POST?
Here's my view: @login_required @csrf_exempt def view(request): import json json_data = json.loads(request.body.decode(encoding='UTF-8')) var1 = json_data['var1'] var2 = json_data['var2'] #... And here's how I tried to test it #... self.client.login(username=u, password=p) dict = {"var1": variable1, "var2": variable2} response = self.client.post(url, WHAT_SHOULD_I_ADD_HERE, content_type="application/json", charset="UTF-8") #... With WHAT_SHOULD_I_ADD_HERE being: dict: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) json.dumps(dict): In order to allow non-dict objects to be serialized set the safe parameter to False. JsonResponse(dict, safe=False): Expecting value: line 1 column 1 (char 0) -
Speed up Djano query
I am working with Django to create a dashboard which present many kind of data. My problem is that the page loading slowly despite I hit the database (PostgreSql) always once. These tables are loading with data in every 10th minute, so currently consist of millions of record. My problem is that when I make a query with Django ORM, I get the data slowly (according to the Django toolbar it is 1,4 second). I know that this not too much b is the half of the total loading time (3,1), so If I could decrease the time of the query the page loading could decrease to there for the user experience could be better. When the query run I fetch ~ 2800 rows. Is there any way to speed up this query? I do not know that I do something wrong or this time is normal with this amount of data. I attach my query and model. Thank you in advance for your help. My query (Here I fetch 6 hours time intervall.): my_query=MyTable.filter(time_stamp__range=(before_now, now)).values('time_stamp', 'value1', 'value2') Here I tried to use .iterator() but the query wasn't faster. My model: class MyTable(models.Model): time_stamp = models.DateTimeField() value1 = models.FloatField(blank=True, null=True) … -
How to send jquery ajax with django form
I would like to send jquery ajax with my UpdateForm and get it in my view, to do my updateform I'm using Generic UpdateView but when I try to send my $('#form').on('submit') does not happen nothing, even the django form does not update. My question is How can I send both django form and jquery ajax together and get both in my view? Thanks in advance class ResearcherInfoUpdateView(LoginRequiredMixin, UpdateView): model = Researcher form_class = ResearcherInfoForm success_url = reverse_lazy('accounts:dashboard') def form_valid(self, form): """If the form is valid, save the associated model.""" researcher = Researcher.objects.get(email=form.cleaned_data['email']) items = [] if researcher.experience.all().count() >= 1: for new_item in form.cleaned_data['knowledge_areas']: area = CNPQ.objects.get(id=new_item.id) items.append(area.id) if not researcher.experience.filter(predominant_area_id=area.id): experience = ExperienceTime.objects.create(predominant_area=area) researcher.experience.add(experience) for item in researcher.experience.all(): if item.predominant_area_id not in items: researcher.experience.filter( predominant_area_id=item.predominant_area_id).delete() else: for new_item in form.cleaned_data['knowledge_areas']: area = CNPQ.objects.get(id=new_item.id) experience = ExperienceTime.objects.create(predominant_area=area) researcher.experience.add(experience) self.object = form.save() return super(ResearcherInfoUpdateView, self).form_valid(form) def get_context_data(self, **kwargs): if 'form' not in kwargs: lista = [] researcher = Researcher.objects.get(user_id=self.request.user.id) for a in researcher.application_area.all(): lista.append(a.id) kwargs['application_area'] = lista kwargs['form'] = self.get_form() return super().get_context_data(**kwargs) my form <form id="form" method="POST" enctype="multipart/form-data" novalidate> {% csrf_token %} {{form|crispy}} <div class="container"> <div class="row text-center"> <div class="col-sm-5 col-xs-5 " style="margin-left:5px; padding:0"> <a class="btn btn-sm btn-default pull-right" data-toggle="modal" data-target="#myModal">Área … -
AttributeError: 'tuple' object has no attribute 'get' [on hold]
In the process of correcting my codes,i debugged a lot in this current project, but I am not able to debug this "AttributeError". Where is this "AttributeError 'tuple' object has no attribute 'get" error coming from ? Please be helping! Thanks in advance forms.py from django import forms from django.contrib.auth import get_user_model User = get_user_model() class LoginForm(forms.Form): username = forms.CharField(max_length=200) password = forms.CharField(max_length=200,widget=forms.PasswordInput) class RegisterForm(forms.Form): username = forms.CharField(max_length=200) email = forms.EmailField() password = forms.CharField(max_length=200,widget=forms.PasswordInput) password2 = forms.CharField(max_length=200,label='Confirm Password',widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'] qs = User.objects.filter(username=username) if qs.exists: raise forms.ValidationError('Username is Taken') else: return qs def clean_email(self): email = self.cleaned_data['email'] qs = User.objects.filter(email= email) if qs.exists: raise forms.ValidationError('This Email is already registered') else: return qs def clean(self): data = self.cleaned_data password = self.cleaned_data['password'] password2 = self.cleaned_data['password2'] if password2 != password: raise forms.ValidationError('password must match') return data urls.py from . import views from django.contrib import admin from django.urls import path urlpatterns = [ path('account/login',views.LoginView, name = 'login_url'), path('account/home',views.acount_home_view, name = 'account_home_url'), path('account/register',views.RegisterView, name = 'ragister_url') ] views.py from django.shortcuts import render from .forms import LoginForm,RegisterForm from django.contrib.auth import authenticate,login from django.shortcuts import redirect from django.contrib.auth import get_user_model # Create your views here. def LoginView(request): if request.method == 'POST': form = LoginForm(request.POST … -
Why I am getting this type of error?
C:\Users\*****\projects\djangoproject>pip install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command "c:\program files\python37\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\Sachin\\AppData\\Local\\Temp\\pip-install-ypmx3pe6\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Sachin\AppData\Local\Temp\pip-record-pyc1o_o8\install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build\lib.win-amd64-3.7 copying _mysql_exceptions.py -> build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb creating build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.7\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- Command ""c:\program files\python37\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\*****\\AppData\\Local\\Temp\\pip-install-ypmx3pe6\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Sachin\AppData\Local\Temp\pip-record-pyc1o_o8\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Sachin\AppData\Local\Temp\pip-install-ypmx3pe6\mysqlclient\ -
Correctly accessing django static files from external javascript
I've got a django application using AngularJS with a bunch of JavaScript and template files. In my django template I can use the {% static %} tag to properly reference those files like so: <script src="{% static "angular/myapp.app.js" %}"></script> However, the external files themselves obviously do not get resolved through django's templating framework and so that's not an option. So what people most often do is just hard code the static path there: $routeProvider.when('/', { // this works but is not ideal templateUrl: '/static/pages/some-angular-template.html', }) I have seen recommendations of loading STATIC_URL into javascript somewhere and using that to construct references. Something like this: Django template: var STATIC_URL = {{ STATIC_URL }}; function getStaticUrl(templatePath) { return STATIC_URL + templatePath; } External JS: $routeProvider.when('/', { templateUrl: getStaticUrl('/pages/some-angular-template.html'), }) This is a bit better, but still not perfect because it only handles the base path. If you want to use something like ManifestStaticFilesStorage (which I do) then you still don't get the proper resolution of the file. Is there any good solution to this problem? Options I am considering: Bootstrapping all necessary URLs into JS variables inside the django template Storing the urls in some hidden HTML markup using data tags (again … -
Django 1.11- Admin custom add in the search_form two dates fields
I begin with Django and i take me ages to add extra fields to my search form. I need advice. What I made: In admin.py I define my ModelAdmin I use all the default configuration usefull, it means: search_fields : here linked to an attribute charfield of my model list_filter : here linked to an attribute datetimefiled of my model The behaviour of the filter is not enough for me, it means ( any date / today / past 7 days, this month,...) Simple I thought just add in the search_form.html two dates fields in GET parameter __gte / __lt I redefine the method def changelist_view , by adding the extra_context Problem it's only works when I do a search with the 3 fields or only the two based on the dates but with the field defined in search_fields the url is : /e=1 ........why -
How to render HTML page using an Ajax call in Django
I am in the scenario where I need to make an Ajax call and render an HTML page as normally done using this command @csrf_exempt def show(request): if request.method == 'POST': # Do Something return render(request, "index.html") Ajax @csrf_exempt def show(request): if request.method == 'POST' and request.is_ajax(): # Do Something return HttpResponse() I am a bit confused can anybody point me in the right direction, Thank You -
Django: Get value of foreign key field without additional SQL to DB
Model class Photo(models.Model): doc_pic = models.ImageField(upload_to='specialist/', default='', null=True, blank=True, max_length=250) doctor = models.ForeignKey(Doctor, blank=True, null=True, on_delete=models.SET_NULL, related_name='photos') I query the photos temp = Photo.objects.all() Now I want the ID of doctor that is saved in doctor field (for first element) print(temp[0].doctor) and I receive the Doctor object. But I want the numeric ID. How can I get that? I am aware that I can get it with temp[0].doctor.id but this will submit another query to the DB that I want to avoid. -
How to make form in _base.html
I need to make form in header section of site. This form will be available for all pages in my site. For example, i have in my app "accounts": forms.py class SignupForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ('phone',) views.py def signup(request): form = SignupForm(request.POST or None) # CODE # ctx = { 'form': form, } return render(request, 'accounts/signup.html', ctx) urls.py from django.urls import path from . import views app_name = 'accounts' urlpatterns = [ path('signup/', views.signup, name='signup'), ] accounts/signup.html {% block signup %} {{ form }} {% endblock %} If i making include {% include 'accounts/signup.html' %} in my _base.html, i dont, get form - {{ form }} but all other content will be included. And can you tell me how exactly get form for all pages in site? This is right opinion? -
filter statement based on calculations django orm
how can I translate query like this in django orm? select id, year, month where (year*100 + month) between 201703 and 201801 Thanks in advance for any help -
Django - string is adding paranthesis and comma to string... IDK why
I have a django project. I have an existing string in a database in the Activity table I created. I am creating a new string that that will replace and update the existing string. When I update the existing spring, I notices that it keeps adding ('...new string...',) and then saving it. I am not sure why it is adding the new marks to the string... here is the code that creates a new sting. grabs the existing string and then updates it before saving the string. description_updated = 'you and ' + friend.user + ' are now friends' activity = UserActivity.objects.filter(reference = ref_code).first() if activity: update_activity = activity update_activity.description = description_updated, update_activity.request = 1 update_activity.save() return redirect('user_home') Here is what is being displayed when I print the activity: assad --- rana -- ('you and rana are now friends',)