Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customizing django form based on currently logged in user
This is a part of my forms.py class SubjectForm(forms.ModelForm): title=forms.CharField(label='',widget=forms.TextInput(attrs={'maxlength':150, 'placeholder':'Write here. . .'})) body=forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder':'Extend here. . .'})) board=forms.ModelChoiceField(label='',queryset=Board.objects.all(), empty_label='Select Board') class Meta: model = Subject fields = ('title','body','board') Right now it's rendering all Board objects in board form field but I want to render only those boards in which the user has subscribed. How can I get user in form and manipulate it? -
Error while installing Django-channels
I'm also getting the same error while installing Twisted. Here's version info: Django : 1.9 Python : 3.5 Trying to install latest version of Django-channels Command used : pip install channels The error : running build_ext building 'twisted.test.raiser' extension error: [WinError 2] The system cannot find the file specified I don't know what i'm missing, could someone help me please, thanks. -
What the use of tables in app django-celery?
I want to use celery to make a spider get proxy data for Internet timing. Now, I get some settings ahout how to use django-celery in django.Although it makes me a long time. But, I also have a problem below: Five tables had been made when I did python manage.py migrate,I know the three head tables is about timing task with the setting CELERYBEAT_SCHEDULER='djcelery.schedulers.DatabaseScheduler' ,but what the use of the tables ,tasks and workers? I try to make different setting about BROKER_URLandCELERY_RESULT_BACKEND,such as redis://,django://,djcelery.backens.database:DatabaseBackend,but I found , the table,tasks, no data born all the time.and the table workers,too. Could somebody explain the table,tasks and workders's use and how can I use it with right settings? -
How to display different model instance names in different places in django admin
I want to display say "name1" as name inside model instance of model "A" detail page and say "name2" for model instance of same model "A" as name in other places (if it is foreign key in other model say "B")in django admin.I tried to make changes in __str__ method but it changes in all places. Is there any other way to do.Any suggestions? Thanks in advance. -
Error Message: "No module named 'django.core.urlresolvers".Even though I've replaced the module
I was trying to create tables in my database by executing the command on the django shell in the Windows CLI migrate.py syncdb It returned with the error message django.core.exceptions.ImproperlyConfigured: Error importing debug panel debug_toolbar.panels.request: "No module named 'django.core.urlresolvers'" After reading up to resolve my problem I discovered it is because the module django.core.urlresolvers is not available in versions of python higher than 1.9 and django.urls is the more suitable module. I replaced the former module in my code with the latter from django.urls import reverse and somehow still manage to get the same error. How do I resolve this? Thanks in advance. -
Distinct Users Filtering
I'm trying to create a messaging App in django but I couldn't re-order the Users properly Here's the Models, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Here's the View, def message(request): users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('sender__first_name', 'receiver__first_name', 'receiver__id', 'sender__id').annotate(Max('id')).order_by('-id__max') return render(request, 'chat/users.html', {'users': users}) Here's what I tried in Template, {% for user in users %} {% if user.sender__id != request.user.id %} {{ user.sender__first_name }} {% else %} {{ user.receiver__first_name }} {% endif %} {% endfor %} This code seems working fine but it's returning same user "Twice" as long as request.user send someone a message & that person replies back to it. How can I fix that? Thank You . . . -
Python3 + Django : How to use Jquery in render_to_string template?
My sauce is below. Elements in the template created using render_to_string are not Jquery controls. ▶ index.html {% extends 'common/base.html' %} {% block contents %} <section> <div class="main-goods-area"> <div class="container" id="prod_list"> </div> </div> </section> {% endblock %} {% block jquery %} <script src="{% static 'js/index.js' %}"></script> {% endblock %} ▶ index.js $(function() { show_inf_list('0','0','0','0','0'); function show_inf_list(section, selection, ordering, start, limit){ $.ajax({ url:'/campaign/list/', data:{ 'campaign_section': section, 'selection_type': selection, 'ordering_type': ordering, 'start': start, 'limit': limit }, dataType:'json', success: function (data) { $('#prod_list').html(data.campaign_list); } }); } $('a[name=btn_like]').on('click', function (e) { e.preventDefault() console.log('a'); return false; }); }); ▶ views.py def ... data['campaign_list'] = render_to_string( 'main/include/prod_list.html', context=context, request=request ) return JsonResponse(data) ▶ prod_list.html <div class="ic-area"> <ul> <li> <a href="" name="btn_like" data-id="{{ campaign.id }}"> {% if user.influencer in campaign.like_users.all %} <i class="ic_heart_small active"></i> {% else %} <i class="ic_heart_small"></i> {% endif %} </a> </li> </ul> </div> I want control 'btn_like' element But, I can't control the 'a[name=btn_like]' How to use Jquery Control in element of render_to_string template? -
Return String if object Existed Function in Django Rest Framework
I have a question about Function which Return String if object Existed in Django Rest Framework. I want to set condition: If FriendshipRequest model have from_user = request.user and to_user=self.user, this relationship_to_user fields will return: 'Existed', if not, print 'Not Existed' Serializers: class UserDetailSerializer(ModelSerializer): relationship_to_user = SerializerMethodField() class Meta: model = User fields = [ 'id', 'relationship_to_user', ] def get_relationship_to_user(self): friend_request_sent = FriendshipRequest.objects.filter(from_user=self.request.user, to_user=user) if friend_request_sent.exist(): return ('Existed') else: return ('Not Existed') -
How to save in database new order of nodes in tree with ajax | django?
I use django-mptt application in backend and jsTree plugin in frontend to create such tree as in the picture below in my Django project: jsTree plugin allows you to drag and drop nodes inside tree. django-mptt application by default in DB create fields like: tree_id, lft, rght and parent_id. tree_id field store information about order of nodes. parent_id field store information about ancestor. When user click the button after drag and drop nodes I want to save the new order of items and there new dependencies (parent_id field) in database. Сan someone say me how to make such thing? template: {% load mptt_tags %} <div id="documents"> <ul> {% recursetree documents %} <li data-id='{{ node.tree_id }}'> {{ node.title }} <ul class="children"> {{ children }} </ul> </li> {% endrecursetree %} </ul> </div> JS: $(function () { $('#documents').jstree({ 'plugins': ["wholerow", "dnd", "search"], 'core': { 'themes': { 'name': 'proton', 'responsive': true }, "check_callback" : true }, }); var to = false; $('#search-documents').keyup(function () { if(to) { clearTimeout(to); } to = setTimeout(function () { var v = $('#search-documents').val(); $('#documents').jstree(true).search(v); }, 250); }); }); -
Adding Reply Form to every Comment in django
I'm trying to build a website where people can comment on a thread and others can also make replies to these comments. I've already made a commenting system but don't know how to add reply form to every single comment so that they can make a reply to that specific comment. Need help and suggestions?? -
how to make objects iterable and count the length elments in objects
What i am try to do is filtering the model according to date . And iterating the those objects what i actually want do is taking the objects from Grade in particular date range and iterating each object then counting the len after that passing range printing the values rows = Grades.objects.filter(user_ql__created_at__range=(from_date, to_date)) for row in rows: row_num += 1 for col_num in range(len(row): ws.write(col_num+2, row_num, row[col_num], font_style) When i do this i got first object of type len() is not found and unable to iterate those row -
Create custom template tag
I have a model that has a method which needs a parameter (the request.user.some_field) to do the job. So, to send this request.user, I've created a template tag. extra_tag.py from django import template register = template.library() @register.simple_tag def precio(sub_medida, tipo_usuario): return sub_medida.precio_venta(tipo_usuario) and when i go to the template where is loaded, I get the following error: on template: 'module' object is not callable on console: "../../extra_tag.py", line 3, in register = template.library() I don't know if this helps, but i followed this documentation: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/ Thanks in advance.. -
Django - optional url parameter returns null
I'm using an optional url parameter using this solution: If the optional argument isn't set, I get "null" in the browser url after the template is rendered: http://localhost:8000/home/Guest/create/null urls.py path('home/<str:username>/create', views.CreateModel.as_view(), name='model_create'), path('home/<str:username>/create/<int:pk>', views.CreateModel.as_view(), name='model_create_id'), views.py class CreateModel(generic.FormView): template_name = 'pythonmodels/user_content/createModel.html' form_class = CreateModel There are a lot of posts on optional url arguments, but I'm lost on where to add a default value inside the class based view if the argument is empty, so it would look like: http://localhost:8000/home/Guest/create Thanks in advance. -
Django Rest and Axios
I am trying to post data using DRF and Axios. I have tried a couple different options so far with the same result, 403 (Forbidden). I am able to get data using axios.get but not able to post data. I am new to rest and using ajax so I apologize if it is something obvious. Axios call return axios({ method: 'post', url: "/schedules/", data: { "emp": this.emp.emp, 'start_time': this.startTime, "end_time": this.endTime, "date": this.today, "location": this.location }, xsrfHeaderName: "X-CSRFToken", responseType: 'json' }) Settings.py CSRF_COOKIE_NAME = "XSRF-TOKEN" Serializer class SchedSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ( 'location', 'emp', 'date', 'start_time', 'end_time' ) View class SchedViewSet(viewsets.ModelViewSet): queryset = Schedule.objects.all() serializer_class = serializers.SchedSerializer -
Using redirect url to clear GET paremeters with SessionWizard from django-formtools
I'm using a SessionWizard in my view and my use case is that want to create a link which bypasses step 1 of the wizard. This step represents simply selecting a plan. So, these links would have hrefs of say, url/?plan=0, url/?plan=1.... etcetera In the get view of the wizard I'm capturing whether there are parameters in request.GET and submitting the first step of the form by building the request.POST QueryDict and calling the wizard's post view to go to the next step. However, since it just calls self.render which returns a TemplateResponse the ?plan=* is left in the url. Is there a way to redirect to the next step so this parameter is removed? -
Django Rest Framework serializing nested data
I am trying to serialize data in this Serializer but I am always getting the output {} Here is my serializer: class RelationshipSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) related_user = UserSerializer(read_only=True) class Meta: model = models.Relationship fields = ( 'user', 'related_user', ) Here is my view: related_user_id = body["related_user"] related_user = models.User.objects.get(id=related_user_id) user = self.get_object() user_serializer = serializers.UserSerializer(user).data related_user_serializer = serializers.UserSerializer(related_user).data # user_serializer and related_user_serializer return valid data. data = {"user": user_serializer, "related_user": related_user_serializer} serializer = serializers.RelationshipSerializer(data=data) serializer.is_valid() # valid return Response(serializer.data) I am getting the id of related_user from post request then getting the queryset of the actual object, and user is the id passed in the url: user/{1}/. I then serialize each user and create a dictionary to pass to RelationshipSerializer. The serializer returns valid but the response is {}, what did I do wrong? -
Logging errors in DRF using Sentry
Am trying to get Django logging working with Django Rest Framework and Sentry. Using the LOGGING entry below, I am able to invoke a logging.error("some error") from my own defined modules running as Celery workers and I can see the error is being pushed to Sentry. Unfortunately, when I invoke the same in a Django Rest Framework Serializer.py or a View.py the errors are not being captured by Sentry. Is there a parameter am missing maybe in DRF or Django to allow them to send errors to Sentry? Below is a sample that is not getting logged. serializer.py import logging logger = logging.getLogger(__name__) class MySerializer(serializers.Serializer): def validate(self, data): logger.error("Log an error") The config below was auto generated using cookie cutter LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry', ], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console', ], 'propagate': False, }, 'raven': { 'level': 'DEBUG', 'handlers': ['console', ], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console', ], 'propagate': False, }, … -
Saving user modified data
I've done a lot of Googling and I can't figure out the best approach to this. I have a database that lists tasks required for users to complete a project. The user can modified material quantities associated with each task and the system will calculate the total cost. I'd like the user to be able to save their project and access it later. I obviously don't want the base task model to be modified. I know that I can create a clone of the task object and save it right back in the database so that it becomes another row in the table, but mixing user data with system data doesn't seem right. I also don't like the idea of repeating a lot of redundant data in the database. Is there a way to only save the quantities the user actually modified? Something similar to a through table in a many to many relationship? What is the best approach to saving user customized data? Thank You. -
Custom Django FormWizard Steps with Templates
This is my working FormWizard that I made by following this and this views.py from django.shortcuts import render from django.template import RequestContext from django.http import HttpResponseRedirect from formtools.wizard.views import SessionWizardView # Create your views here. def index(request): return render(request, 'wizardApp/index.html') class ContactWizard(SessionWizardView): template_name = "wizardApp/contact_form.html" def done(self, form_list, **kwargs): process_form_data(form_list) return HttpResponseRedirect('../home') def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] print(form_data[0]['subject']) print(form_data[0]['info1']) print(form_data[0]['info2']) print(form_data[1]['sender']) print(form_data[1]['info1']) print(form_data[1]['info2']) print(form_data[2]['message']) print(form_data[2]['info1']) print(form_data[2]['info2']) return form_data urls.py from django.conf.urls import url from wizardApp import views from wizardApp.forms import ContactForm1, ContactForm2, ContactForm3 from wizardApp.views import ContactWizard app_name = 'wizardApp' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^home/$', views.index, name='index'), url(r'^admin/', admin.site.urls), url(r'^contact/$', ContactWizard.as_view([ContactForm1, ContactForm2, ContactForm3])), ] forms.py from django import forms class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) info1 = forms.CharField(max_length=100) info2 = forms.CharField(max_length=100) class ContactForm2(forms.Form): sender = forms.EmailField() info1 = forms.CharField(max_length=100) info2 = forms.CharField(max_length=100) class ContactForm3(forms.Form): info1 = forms.CharField(max_length=100) info2 = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) contact_form.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> {{ wizard.form.media }} </head> <body> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="/contact/" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} … -
Passing post data from Nginx to Django method
I'm having a Django app running on Nginx and Gunicorn, Inside the app i have a clients.py file with a method that receives post data from external server and process them, the django url mapped to the method is url(r'^client/client_request/$', clients.externalclient) The external server won't post data unless it get 200 OK response from my server. I can log posted data in nginx log but can't catch them to my method in django app, here is my Nginx config server{ listen 80; server_name 00.00.000.000; error_log /var/log/nginx/error.log; large_client_header_buffers 4 16k; # Tell nginx to ignore favicon location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://127.0.0.1:8000/; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; } location /assets/ { autoindex on; alias /var/www/html/dev2_assets/; } location client/client_post/{ proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; keepalive_requests 10; keepalive_timeout 75s; proxy_redirect http://00.00.000.00/ /client/client_post; } } and here is the django method that receives post request from django.http import HttpResponse def externalclient(request): if request.method == 'POST': print "Request received" else: print "Method not allowed" Please any one who can see the mistake will be appreciated. Thank you. -
GoLang vs Python Django/Flask
I'm currently working on developing a front end for a monitoring system (sensu) and I'm a little torn. I definitely know python more extensively than go, but I really like go's concurrency a lot for something like this where I'm constantly querying an API for certain results and such. My question is: For those who have had experience with both, which one would you go with and why? -
Django/Python: Calling a model/class function with an argument from Template
In Django 2.0, I'm trying to call a method from a class, from a template. Call from template {% test.method(user) %} Method from class def method(self, user): return Test.objects.filter(test_id=self.id, user_id=user.id) I know this isn't possible, but what would be the best alternative? There's no way I can execute the query without passing user as an argument. Thanks! -
Django Project: namespace 'admin' isn't unique
on trying to run C:\Python34/python manage.py makemigrations, I get the following error: Error WARNINGS: ?: (urls.w005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLS in this namespace What precisely do I need to change and where do I need to look? teachers/url.py from django.contrib import admin from django.urls import path from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.teachers, name='teachers'), ] url.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('teachers/', include('teachers.urls')), ] main/url.py urlpatterns = [ path('admin/', admin.site.urls), path('header/', views.header, name='header'), path('', views.index, name='index'), ] I've pasted the various url.py files above and imagine it's a problem somewhere there. could anyone please point me in the right direction, with an explanation please? I've considered that I could/should remove path('admin/', admin.site.urls), from all but the urls.py file (root) .....when I do remove this, I don't get the same error, but I don't know if that will cause other problems and if this is the right thing to do? -
Django display a value from a dictionary within dictionary
I'm trying to display values from a dictionary within a dictionary in a template using django. I have a dictionary like this in my views: characters = { "char1": {'name': "David", 'stars': 4, 'series': "All star"}, "char2": {'name': "Patrick", 'stars': 3, 'series': "Demi god"} } I can display the whole dictionary on the page, however I want to display only the 'name' and 'David' key:value pairs. I wrote the following in the template: {% for char in characters %} {% for key, value in char %} {{ key }}: {{ value }} {% endfor %} {% endfor %} However this doesn't show me anything. What is wrong with this double loop? Thanks -
How to render Django flat pages as plain text with line breaks (no html tags allowed)
We have a continuing need to update an ads.txt file that lives at the root of a Django project. The current method to update this file is ftp it and a “service nginx restart” performed by a developer. We want to now do this with a flat page and template and simply have a “non-developer” cut and paste the contents of the ads.txt file into the Content: field via the Django administration app, save and all should be well. The issue is the line breaks do not render unless we add html tags. This causes the ads.txt file to not pass validation tests since no html is allowed, only plain text. How can we accomplish this? The template is simply {{ flatpage.content }} Trying {{ flatpage.content|linebreaks }} causes html tags to be inserted into the rendered page and fails the ads.txt test. We’ve tried various combinations such as (r'^ads_txt/$', 'media.views.custom_header') in urls.py and def custom_header(self): self.response.headers['Content-Type'] = 'text/plain' in views.py to no avail.