Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store javascript code snippet or iframe code snippet in Django
I'm implementing a series of banners on my website which are provided by third-party websites. Some of them are iframe code, some of them are javascript code (and I can't exclude other types as well). Since I will have to use this pieces of code a few times throughout the website, I am thinking about how I should store them in my Django website (postgresql). Can I just store the code as text and then output it in the template using the |safe filter? Or do we have a better approach recommended? Thanks, Vittorio -
Django-debug-toolbar does not appear
I'm using Django 2.0.1 and no matter what I do I can't get the toolbar to appear. I've looked all over and nothing seems to work. DEBUG=true in my settings django.contrib.staticfiles and debug_toolbar are in INSTALLED_APPS 'debug_toolbar.middleware.DebugToolbarMiddleware' is high up in MIDDLEWARE_CLASSES (tried moving it around) I have INTERNAL_IPS = ('127.0.0.1',) in my settings I tried adding print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR']) in a view, and it printed IP Address for debug-toolbar: 127.0.0.1 I have a closing in my template I have run pip install django-debug-toolbar and have run the python manage.py collectstatic (and there is a debug_toolbar dir) I added the below to the urls.py (no spaces between underscores) if settings.DEBUG: import debug_toolbar urlpatterns = [ path('_ _debug_ _/', include(debug_toolbar.urls)), ] + urlpatterns I tried adding def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK" : show_toolbar, } But it still didn't do anything. I can't seem to figure it out -
Python( Django ) pip install psycopg2 error in MacOS
I set the virtualenv for my project and when I want to run pip install psycopg2 I get an error below ERROR: Complete output from command python setup.py egg_info: ERROR: running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from the source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/r5/mt37g42j2h3b676lpx3qlznm0000gn/T/pip-install-yijundiy/psycopg2/ What should I do!? -
fetch 3 first objects with the same fk, django
pk name foreign-key 1--- a ---100 2--- b--- 200 3--- c ---100 4 ---d ---100 5--- e--- 100 6--- f ---200 7--- g ---100 8--- h ---200 9--- k ---200 10--- l ---100 I need to construct query-set that would fetch all objects with certain (cpecified in the list or in generator) foreign keys but only first 3 object with the same foreign-key. No ordering, ie random is possible in this example case it would be (1,3,4) for foreign key 100 and (2,6,8)for foreign key 200 Lets say model-name is Model. Thank you! -
Django only one user/one date in same model
I have a table that several users will add dates to. Each user can add a date. But you can only add that date once. How can I prevent a user from adding the same date more than once? Thanks in advance! models.py class MarcacaoRefeicoes(models.Model): class Meta: ordering = ['-data'] verbose_name = 'Marcação de Refeição' verbose_name_plural = 'Marcação de Refeições' user = models.ForeignKey(User, related_name='marcacao_refeicoes', on_delete=models.CASCADE) data = models.DateField(null=True, verbose_name='Data') def __str__(self): return '{}'.format(self.data) views.py def marcacao_refeicoes_adicionar(request, pk=None): user = get_object_or_404(User, id=pk) form = MarcacaoRefeicoesForm(request.POST or None, request.FILES or None, initial={'user': pk}) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, 'Marcação adicionada com sucesso!') return HttpResponseRedirect(reverse("marcacao_refeicoes", kwargs={'pk': pk})) context = { "user": user, "form": form, } return render(request, 'gestao/area_individual/marcacao_refeicoes/adicionar.html', context) -
How to add tooltip in django matplotlib scatterplot using mplcursors
I am trying to add tool-tip in scatter plot using mplcursor..its working fine..but when i integrated it with django its not working import matplotlib.pyplot as plt import numpy as np import mplcursors np.random.seed(42) fig, ax = plt.subplots() ax.scatter(*np.random.random((2, 26))) ax.set_title("Mouse over a point") mplcursors.cursor(hover=True) plt.show() -
Django - how form initialization works?
Looking at the view code, to me it looks like the form class should be initialized everytime a GET is performed. #views.py if request.method == 'GET': form = PrenotaForm() return render(request, "prenota.html", {'form': form, 'posti_liberi': posti_disponibili, 'giovani_iscritti': giovani_iscritti}) else: # it's a POST The thing I would figure out is why my code into the form class does not look to be executed at every refresh: # forms.py class PrenotaForm(forms.ModelForm): size_gruppi = 30 print("gruppi size is : " + str(size_gruppi)) In my console I see that the code is executed everytime i modify and save the forms.py file, or whenever I start the server with python manage.py runserver: Performing system checks... gruppi size is : 30 But simple refreshes of the interested page does not execute the code as shown in console: Django version 2.1, using settings 'test_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [24/May/2019 15:35:38] "GET /it/iscrizione/prenota/ HTTP/1.1" 200 11898 [24/May/2019 15:35:38] "GET /static/images/favicon.ico HTTP/1.1" 200 549 [24/May/2019 15:35:39] "GET /it/iscrizione/prenota/ HTTP/1.1" 200 11898 [24/May/2019 15:35:39] "GET /static/images/favicon.ico HTTP/1.1" 200 549 [24/May/2019 15:35:39] "GET /it/iscrizione/prenota/ HTTP/1.1" 200 11898 [24/May/2019 15:35:39] "GET /static/images/favicon.ico HTTP/1.1" 200 549 It is causing me problems because the form is not … -
Keep a django app user logged in with safari "add to home screen"
I have added my django app to my iphone home screen with the safari bookmark. As it has been described here, when the app is opened trough this bookmark, the user is every time logged out. I wonder how can I keep my user logged in to my django app. Is there a way to manage this with Django? -
got an unexpected keyword argument in django
I am work with a recommend function which generate post queryset by same tag in this post. it work pretty much like this: when a post page is opend PostDetailView will pass parameter post_pk to Sidebar.get_recommend then way to Post.recommend_posts then i received this error TypeError: recommend_posts() got an unexpected keyword argument 'post_pk' class Post(models.Model): ... @classmethod def recommend_posts(cls, post_pk=None): post = cls.queryset.get(pk=post_pk) post_tags = [tag for tag in post.tag.all()] recommend_list = Post.objects.none() for tag in post_tags: recommend_list = recommend_list | tag.post_set.all() recommend_list = recommend_list.distinct().exclude(pk=post_pk) return recommend_list class PostDetailView(CommonViewMixin, DetailView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post_pk = self.kwargs.get(self.pk_url_kwarg) context.update({'sidebars':Sidebar.get_recommend(post_pk=post_pk),}) return context class Sidebar(models.Model): ... @property def content_html(self): result = '' ... ... elif self.display_type == self.DISPLAY_COMMENT: context = { 'comments':Comment.objects.filter(status=Comment.STATUS_NORMAL)[:5] } result = render_to_string('config/blocks/sidebar_comments.html', context) return result @classmethod def get_recommend(cls, post_pk=None): cls.post_pk = post_pk return cls.objects.filter(status=cls.STATUS_SHOW).filter(display_type=cls.DISPLAY_RECOMMEND) -
Get values from a specific user - queryset in Django
I stuck with this queryset, no idea how to write it properly. So I'd like to see all related users to this specific user, in other words I have a friend list. models.py class Friend(models.Model): user = models.ForeignKey(User, related_name="friendship_creator_set", on_delete=models.CASCADE) friend = models.ForeignKey(User, related_name="friend_set", on_delete=models.CASCADE) views.py def profile(request): friends = Friend... context = { 'friends': friends, } return render(request, ..., context) How to write queryset to get list of usernames who are firends to specific user? -
How to process data after a request
I have a form where you can input some data, but i want to return the view with a suc6 message and process that data and finally add it to the database. I have everything working but if I process the data it doesn't return the view right away and I don't know if its good practice to use a Thread instead of Processing the data in the view.py -
How to list files contained in MEDIA_ROOT from within a view?
I am trying to print MEDIA_ROOT folder contents from within a view. settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') The directories are like below: >>> from django.conf import settings >>> settings.BASE_DIR 'M:\\django\\newenv\\django_projects\\mediaproject' >>> settings.MEDIA_ROOT 'M:\\django\\newenv\\django_projects\\mediaproject\\media' views.py: from django.conf import settings from django.http import HttpResponse import os def list_media(request): print(os.listdir(settings.MEDIA_ROOT)) return HttpResponse('OK') Why do I get the following error when list_media view is called?: Traceback (most recent call last): File "M:\django\newenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "M:\django\newenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "M:\django\newenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "M:\django\newenv\django_projects\mediaproject\mediapp\views.py", line 14, in list_media print(os.listdir(settings.MEDIA_ROOT)) FileNotFoundError: [WinError 3] The system cannot find the path specified: 'M:\\django\\newenv\\django_projects\\mediaproject\\media' Is only possible through MEDIA_URL as in this answer? -
How to deal with a `relation "cms_disclaimerpanel" already exists` and ProgrammingError: column "http_request_lang" of relation "xyz" does not exist
I have a rather annoying issue when trying to send my merge to my automated tests on circle CI. Just for the context, I've inherited a project where the authors are no longer working at my current work. I'm working on django and I've done a merge, from my local dev branch to my local master branch. The merge went well. However, when starting the django server through a manage.py runserver, it gives me the warning that I will need to migrate my apps as some of them are not up to date. When doing the manage.py migrate, I'm running into the first issue: 1- django.db.utils.ProgrammingError: relation "cms_disclaimerpanel" already exists I fix the issue by manually editing the migration file, commenting the following lines # migrations.CreateModel( # name='DisclaimerPanel', # fields=[ # ('abstractpanel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='cms.AbstractPanel')), # ('title', models.CharField(blank=True, max_length=1024, verbose_name='title')), # ('show_title', models.BooleanField(default=True, verbose_name='show title')), # ('subtitle', models.TextField(blank=True, verbose_name='content')), # ('show_subtitle', models.BooleanField(default=True, verbose_name='show subtitle')), # ('alignment', models.CharField(choices=[('left', 'left'), ('center', 'center')], default='center', max_length=10, verbose_name='text alignment')), # ('button', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='cms.Link')), # ], # options={ # 'verbose_name': 'Disclaimer Panel', # }, # bases=('cms.abstractpanel',), # ) Then the second issue happened, while carrying my manage.py migrate 2 - ProgrammingError: … -
How to record current user when a new data saved in Django?
I'm trying to save current user when a new record saved in Django. I tried some code but it seems I am missing somethings. In my modes I've created a ForeignKey for User table and I'm using generic class based views. Tried to save current user with a save_model function but couldn't do it right. Here my codes: My models.py: from django.utils import timezone from django.conf import settings class Backlinks(models.Model): link = models.URLField(max_length=100,verbose_name="Link") keyword = models.CharField(max_length=100,verbose_name="Anahtar Kelime") created_date = models.DateTimeField(default=timezone.now,verbose_name="Eklenme Tarihi") end_date = models.DateTimeField(default=timezone.now,verbose_name="Bitiş Tarihi") description = models.TextField(null=True,blank=True,verbose_name="Ek Bilgi") source = models.URLField(max_length=100,verbose_name="Kaynak") author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,verbose_name="Kullanıcı",null=True,blank=True) def __str__(self): return self.link class Meta: verbose_name = 'Backlink' verbose_name_plural = 'Backlinkler' Here my views.py: class LinkCreate(LoginRequiredMixin,CreateView): model = Backlinks form_class = YeniForm success_url = "/" login_url = "/hesap/login/" def save_model(self, request, obj, form, change): if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() When I've trying to save the form I'm getting this error: IntegrityError at /ekle/ NOT NULL constraint failed: backlinks_backlinks.author_id Thanks in advance. -
How to iterate over my postlist to display tags from taggit?
I want to iterate over my postlist, to show on click all the posts with the same tag. I want them to display at the index.html . I understand the function, but i don´t know how to implement it into my template. My views.py from django.views import generic from .models import Post from django.shortcuts import render class PostList(generic.ListView): model = Post template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def tag(request, slug): posts = Post.objects.filter(tags__slug=tag) return render(request, 'index.html', {"posts": posts, "tag": tag}) def about(request): return render(request, 'about.html', {}) My template <header class="masthead" > <div class="overlay"></div> <div class="container"> <div class="row"> <div class="site-heading"> <h5 class=" site-heading mt-3"> Erfolgreiche Problemlösungen in der Programmierung, Linux und Windows</h5> <p class="texthead"> </p> </div> </div> </div> </div> </div> </header> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in post_list %} <div class="card mb-4" > <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on | date:"d M Y"}} | Tag: {% for tag in post.tags.all %} <a class="mycardtext" href="{% url 'tag' tag.slug %}">{{ tag.name }}</a> {% empty %} None {% endfor %} </p> <p class="card-text">{{post.content|truncatewords:25|safe}}</p> <div><a href="{% url 'post_detail' post.slug %}" … -
"which web framework to learn for running python scripts in background"
Which framework should i learn for making small web apps(Like a java applet). That can run python scripts in background (Like a small ML model) Eg- A rent predictor that takes values of features from the user. And that can access files on the system of the user from the browser(I already know python). -
Django channels how to check if a group exists in channel layer?
I have a piece of code (django channel consumer) which creates an individual group for each user connected. like this @login_required_connection async def connect(self): await self.channel_layer.group_add( self.user.id, self.channel_name ) await self.accept() Everything meant for that user is pushed to his group from django side, and consumer forwards it to him. The problem is that if connection breaks for a minute and then reconnects, user does not receive anything pushed within that duration. What I want to do (please suggest a better approach if there is one) is save data for user in redis and push all data when he reconnects. My question is, how can I check if a group for user exists or not? so that I can save data to cache if does not exist. NOTE Currently I am maintaining online / offline status in redis. (When user connects place a key for him and remove on disconnect). But I just want to check if channel exists or not. -
login_exempt_urls not working in my custom middleware
I am trying to create a custom middleware so when the user is not logged in they can still register to the site. However with this code 'register' redirects me to accounts/login. If you could help. Custom_middleware.py: from django.conf import settings from django.shortcuts import redirect EXEMPT_URLS = [settings.LOGIN_URL.lstrip('/')] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [url for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') print(path) if not request.user.is_authenticated: if path not in EXEMPT_URLS: return redirect(settings.LOGIN_URL) settings.py LOGIN_REDIRECT_URL = '/accounts/' LOGIN_URL = '/accounts/login/' LOGIN_EXEMPT_URLS = ( r'^register/$', ) Thanks -
How to run a Validation Error in clean funtion using django query?
This is my model: class Stockdata(models.Model): company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True,related_name='Company_stock') quantity = models.PositiveIntegerField(null=True,blank=True,default=0) rate = models.DecimalField(max_digits=10,decimal_places=2,default=0.00) opening = models.DecimalField(max_digits=10,decimal_places=2,default=0.00) stock_name = models.CharField(max_length=32) I want to make the stock_name unique for every company. So, I have done the following: def clean(self): if Stockdata.objects.filter(company=self.company,stock_name__iexact=self.stock_name).exists(): raise ValidationError({'stock_name':["This stock name already exists"]}) But when I try to save() or submit the form it creates a duplicate value(i.e. it creates a value which already exists). Any idea how to perform this? Thank you -
cant access to django post request key
I write a Django web application and this project have one function that gives request from client, this request has one key this key is "tokene' when I send this request with Postman, my function cant find 'tokene' key so I write a small python code to send Request and this code is work! why? # its my python code import requests r = requests.post('http://localhost:8000/submit/expensequery/', data={'tokene':'123456789'}) print (r.url) # its my webapplications function def query_expenses(request): if (request.POST.has_key('tokene')): this_token = request.POST['tokene'] num = request.POST.get('num', 10) this_user = get_object_or_404(User, token__token=this_token) expenses = expense.objects.filter(user_name=this_user).order_by('-date') [:num] expenses_serialized = serializers.serialize("json", expenses) return JsonResponse(expenses_serialized, encoder=JSONEncoder, safe=False) else: return HttpResponse('please send token !') -
Queryset for models FK relations in django
These are my models and fields: Models.py Course: title slug CoursePrerequisite this_course = ForeignKey(Course) prerequisite_of_course = ForeignKey(Course) Curriculum: course = ForeignKey(Course,) title slug Enrollment: student = ForeignKey(User) curriculum =ForeignKey(Curriculum) date Brif of my system: As seen from my model file, in this system, the courses have a pre-requisite state.Untile preson can't pass pre-requisite of course, can't take the course. Each course is presented for enrollment in model named: 'Curriculum'. And finally my problem is: In fact, I know that I must first check student enrollment and find the 'Curriculum' that he have,and by this, find all course of student. Then,among the course I will find the course that have prerequisite_of_course and finally check for student for each of this prerequisite course check that student enroll in course curriculum! It's very hard for me to write this query? Can you help me? -
How can we include the invoice system in django
I'm developing an invoice system for the sales and i need to design invoice for the sales .there was some package django-invoicing but there is no proper description for that. can anyone say about it or how to do it -
how to validate django custom database fields?
I'm reading the django documentation on how to create custom database fields. However, there is no mention of how fields are validated. I looked into the source code of existing fields, but I can't find validation logic there either. How do django fields handle validation? Or they don't do it at all, and let the database exceptions propagate up the stack trace? -
Django/vanilla javascript ajax posts successfully but the page still reloads
Ajax submitting a form works, but I'm unable to stop the page reload. I've tried several variations of event listening by id. On the form, the button, tried using inline onclick, onsubmit, tried putting the button outside of the form. <form method="post" id="form1"> {% csrf_token %} {{ form|crispy }} <button type="submit">Click</button> </form> function parse_cookies() { var cookies = {}; if (document.cookie && document.cookie !== '') { document.cookie.split(';').forEach(function (c) { var m = c.trim().match(/(\w+)=(.*)/); if(m !== undefined) { cookies[m[1]] = decodeURIComponent(m[2]); } }); } return cookies; } var cookies = parse_cookies(); var title = document.getElementById('title_identifier'); function ajax_function() { var request = new XMLHttpRequest(); request.open("POST", `/ajax_post_function/${title.textContent}/`, true); request.setRequestHeader('X-CSRFToken', cookies['csrftoken']); var formElement = document.querySelector("#id_comment"); request.send(new FormData(formElement)); } form = document.getElementById('form1') form.addEventListener('submit', ajax_function) If I change the event handler from the form to the button or vice versa, it posts successfully with the message shown in chrome dev tools being: (1) VM667 ajax_post_function.js:22 XHR finished loading: POST "http://localhost:8000/ajax_post_function/WhateverTitle/". Navigated to http://localhost:8000/ajax_post_function/WhateverTitle/ But it just goes back to the top of the page again. However, If I use this ajax function, then the comment is not submitted, and the response from the chrome dev tools is: function ajax_function(e) { var request = new XMLHttpRequest(); request.open("POST", … -
How to load dash-plotly graphs in django template using ajax call?
I'm using google maps on google maps I have put some markers where I have placed the air quality monitoring sensors. Now what I want is when I click on the marker it shows me the data of the sensors in graphs to do this I'm using Dash Plotly to draw graphs. And to show the graphs on click I send a ajax request to the django views.py where dash_view() function return the html fil=(chart.html) using jquery function I put the code of chart.html in div id=#chart_div which is in index.html. Now the problem is when I first click on the marker it only shows that graphs are loading with this (Uncaught ReferenceError: DashRenderer is not defined) error in the console when I click on the marker multiple times only then graphs are displayed and after double or triple clicks the single click also starts working. And when I Use {% plotly_direct name="AQI" %} to render the graph in template it takes multiple clicks to show graphs and when I use {% plotly_app name="AQI" %} it works on one click but the styling of the whole graph is removed. #############views.py############# @csrf_exempt def dash_view(request): return render (request,'map/chart.html') #############ajax_call on click marker############## …