Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
(1048, "Column 'user_id' cannot be null") when submitting form - Django
When I try and upload an image, I am getting an error (1048, "Column 'user_id' cannot be null") however, there is no user_id column. I tried setting user = models.OneToOneField(null=False), but it did not work. models.py class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=140, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') image = models.ImageField(upload_to='profile_image', default='profile_image/Default.jpg') def __str__(self): return self.user.username forms.py class UpdateBioForm(forms.ModelForm): image = forms.ImageField() class Meta: model = UserProfile fields = ( 'image', 'city', 'website', 'description', ) widgets = { 'description': forms.Textarea(attrs={'rows': 4, 'cols': 15}), } def save(self, commit=True): savedBio = super(UpdateBioForm, self).save(commit=False) savedBio.image = self.cleaned_data['image'] savedBio.city = self.cleaned_data['city'] savedBio.website = self.cleaned_data['website'] savedBio.description = self.cleaned_data['description'] if commit: savedBio.save() return savedBio views.py def update_bio(request): if request.method == 'POST': form = UpdateBioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') else: form = UpdateBioForm(instance=request.user) args = {'form': form} return render(request, 'accounts/update_bio.html', context=args) -
Is it possible to isolate side effects in a python web framework (django, pyramid, flask) view? If so, how?
I usually try to keep all my business logic outside of the view and let the view only deal with view specific things. However, this still doesn't help in isolating side effects. For example, if I set up a view that accepts a POST request to create an item, I usually do a few things Validate incoming request data Transform any arguments if necessary Create the item and save it to the db I have seen the effect library but I don't love the syntax and it hasn't been updated in 3 years. On the front end, Redux does a pretty good job at isolating side effects with middleware. -
Virtualenv have multiple possible locations
A colleague of mine implement a shell script with the following line output="$(venv/bin/python manage.py has_missing_migrations --quiet --settings=project.tests_settings 2>&1)" Here is the full code : # Check missing migrations output="$(venv/bin/python manage.py has_missing_migrations --quiet --settings=project.tests_settings 2>&1)" [ $? -ne 0 ] \ && ipoopoomypants "Migrations" "$output" \ || irock "Migrations" If I run the script, I obtain Running pre-commit checks: [OK] anonymize_db ORM queries [OK] Forbidden Python keywords [OK] Forbidden JavaScript keywords [OK] Forbidden HTML keywords [FAIL] Migrations COMMIT REJECTED: .git/hooks/pre-commit: line 88: venv/bin/python: No such file or directory The problem with the above line is it takes into account that the virtual environment has been created inside the project itself. However, it is not always the case. From what I am concerned, I work with virtualenvwrapper. Hence, my virtualenv is not ./venv, but well in ~/.virtualenvs/venv. Question : How could I modify the above line in such a way it will consider both path ./venv and ~/.virtualenvs/venv? -
DRF login generate token and session at the same time
My site uses Django Rest Framework with an angular frontend and knox tokens for login. I want to add django-wiki to my site and right now it works, except users that login to my site who want to visit the wiki have to login again because django-wiki uses session authentication and my site uses tokens. Is there a way for a DRF login action to return both a token and a session?