Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django/Python - Error: That port is already in use
I'm trying to host my Django website for the first time, but it appears that the port is already in use. I haven't hosted anything before and I get the following result with netstat -ntlp: I would like to keep the standard port if possible... does anyone know a solution? I'm not sudo user. -
Django not rendering anchor tags childs properly
I have this and Django is rendering this One anchor tag child was rendered outside its parent. I did the same with a div instead of anchor tag and it worked just fine. That code block was inside a {% for %}. removed the for and deleted every template tag. Django still doesn't render properly. -
django related field exists after delete
I've an Order model and others models which related with it. An user can delete any of this items and I must perform a check if the order is empty after deletion and set as active False in case true. Some basic code to ilustrate it class Order(models.Model): paid = models.BooleanField(default=False) active = models.BooleanField(default=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) def empty_order(): """ I must implement it """ class HomeOrder(models.Model): ... order = models.OneToOneField(Order, related_name='primary_home') class TourOrder(models.Model): ... order = models.ForeignKey(Order, related_name='tours') I have a post_delete signals that are connected with every of this Models related to Order: post_delete.connect(delete_order_if_empty, sender=HomeOrder) post_delete.connect(delete_order_if_empty, sender=TourOrder) def delete_order_if_empty(sender, instance, **kwargs): if instance.order.empty_order(): instance.order.active = False instance.order.save() An Order can have one Home, so if the Home exists I can do order.primary_home, if Home does not exist it will raise an AttributeError because it is an OneToOne relationship. An Order can have many Tours, so in the empty_order method I thought to do some checks as following. def empty_order(): home = hasattr(self, 'primary_home') # Avoid AttributeError exception tours = self.tours.exists() this_order_has_something = primary_home or tours return not this_order_has_something Now, when I delete an HomeOrder the signal is raised but the empty_method never realized that this HomeOrder does not … -
Distinct in Django model, not the view?
If I have a database table that has a list of ID's and a description I need without the additional attributes. How can I do a group by in my Django model to limit my data set to the first two columns below as shown in the results, similar to a group by in SQL? id name attribute 1 a a 1 a b 1 a c 1 a d 2 b a 2 b b 2 b c 3 c a 3 c b desired result: id name 1 a 2 b 3 c Again i'm looking to do this in my model and not the view using .distinct() and order by.. Here is my current model: class QVDSSSecurityDimension(models.Model): id = models.CharField(db_column='CM_Data_Restriction', serialize=False, max_length=10, primary_key = True) # Field name made lowercase. name = models.CharField(db_column='CM_Company_Name', max_length=50, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'QV_DSS_Security_Dimension' The reason i'd like to do it in my model is because I get the following error because there are 8 attributes associated with QVDSSSecurityDimension for most users id's and this relates to the User table as a foreignkey MultipleObjectsReturned at /account/profile/ get() returned more than one QVDSSSecurityDimension … -
Custom Workflow?
I need to implement a standard workflow with three linear steps to handle, i.e. Select Plan & Preference, Personal Information, and Review & Payment. I know three available workflows with python3 and Django, but I think it is overkill for what I am going to do. Select Plan & Preferences: A client may choose one plan as well as some craft products. Personal Information: A client will fill fields related to where he lives, phone number, first name, last name, email, ... Review & Payment : Create an account if necessary, Review his/her order and make the payment related to the current order. Availabe Workflow - With Python 3 Maybe the solution is to implement a custom workflow, but I am a bit confused how to do it. I need a user follows some views step by step. Could someone explain to me roughly how can I do it? P.S. I am working with Django 1.11 and python 3.4. -
Django ldap module error "AttributeError: module 'ldap' has no attribute 'OPT_X_TLS_REQUIRE_CERT'"
I try to start my Djngo project and I catch this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/erastov/PycharmProjects/auction/auction/backend/auction/settings/dev.py", line 1, in <module> from .base import * File "/home/erastov/PycharmProjects/auction/auction/backend/auction/settings/base.py", line 86, in <module> ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER AttributeError: module 'ldap' has no attribute 'OPT_X_TLS_REQUIRE_CERT' I use Python 3.5, Django 1.11.7, ldap 1.0.2 It's happend when I remove my local project and clone from github again. I installed all requirements as usual. -
Get queryset data of django by ajax
I am trying to sending a json response from django views. Using below code. msg_obj=Message.objects.all() msg_list=list(msg_obj.values()) print(msg_list) return JsonResponse(msg_list,safe=False) Then on success in ajax I am doing like this:- success: function (data) { alert(data['id']) $('#msg-list').append("<p> he" + data['id'] + "</p>"); } if I print msg_list in django it gives me result like this: [{'id': 1, 'username_id': 2, 'fusername_id': 3, 'text': 'hello friends'},{'id': 1, 'username_id': 2, 'fusername_id': 3, 'text': 'hello friends'}] I have tried many combinations but unable to get or print the data back at client side(ajax on success function). Thanks in advance for any help. -
Updating Python without sudo commands?
I'm currently on Python 2.7, I want to update to 3.6.3 and also install Django afterwards. However I'm not super user, so I can't use Sudo commands. -
Child model field values when Parent Class is deleted
I have a lot of models in my database that inherit from a BaseModel. The Base model only has a few fields on it though, for creation/expiration dates etc. If I deleted the parent class altogether, moved those inherited class fields to its child, and than remigrated the schema of my database, what will happen to those field values ? Will they stay there, or be deleted ? If I did delete the parent class, i'm sure order of operations would matter. Base class BaseModel(models.Model): class Meta: abstract = True created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) @classmethod def model_field_exists(cls, field): try: cls._meta.get_field(field) return True except models.FieldDoesNotExist: return False class ChildModel() name = models.Charfield(max_length=255) age = models.IntegerField(default=1) New ChildModel class after deleting BaseModel class ChildModel() name = models.Charfield(max_length=255) age = models.IntegerField(default=1) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) -
Can't use any sudo commands on linux?
I'm trying to update python and install django on my linux server, but I can't get sudo commands to work. Whenever I type a command with sudo, I get the following >>> $ sudo apt-get update File "<stdin>", line 1 $ sudo apt-get update ^ SyntaxError: invalid syntax Server info Python 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on linux2 I don't know what type of linux this is unfortunately. -
django-rest-auth: Reverse for 'account_reset_password_from_key' not found
I have been trying to setup password reset functionality in DRF using django-rest-auth. Earlier I was getting error TemplateDoesNotExist:registration/password_reset_email.html which I resolved by adding the following code code serializer.py - from rest_auth.serializers import PasswordResetSerializer from allauth.account.forms import ResetPasswordForm class PasswordSerializer(PasswordResetSerializer): password_reset_form_class = ResetPasswordForm settings.py - REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'api.serializers.PasswordSerializer', } However, Now I am getting into another issue - "NoReverseMatch: Reverse for 'account_reset_password_from_key' not found. 'account_reset_password_from_key' is not a valid view function or pattern name.". And haven't found any solution or workaround for this. Any help would be appreciated. -
"Your credentials aren't allowed" - Google+ API - Production
I recently implanted the connection with facebook and google on my local server, and everything worked. But, when I tried to do it in production, the connection with google returns: "Your credentials aren't allowed". (Facebook works) I don't know why, because i'm pretty sure that my application is confirmed by Google. Do you have some ideas ? Thanks in advance ! -
Group_by in Django Database | Most efficient query order
I'm working on an old django app which unfortunately has one giant table in the database, meaning conventionally our queries are very slow. We cannot migrate the DB nor re-factor it into multiple tables for reasons beyond my control. I would like to make sure that these queries are as efficient as possible because they are a bit more complex than the queries that are typically being done in this app. For the following questions consider the following table schema: Table Orders: name: string price: integer order_date: date Django version = 1.6.5 Question 1 I'm coming from Rails, in which I would typically use the groupdate gem to group output as such: >> Orders.group_by_day() >> >> { 2013-1-1: {<all orders taking place on Jan 1st, 2013>}, 2013-1-2: {<Jan 2nd 2013>}, ... } Is there something built into Django that does something similar efficiently? I found https://docs.djangoproject.com/en/2.0/topics/db/aggregation/ but it doesn't appear as though it outputs in a similar manner. Question 2 Does the order in which you stack queries affect the speed at which it is executed? For example given the same query written in 3 different ways: Orders.where(price > 5).group_by_day() Orders.group_by_day().where(price > 5) { partial_orders = Orders.where(price > 5) partial_orders …