Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i link multiple orders to as single customer django
I have 2 models, Customer and Order, Order is linked to Customer via the foreignkey, my problem comes from relating a customer with multiple orders, in my customer_list.html i did this linking a name to a pk: {% for customer in customer_list %} ....href="{%url 'order_app:order_detail' pk=customer.pk %}"> Customer Name.. {% endfor %} And i want to display all the orders of that particular customer in order_detail.html for e.g: {% for order in customer.orders.all %} <tr> <td>{{order.pk}}</td> <td>{{order.project_title}}</td> <td>{{order.order_date}}</td> <td>{{order.order_status}}</td> <td>{{order.amount}}</td> </tr> {% endfor %} This method doesnt work, and i cant seem to figure out how to fix this Thank you for your help -
Change django-messages-to-bootstrap-notify settings
I'm using django-messages-to-bootstrap-notify to show notification on my django project. How can I change it's default settings to show my customized notifications? -
Django: relate userprofile to app models
myimages app: models.py: class Image(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) title = models.CharField(max_length=100) photo = models.FileField() urls.py: url(r'image/add/$', views.ImageCreate.as_view(), name='image-add'), views.py: class ImageCreate (CreateView): model = Image fields = ['title', 'photo'] I am creating a website for people to upload images in Django what should be added to the codes so that when a user of the page upload an image using the following generic view function, the database can save the owner and relate the user as the owner to the image models here: models.ForeignKey(UserProfile, on_delete=models.CASCADE) -
Syntax Error:Invalid syntax when installing django in cent os 6.9
I am getting the following error when executing this command "sudo pip install django" Traceback (most recent call last): File "/usr/bin/pip", line 7, in <module> from pip._internal import main File "/usr/lib/python2.6/site-packages/pip/_internal/__init__.py", line 42, in <module> from pip._internal import cmdoptions File "/usr/lib/python2.6/site-packages/pip/_internal/cmdoptions.py", line 16, in <module> from pip._internal.index import ( File "/usr/lib/python2.6/site-packages/pip/_internal/index.py", line 526 {str(c.version) for c in all_candidates}, ^ SyntaxError: invalid syntax And python installed version is Python 2.7.11 using this command python -V -
django 2 custom jwt_get_username_from_payload_handler
To validate the jwt token of auth0 in django, I use the following code in settings.py def jwt_get_username_from_payload_handler(payload): return 'authuser' JWT_AUTH = { 'JWT_PAYLOAD_GET_USERNAME_HANDLER': jwt_get_username_from_payload_handler, 'JWT_PUBLIC_KEY': PUBLIC_KEY, 'JWT_ALGORITHM': 'RS256', 'JWT_AUDIENCE': API_IDENTIFIER, 'JWT_ISSUER': JWT_ISSUER, 'JWT_AUTH_HEADER_PREFIX': 'Bearer', } where authuser is the username. So Instead of writing it directly I want to receive it in request header and pass it. Please help me in customising this function - jwt_get_username_from_payload_handler in such a way. TIA -
Implement plotly dashboard in django
How to implement a plotly dashboards containing graphs with filters in django?please explain with an example? -
Python Sqlalchemy filter by date range
I have two date picker fields that i want the users to select from date to end date. and i want to display data between the two dates that was selected. From example form date: 2/14/2018 to date:3/15/2018. when the function is called i want to extract and display data between this two dates. i just need some help with the query to accomplish that. I am using sqlalchemy to pull data from an mssql db -
Django Request Session on anonymous users
I have the following problem: I'm using the Django Rest framework with anonymous users (i don't have users in my application) and in my views file when i try to modify the request.session variable, the value is not persistent in all views. I have two different class based views: def post(self, request): ... request.session["instances"] = serializer.data request.session.modified = True ... return Response(data, status=status.HTTP_200_OK) def get(self, request, page): ... print request.session["instances"] ... return Response(data, status=status.HTTP_200_OK) On the second view i get a key error, basically the key "instances" doesn't exist. This is my settings file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] SESSION_SAVE_EVERY_REQUEST = True I haven't been able to store data on request.session successfully, i tried checking if the session has a session_key but it prints None, so i created a session on the first view with session_id = request.session._get_or_create_session_key() but still on the second view it doesn't exist anymore (session_key is None). Anybody here had this problem before? -
Use @staticmethod in Django Rest Framework endpoint method?
Should I be defining post, get, etc methods of a Django Rest Framework APIView as static? class HomeView(APIView): def get(request): etc... or class HomeView(APIView): @staticmethod def get(request): etc... What are the pros/cons of each way? Thank you -
Django:Html templates
I written a base html for another html base.html {% for foo in subjectType %} <li class="nav-item"> <a class="nav-link" href="{% url "type" foo.type_name %}">{{ foo.type_name }}</a> </li> {% endfor %} and my navbar extends from base.html,but other html extends base.html,Can't display correct navbar.because other cant get "subjectType" How can I code this? I use python3.6.5 and django2.0 -
Django-'str' object has no attribute 'get'
Class for creating object and using newly created object redirecting to the new page. Html page taking input for creation -
Pass date year month slug in html template ajax post request
I have a blogost, comment and like model. The like model has a genericforeignkey field so I can link likes to blogposts and comments. The view is working correctly however I am having trouble passing the parameters in the ajax request urls.py urlpatterns =[ url(r'^$',views.home, name = 'home'), url(r'^blog/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[-\w]+)/$', views.blog, name = 'view_blogpost_with_pk'), url(r'^blog/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[-\w]+)/ajax/like/$',VotesView.as_view(model=BlogPost, vote_type=Like.LIKE), name='blog_like'), url(r'^blog/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[-\w]+)/ajax/dislike/$', VotesView.as_view(model=BlogPost, vote_type=Like.DISLIKE), name='blog_dislike'), ] blog.html <ul> <li data-id="{{ like_obj.id }}" data-type="blog" data-action="like" title="Like"> <span class="glyphicon glyphicon-thumbs-up"></span> <span data-count="like">{{ like_obj.votes.likes.count }}</span> </li> <li data-id="{{ like_obj.id }}" data-type="blog" data-action="dislike" title="Dislike"> <span class="glyphicon glyphicon-thumbs-down"></span> <span data-count="dislike">{{ like_obj.votes.dislikes.count }}</span> </li> </ul> And the javascript. Just including dislike, like is very similar <script> function dislike() { var dislike = $(this); var type = dislike.data('type'); var pk = dislike.data('id'); var action = dislike.data('action'); var like = dislike.prev(); $.ajax({ url : '/home/blog/2017/10/1/git/ajax/dislike/', method : 'POST', data : { 'obj' : pk }, success : function (json) { dislike.find("[data-count='dislike']").text(json.dislike_count); like.find("[data-count='like']").text(json.like_count); } }); return false; } <script> $(function() { $('[data-action="like"]').click(like); $('[data-action="dislike"]').click(dislike); }); </script> So at the moment this working great except when i replace url with url: '{% url "home:blog_dislike" year=obj.year month=obj.month day=obj.date slug=obj.slug %}' I get django.urls.exceptions.NoReverseMatch: Reverse for 'blog_like' with keyword arguments '{'year': '', 'month': '', 'day': '', 'slug': ''}' … -
Django - Add a clustered index to a datetime field
Here is a model I have on Django: class Game(models.Model): datetime = models.DateTimeField(db_index=True, blank=False) .... I don't have a primary key on that class, so Django creates an artificial primary key 'id', why I am fine with. A Game will be accessed by comparing its datetime field with the current datetime (today's date), so my app will have a section for upcoming games and past games. Therefore, it is important I create an index on datetime because that's how I will access the games. From what I understand from databases (if anything I say here is wrong please let me know), an entity can only have 1 clustered index. The clustered index is always set on the primary key. The attribute 'db_index=True' on the DateTimeField creates an unclustered index on the datetime field. My goal is to create a clustered index on the datetime field in order to decreases the I/O cost when querying games. It makes sense to do that, right? Is it possible to do that while keeping id as the primary key? Should I make datetime the primary key? What would be the drawbacks to that? Also, I am using postgres as my database if that changes … -
Génération de pdf avec django et l'envoie de ce pdf en pièce jointe
Bonjour! Je suis en train de créer un site pour les inscriptions des élèves avec le framework django, je suis arrivé sur une partir où je doit afficher le formulaire à l'utilisateur et je reçois les informations saisies après traitement je dois envoyer un mail à l'utilisateur contenant les informations qu'il a saisie en les mettant dans un pdf dont je dois générer à partir d'un template contenant le dictionnaire de contexte. Pour le moment le pdf que je peu générer n'est possible qu'en l'envoyant au navigateur à travers la fonction HttpResponse mais le problème avec ça est que c'est l'utilisateur qui décide de le téléchager ou non et moi j'ai plus la posibilité de mettre main sur le pdf afin de l'envoyer en pièce jointe. J'ai pensé à ouvrir une base de données où il y aura un champ de type models.FileField, générer le pdf avec le dictionnaire de contexte à travers la librairie xhtml2pdf que je pourais enregistrer dans la base de données avec un signal envoyer le mail en prennant comme pièce jointe l'object file que j'aurai enregistrer dans la base de données. Sauf aucune des méthode n'aboutit pour le moment aidez moi à traverser cette partie. … -
django.contrib.auth extends User with Profil error "No column id"
I use django.contrib.auth and extend it with a OneToOne profil. A couple days ago all was working, but today I cant access profil from user.profil, and my model dont work, I keep getting error Django.db.utils.OperationalError: no such column users_profil.id Why? from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) postal_code = models.CharField(max_length=255) facebook_profil = models.URLField(max_length=255) make = models.CharField(max_length=255) model = models.CharField(max_length=255) year = models.CharField(max_length=255) photo = models.ImageField(upload_to="") And I cant access profil >> from django.contrib.auth.models import User >> from users.models import Profil >> user = User.objects.get(pk=1) >> user.pk 1 >> user.profil Django.db.utils.OperationalError: no such column users_profil.id -
How to configure django-tinymce for use in ModelForm?
I have followed the instructions here to install and configure django-tinymce in my django project, but i do not see the tinymce editor on my form. Namely, I installed into my virtual environment with pip, added tinymce to installed apps and included the tinymce urls in my urlconf. In urls.py, I have from django.conf.urls import url urlpatterns = [ ... url(r'^tinymce/', include('tinymce.urls')) ] In their documentation, they use the deprecated patterns function, so I use url instead. Then, in models.py I have the following field definition, from django.db import models class BusinessUser(user): ... company_description = models.TextField(help_text="Provide a description of your business for potential candidates.") I then set the widget for this field to be a tinymce field as per the usage instructions. from .models import * from django.contrib.auth.forms import UserCreationForm from tinymce.widgets import TinyMCE class BusinessRegistrationForm(UserCreationForm): class Meta: model = BusinessUser fields = ( ... 'company_description' ... ) widgets = { 'company_description': TinyMCE(attrs={'cols': 80, 'rows': 30}) } Lastly, I have added {{ form.media }} at the end of the head in my html template that uses the form (and my form is indeed passed to the template as the variable "form"). The html is updated with a class of tinymce … -
how to use FilterSet in django with date field
I have a dat_transacao field and i´d like to create a range with it, but it didn´t work. I created dat_inicial and dat_final in filters.py, but the screen didn´t filter the records by this fields. Something is wrong but i don´t know what is it. Anyone can help me please ? Thanks. models.py: class transacao(models.Model): dat_transacao = models.DateTimeField('Geração da Transação', auto_now=True) pessoa = models.ForeignKey(pessoa, default='', blank=True, null=True) # Chave estrangeira da Classe Pessoa tipotransacao = models.ForeignKey(tipotransacao, default='', blank=True, null=True) # Chave estrangeira da Classe Tipo de Transação servico = models.ForeignKey(servico, default='', blank=True, null=True) # Chave estrangeira da Classe Servico (que pode ser NULL) bloco = models.ForeignKey(bloco, default='', blank=True, null=True) # Chave estrangeira da Classe Bloco filters.py: from .models import * import django_filters #from django_filters import DateTimeFilter class livrorazaoFilter(django_filters.FilterSet): dat_inicial = django_filters.DateTimeFilter(name='dat_transacao',lookup_type=('gte')) dat_final = django_filters.DateTimeFilter(name='dat_transacao',lookup_type=('lte')) class Meta: model = transacao fields = ['dat_inicial', 'dat_final', 'tipotransacao', 'pessoa', 'bloco'] views.py def transacao_livrorazao(request, id=None): instancia_transacao = transacao.objects.all().order_by('-dat_transacao') instancia_transacaofilter = livrorazaoFilter(request.GET, queryset=instancia_transacao) context = { "queryset": instancia_transacao, "filter": instancia_transacaofilter, "instancia_transacao": instancia_transacao } return render(request, 'livrorazao/livrorazao.html', context) livrorazao.html: <!DOCTYPE html> <html dir="ltr"> <form class=" bd-form-2 " action="#" name="form-name" method="get"> {% csrf_token %} <p>Período</p> <p>De</p> <input type="date" name='filter.form.dat_inicial' id="dat_inicial" class="bd-form-input" > <p>até</p> <input type="date" name='filter.form.dat_final' id="dat_final" class="bd-form-input" … -
Making a database in SQLite and integrating it with Django
I'm new to working with Django and databases, and I'm trying to make a web app that helps users plan their schedule. Ideally I would have a database of existing courses that are offered (each has a course number and the semester - either fall or spring). Then, the user would input 1. their year of college (this helps determine how many semesters are left) and 2. which of the courses have been already taken (which helps determine how many are left). The output should be a sample schedule (with restrictions). My problem is that I'm not sure how to handle the output creation and the inherent restrictions. For instance, if the user took 201, then the only course that could be taken is 301 as opposed to 302 (even if both 301 and 302 are offered at the same time) because 201 is a prerequisite for ONLY 301 (while 302 has its own prerequisites). Also, 100 levels need to go before 200 levels and so forth. Not sure how to handle this best, especially in the case of the original database creation. I presume that the '100 then 200 level' problem would be solved in the code that determines … -
500 Server Error on Heroku After Changing Django Setting --Error Log No Info
So, I was attempting to add a few features to my Django settings following this article here: http://bookofstranger.com/django-compressor-with-s3-and-cloudfront/ I allready had my site successfully set up with AWS and Cloudfront serving the static and media files. I was just trying to add django-compressor to compress the files and speed up the site. I have NO idea what the issue is as I have looked at the heroku logs and all I can see is that there was a GET request with a 500 server error --nothing else. On my local server---the site loads ok after i ran collectstatic. there is an error i can see in the cmd line: Traceback (most recent call last): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 696, in __init__ self.handle() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 154, in handle handler.run(self.server.get_app()) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 144, in run self.close() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split' I posting my settings file below (at least the relevant parts that I added or changed): #This will make sure that the file URL does not have unnecessary parameters like your access … -
SIMPLE Django button to execute view function
After a few days of tutorials I am calling it quits, any help would be appreciated. Can't get this to work, I'm sure it's easy, but this stuff is extremely convoluted. Just trying to delete a session variable with a button. I tried Ajax examples as well. Please don't forward me to another post unless you are sure it will actually work, because many do not. URL: urls.py ... url(r'^$', clear_session, name='clear_session'), ... and View: views.py def clear_session(request): print('hello') if not request.POST: print('hello') del request.session['jobs_append'] print('session list', request.session['jobs_append']) and Template: index.html ... <input id="clear_sesh" name="update_log" type="button" value="Update Log"/> ... <script type="text/javascript"> $(function(){ $("#clear_sesh").click(function(){ $.post( url : "/clear_session/", dataType:"html", success: function(data, status, xhr){ //do something with your data } ); return false; }); }); </script> ... <!-- jQuery --> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="{% static 'vendor/bootstrap/js/bootstrap.min.js' %}"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="{% static 'vendor/scrollreveal/scrollreveal.min.js' %}"></script> <script src="{% static 'vendor/magnific-popup/jquery.magnific-popup.min.js' %}"></script> <!-- Theme JavaScript --> <script src="{% static 'js/creative.min.js' %}"></script> -
how to add user to group while creating users in django
im using django default signup template to create a user but i want to add him to a group which has some permissions. from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User,null = True,on_delete=models.CASCADE) #user.groups.add(name='CUSTOMER') # is_staff = models.BooleanField(default=True) def __str__(self): return "%s's profile" % self.user def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) -
Management of pdf with django through a template and sent as an attachment of an electronic mail
I am creating a site for student registrations with the django framework, I have arrived at a place where I have to display the form to the user and I receive the information entered after treatment I have to send an email to the user user containing the information he has entered by putting them in a pdf which I must generate from a template containing the context dictionary. For the moment the pdf that I can generate is possible only by sending it to the browser through the function HttpResponse but the problem with that is that it is the user who decides to download it or not and I I have more posibility to put the hand on the pdf to send it as an attachment. I thought to open a database where there will be a field of type models.FileField, generate the pdf with the context dictionary through the library xhtml2pdf that I could save in the database with a signal send the email by taking as attachment the object file that I will record in the database. Except none of the methods are successful for the moment help me to cross this part. Here are the … -
how to make it so user can post comment only after login in Django
I'm coding a news website,I want the user can submit the comment of the news only after they have logged in,if not,the website will return to login.html. Now I have made it that only the user who have logged in can submit a comment,the issue is once I log off and submit a comment the error says: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x10fed10b8>>": "NewsComments.user" must be a "UserProfile" instance. Note:I have rewrote the User models and rename it UserProfile .It works very well. Here is my news/views.py: def newsDetailView(request, news_pk): news = News.objects.get(id=news_pk) title = news.title author = news.author_name add_time = news.add_time content = news.content category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) comment_form = CommentForm(request.POST or None) if request.method == 'POST' and comment_form.is_valid(): comments = comment_form.cleaned_data.get("comment") comment = NewsComments(user=request.user, comments=comments, news=news) comment.save() return render(request, "news_detail.html", { 'title': title, 'author': author, 'add_time': add_time, 'content': content, 'tags': tags, 'category': category, 'all_comments': all_comments, 'comment_form': comment_form }) Here is my news.detail.html <form method="POST" action="">{% csrf_token %} <div class="form-group"> <label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5></label> <textarea id="js-pl-textarea" class="form-control" rows="4" placeholder="我就想说..." name="comment"></textarea> <div class="text-center mt-3"> <input type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button" value='Submit'> </input> </div> </div> </form> Here is my urls.py: path('-<int:news_pk>', newsDetailView, name="news_detail"), -
(Django) A request was passed with missing value for 'category' which the code could not process. I need to catch this exception and handle it
An AssertionError was raised where a negative value was passed in the api request: AssertionError: Negative indexing is not supported. File "django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "newrelic/hooks/framework_django.py", line 544, in wrapper return wrapped(*args, **kwargs) File "api/views.py", line 1811, in lots sale_id File "api/views.py", line 1684, in lots_v1 datetime_now File "api/views.py", line 1409, in get_lot_items lots = paginator.page(page) File "django/core/paginator.py", line 62, in page return self._get_page(self.object_list[bottom:top], number, self) File "django/db/models/query.py", line 269, in __getitem__ "Negative indexing is not supported." This most likely resulted in 'infinite spinning wheel' showing to the user as the request was never finished due to the backend error. I need to catch and handle these incorrect values for the parameters of the url. -
Run a function every N calls to an API in a distributed environment
I need to run a function send_user_survey to every 100 users who hit a certain endpoint. I can't simple increment a counter locally because I have multiple machines, so 50 hits on one machine and 50 on another should trigger one run of send_user_survey. I could store the count on the database but using a SQL database to lock and increment on every API call doesn't seem like the right solution, especially since this API gets hit pretty hard.