Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parse html to text and text to html in DRF
I need to parse the html code to markdown and again i need to parse the markdown text to html for rendering, for this thing i need to use two different package. Currently i'm going to use html-to-text - Html to Markdown text and mistune - Markdown text to Html. The thing is that everything i need to do in the API part. So no connection with front-end. I need a better solution to do this. -
Load different HTML page based on URL in Django class based view
Currently my urls.py has this code login_view = LoginView.as_view() url(r'^login$', login_view, name='login'), I have written a corresponding LoginView in my views.py class LoginView(FormView): template_name = 'auth/login.html' form_class = forms.LoginForm Now my requirement is I want to create a login page for different set of users who would come from a different url. For ex myproject.com/customers. I can do it with a new View class. But I want to make it generic and want to handle it in the same LoginView() class. Is it possible to catch the url parameter and check that inside LoginView and load a different login.html page for them. Or is there any other way using which we can handle this situation -
How to handle API Framework casing that is different than Javascript Casing?
I use django rest framework that uses snake_case for attributes which send data to Angular client which should work on camleCase since they are javascript properties. What is the cleaner way to handle this incoherence ? -
username field in django sign up form
I use from django.contrib.auth.forms import UserCreationForm in forms.py for creating sign up form. first I register with a username, for example ali and again when I try to register with Ali it allows me to create user. how can I prevent registering with two same username like Ali and ali ? -
My product index is not updating as i am using haystack solr django oscar
As I am using Django oscar haystack and solr setup it is working fine, but when I do any change in product data it is not updating the index, when I do sorting and anything it is working like previous index result. I added in settings HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' but it is not working, as I used the default app that is provided by Django oscar. so what tweaks needed to resolve this problem . -
To add GET parameters in Swagger
Use django rest framework and django-rest-swagger in documentation of the methods it is not showing available GET parameters and the question is how can I set? ru version. -
Django add form on every page
In my application i need to add a form in base.html, which I've done. For this i used context_processors, now my problem is everytime i'm trying to post, i'm getting a blank page and this error: Method Not Allowed (POST) In this form i want just to add a button where it will mark all current users notifications as read. I know that you can use context_processors like this: def my_context(request): data = dict() if request.user.is_authenticated: data['notifications'] = Notification.objects.filter(user=request.user, read=False) data['form'] = NotificationForm() return data But instead of adding the form i need these lines: def my_context(request): data = dict() if request.user.is_authenticated: data['notifications'] = Notification.objects.filter(user=request.user, read=False) if request.method == 'POST': if 'read-notifications' in request.POST: for notification in data['notifications']: notification.read = True notification.save() next = request.POST.get('next', '/') return redirect(next) return data The form in base.html: <form action="" method="POST">{% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> <button type="submit" class="btn m-btn--square btn-primary" name="read-notifications">Mark as read</button> </form> urls.py url(r'^orders/create/$', views.admin_order_document, name='create_order'), url(r'^orders/waiting/$', views.OrdersWaitingListView.as_view(), name='order_waiting_list'), url(r'^orders/unallocated/$', views.OrdersUnallocatedListView.as_view(), name='order_unallocated_list'), url(r'^orders/working/$', views.OrdersWorkingListView.as_view(), name='order_working_list'), How can i show this form on every page without getting the above error? -
Django full text search: TrigramDistance not working
I am using Django 2.0 and postgresql 9.6. I have installed pg_trgm extension in the postgresql I am trying to understand how triagram works: I am trying the following. I want words nearer to "sridam" to be matched using triagram from django.contrib.postgres.search import TrigramDistance from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector vector = SearchVector('title',config='english_unaccent', weight='A') + SearchVector('description',config='english_unaccent', weight='B') query = SearchQuery('sridam',config='english_unaccent') Article.objects.annotate(distance=TrigramDistance(vector, query)).filter(distance__lte=0.7).order_by('distance') ProgrammingError: operator does not exist: tsvector <-> tsquery LINE 1: ...SCE("articles_article"."description", '')), 'B')) <-> plaint... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. -
Make one select field depend to another in Django admin
I have Django model as follows: class UserBusinessUnit(models.Model): company = models.ForeignKey(to=Company, limit_choices_to={'is_dealership': True}) user = models.ForeignKey(to=User) brands = models.ManyToManyField(to=Brand) business_unit = models.ForeignKey(to=BusinessUnit) active = models.BooleanField(default=True) class Meta: ordering = ('user__username',) def __unicode__(self): return self.user.email + ' - ' + self.business_unit.name In Django admin panel it look like this: I want to be able to populate User and Business unit field depending in Company field. Thus if I change company field I want that the User and Business field are instantly populated. Any idea how to do that? -
How to run a Django management command as a cron in a Docker container?
I just wanted to run a Django management command as a cron inside a Docker container. Dockerfile: FROM python:3 MAINTAINER DAWN ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install -y vim RUN apt-get install -y nginx RUN apt-get install -y gdal-bin RUN apt-get -y install cron RUN mkdir /code WORKDIR /code RUN mkdir /code/logs ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD ./my_project /code COPY ./docker-entrypoint.sh /code/my_project/ COPY ./django_nginx.conf /etc/nginx/sites-available/ RUN rm -f /etc/nginx/sites-available/default RUN ln -s /etc/nginx/sites-available/django_nginx.conf /etc/nginx/sites-enabled RUN echo "daemon off;" >> /etc/nginx/nginx.conf ADD crontab /etc/cron.d/my_cron RUN chmod 0644 /etc/cron.d/my_cron RUN touch /var/log/cron.log ENTRYPOINT ["/code/my_project/docker-entrypoint.sh"] RUN /usr/bin/crontab /etc/cron.d/my_cron crontab: 1 * * * * root python /code/manage.py my_management_command >> /var/log/cron.log 2>&1 This cron is not getting executed even though I can see it in the crontab inside the container by connecting to the container using docker exec -it my_container /bin/bash crontab -l Where am I going wrong? -
Django ORM filter nested
how do I make a django nested query, for instance to filter all products that has an attribute with (length > weight / 4000) ? Here's roughly the 3 models I'm working on Product(models.Model): name = models.CharField('name') # code for example: 'length', 'weight' Attribute(models.Model): code = models.CharField('code') AttributeValues(models.Model): product = models.ForeignKey( 'Product', related_name='attribute_values', verbose_name=_("Product") ) attribute = models.ForeignKey( 'Attribute', verbose_name=_("Attribute") ) value = models.FloatField() I hope that my model is enough to explain what I'm asking. Thanks in advance -
Django: Accessing model fields from form widget in template
I have a ModelForm which uses a CheckboxSelectMultiple widget to represent data from a ManyToManyField. By default this will render a list of checkboxes with the label being set to the return value of the __str__ method of the related model. However, I wish to display data from other fields in the related model in addition to the choice_label provided by the widget. For example consider the implementation below: models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.name class Order(models.Model): items = models.ManyToManyField('Item') forms.py from django import forms from .models import Order class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['items'] widgets = {'items': forms.widgets.CheckboxSelectMultiple} template.html {% for item in form.items %} <tr> <td>{{ item.tag }}</td> <td>{{ item.choice_label }}</td> <td>{{ item.category }}</td> </tr> {% endfor %} The problem here is the {{ item.category } part of the template.html, is there a way to access this information from the template? -
Django rest-framework getting number of registered users in a given date range
I am learning Django, I wanted to get the number of registered users in a given date range grouped by the registration date here is my code profiles = Profile.objects.filter(date_joined__gte=datetime.date(2011, 1, 1), date_joined__lte=datetime.date(2018, 2, 28)).annotate(count=Count('id')).order_by('date_joined') I want it to return as a JSON in the form { 'date': '2018-01-01', 'user_count': 14264 }, I have created a Profile Serializer but I do not think the two are compatible, the fields in Profile are not the ones I want to return Person model class Profile(User): department = models.CharField(max_length=100) def __str__(self): return self.username + " (" + self.department + " )" Person Serializer class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' -
How do I stop Django development server from restarting?
I want Django development server to exit when an error happens. But whenever the server exits, it restarts. I tried to kill the process using os.kill(os.getpid, 9) which does not work. I tried sys.exit, os._exit, and raised errors and none of them works. Notes: Since the program doesn't only run on Linux, so ideally I wish not to use anything like bash. Also I don't want to disrupt other processes. -
Django clean_email function returning "enter a valid email"
I made a clean_email function in my forms.py to check if the email the person is signing up with is part of a registered school. This is the form: class StudentRegister(UserCreationForm): email = forms.EmailField(required = True) def __init__(self, *args, **kwargs): super(StudentRegister, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['placeholder'] = 'example@example.com' self.fields['first_name'].widget.attrs['placeholder'] = 'First Name' self.fields['last_name'].widget.attrs['placeholder'] = 'Last Name' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password2'].widget.attrs['placeholder'] = 'Password' class Meta: model = get_user_model() fields = ( 'email', 'first_name', 'last_name', 'password1', 'password2' ) def clean_email(self): email = self.cleaned_data.get('email') email = email.split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: raise forms.ValidationError('School not found, check your email') return email def save(self): user = super(StudentRegister, self).save() student = Student(user = user) student.save() return user, student This is the view for the student registration: def student_registration(request): #Student Registration if request.method == 'POST': form = StudentRegister(request.POST) #Gets school object from email domain. email = form['email'].value().split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: pass if form.is_valid() and school: user, Student = form.save() Student.school = school Student.save() user.groups.add(Group.objects.get(name='Student')) #user.is_active to stop users logging in without confirming their emails user.is_active = False user.save() #Sends confirmation link. send_confirmation_email(request, user) args = {'email': user.email, 'link': user.Student.school.email_website,} return render(request, 'email/token_sent.html', args) else: args = {'form': form,} return render(request, … -
Django restframework import data from another table?
I'm using Django rest framework with MySQL. Let me explain my two tables. [article] - articleNo(Primary key) - content [comment] - articleNo(FK to article) - userkey - comment I want to import comment data to artice table. class articleDetailSerializer(serializers.ModelSerializer): userkey = userSerializer(read_only=True) likeCount = serializers.IntegerField(source='like_set.count', read_only=True) commentCount = serializers.IntegerField(source='comment_set.count', read_only=True) comment = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = article fields = ('articleNo', 'userkey', 'content', 'likeCount', 'commentCount', 'comment') class commentSerializer(serializers.ModelSerializer): class Meta: model = comment fields = ('articleNo', 'content', 'userkey') When I visit /article, Current output is: { "articleNo": 26, "userkey": { "userkey": "121212", "username": "Da" }, "content": "test", "likeCount": 3, "comment": [ 1, 2, 3 ] }, What I would like instead as output is something like: { "articleNo": 26, "userkey": { "userkey": "121212", "username": "Da" }, "content": "test", "likeCount": 3, "comment": [ { articleNo: 26, userkey: "12345", content: "first comment" }, { articleNo: 26, userkey: "23456", content: "second comment" }, { articleNo: 26, userkey: "33333", content: "third comment" }, ] }, Can it be implemented with Rest framework? Thanks. -
Django URL dispatcher - it calls the same view to the different URL(regular expression)
Hello thank you very much for reading my question post. I have different url path patterns in urlpatterns, but Django URL dispatcher(re-path) calls the same view( views.selected_verb) for the different URL expressed by Regular expression. These urls call the same view(views.selected_verb) http://127.0.0.1:8000/arabic/verbs/%D9%83%D8%A7%D9%86/ http://127.0.0.1:8000/arabic/verbs/%D9%83%D8%A7%D9%86/quiz/ Would love to know how to fix it(calls different views) here is urlpatterns urlpatterns = [ path('', views.index, name='index'), path('verbs', views.verbs, name='verbs'), re_path(r'^verbs/(?P<verb>.+)/$', views.selected_verb, name='selected_verb'), re_path(r'^verbs/(?P<verb>.+)/quiz/$', views.quiz, name='quiz'), ] Thank you very much again! -
How to see Nginx log?
When I want to see the Gunicorn log to see if I have any errors, I do gunicorn --log-file=- <my_app>.wsgi:application - what command do I use to see the Nginx log? -
Django app not being served with Python3.5 and httpd
I have a Django app hosted on: Server version: Apache/2.4.6 (CentOS) Server built: Oct 19 2017 20:39:16 here's my django.conf file: Alias /static /home/faizan/myproject/static <Directory /home/faizan/myproject/static> Require all granted </Directory> <Directory /home/faizan/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python3.5/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py My application was working when I had python 2.7 installed in my virtual environment and had django.conf like this: Alias /static /home/faizan/myproject/static <Directory /home/faizan/myproject/static> Require all granted </Directory> <Directory /home/faizan/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py -
Invalid syntax error while running unit test in django
my sample django project works fine and i get result but the problem is that whenever i run unit test on my project i get syntax error as follows in test.py. i have tried using .format() still it shows up error .why cant i use f'this is my text' to format my string ? error log ERROR: blog.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: blog.tests Traceback (most recent call last): File "/usr/lib/python3.5/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/home/blog/tests.py", line 28 self.assertEqual(f'{self.post.title}', 'Content') ^ SyntaxError: invalid syntax -
Why does Jenkins starting my django server give me 404, but manually running the same script work properly?
This is my fabric script that runs on the jenkins server. sudo('/home/myjenkins/killit.sh',pty=False) sudo('/home/myjenkins/makedir.sh',pty=False) sudo('/home/myjenkins/runit.sh',pty=False) This kills the old server, creates a virtualenv, installs the requirements and restarts the server. The problem is the with the script that starts the server - runit.sh :- nohup /home/myjenkins/devserver/dev/bin/python /home/myjenkins/devserver /workspace/manage.py runserver --noreload 0:80 >> jenkins.out & When the jenkins server that starts the server and I navigate to the homepage, it gives me a 404 Page Not Found. It says /static/index.html not found. But the file exists. When I run 'sudo bash runit.sh' and I access the homepage, It works fine. Please ask me for more details if you need it. -
Python - Django -Tastypie - How to run code after reutrningt
For the below code the return statement seems to execute only after the function has completed def runJob(objects,bgJob): """DO SOME DJANGO STUFF" try: return prepareResponce(status=202) finally: runJob(objects, bgJob) Basically I need to execute runJob after the return statement -
500 error when uploading files with Filer to S3 using boto3 and django-storages on Elastic Beanstalk
I receive the following 500 http error when attempting to upload a file via the django-cms Filer admin in my app deployed to Elastic Beanstalk: In browser console, coming from fileuploader.min.js:26: POST http://app-staging.us-east-1.elasticbeanstalk.com/admin/filer/clipboard/operations/upload/1/?qqfile=example.jpg 500 (Internal Server Error) I am using django-cms (and therefore easy-thumbnails), django-storages and boto3. When deploying, the collectstatic command in my .ebextensions config file works great, and the files are all nicely stored in the S3 bucket in /staging/static/. Removing the DEFAULT_FILE_STORAGE assignment works fine, but is obviously untenable as each eb deploy of any changes to beanstalk results in a new instance and erases previous file uploads. Stack trace: Internal Server Error: /admin/filer/clipboard/operations/upload/1/ Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/admin/clipboardadmin.py", line 114, in ajax_upload file_obj.save() File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/imagemodels.py", line 53, in save super(Image, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/abstract.py", line 74, in save super(BaseImage, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/filemodels.py", line 194, in save super(File, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/polymorphic/models.py", line 74, in save … -
Getting an error while following django tutorial
I am completely new to both django and python and currently I am following https://docs.djangoproject.com/en/2.0/intro/tutorial01/ tutorial. Getting the following error while running the command python manage.py runserver. Can anyone please help? Performing system checks... Unhandled exception in thread started by <function wrapper at 0x102cf8140> Traceback (most recent call last): File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/poojadeole/Desktop/projectdjango/mysite/mysite/urls.py", line 16, in <module> from django.urls import include, path ImportError: cannot import name include -
Django model.py models.ForeignKey()
I am a newbie on Django framework and a bit confused on the models. When a "class" in the model.py, can I just understand it as "table" in database? For example, in the code below, "Test", "Contact", and "Tag" are all tables in the database used by Django? from django.db import models class Test(models.Model): name = models.CharField(max_length=20) class Contact(models.Model): name = models.CharField(max_length=200) age = models.IntegerField(default=0) email = models.EmailField() def __unicode__(self): return self.name class Tag(models.Model): contact = models.ForeignKey(Contact) name = models.CharField(max_length=50) def __unicode__(self): return self.name In the class Tag, it is using models.ForeignKey(Contact), based on my understanding, the foreignkey should be established on one specific column of a table, but why the ForeignKey is establish on a table directly, i.e. Table Contact? Any guidance is highly appreciated.