Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting Django App to DRF App
I have a django app that is not live yet and I just got a request to use API and i ended up selecting DRF. But am really lost on some of its components. I was able to login, get token and pass the token to get something. It will use angular.as on front end now, which needs all to be JSON. While i will rewrite the views, i want to reuse as much as possible especially modules. E.g. I have a validation that validates registration of forms (it used from three different views because a member can be registered in three different ways with some conditions applied i.e. self-registration, company registration and company-agent registration). def validate_member(data,editing=False,directregistration=True): #data is passsed from forms.py. Return any error message and the cleaned data to the calling forms.py return [errmsg,data] forms.py clean method example: class NewMemberForm(forms.Form): firstName=forms.CharField(max_length=25,required=True,widget=forms.TextInput()) def clean(self): self.cleaned_data=super(NewMemberForm,self).clean() validate_member_form=validate_member(self.cleaned_data,directregistration=True) #do we have error messages now? if len(validate_member_form[0])>0: #yes we have error messages raise forms.ValidationError(_(validate_member_form[0]),code='invalid') return validate_member_form[1] and my views.py: if request.method=='POST': err_found=False go_id='' form=NewMemberForm(request.POST or None) if form.is_valid(): #create user pass I see forms.py is useless in DRF APIView (i failed to get an example at least). How do I convert such … -
Django: ForeignKey set to default null (author_id)=(0)
I am using Django 1.11.1 and python3. Can not set author field to default null. What can be wrong? author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+', null=True, blank=True, db_constraint=False) error: DETAIL: Key (author_id)=(0) is not present in table "auth_user" -
Why I don't see a list of my objects in Django Build-in API Documentation? [duplicate]
This question is an exact duplicate of: The built-in API Django documentation doesn't display anything I am trying to add documentation to my Django app. I did everything in accordance with official Django Built-in API documentation. I have coreapi, markdown and pygments in requirements.txt file. However when I open for instance localhost:8000/docs/ I don't a see list of my objects as at the top of this site (in this case snippets and users). My urls.py: from rest_framework.documentation import include_docs_urls API_TITLE = 'API title' API_DESCRIPTION = '...' urlpatterns = [ url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)) ] -
Django Multiple JQuery Use In templates
I want to write some JQuery code in multiple templates. However, I do not want to write this: <script src="{% static "js/vendor/jquery-1.11.2.min.js" %}"></script> in every single template. Currently I have all my JQuery files defined in base.html like so: {% block js %} <script src="{% static "js/vendor/jquery-1.11.2.min.js" %}"></script> <script>window.jQuery || document.write('<script src="{% static "js/vendor/jquery-1.11.2.min.js" %}"><\/script>')</script> <script src="{% static "js/vendor/bootstrap.min.js" %}"></script> <script src="{% static "js/plugins.js" %}"></script> <script src="{% static "js/main.js" %}"></script> {% endblock %} and then in my other templates I wish to call them like this: //Child.html {% block js %} {{ block.super }} <script> ...Some JQuery Code... </script> {% endblock %} But it is not working. Any ideas? -
How to represent join queries in Django?
How do we present sql query like this one in django? select * from question LEFT JOIN (select * from question_solved where username = 'ashu' ) AS result on question.q_id = result.q_id I tried to perform query separately, q = question_solved.objects.filter(username='ashu') y = Question.objects.filter(q__q_id = Question.q_id) But it is giving me error django.core.exceptions.FieldError: Cannot resolve keyword 'q' into field. Choices are: q_answer, q_content, q_id, q_submission, q_tags, q_title, q_type my model file from django.db import models # Create your models here. class Question(models.Model): q_id = models.CharField(primary_key=True, max_length=20) #q_difficulty = models.IntegerField() q_title = models.CharField(max_length = 200) q_content = models.CharField(max_length = 1000) q_type = models.IntegerField() q_answer = models.FloatField() q_submission = models.IntegerField() q_tags = models.CharField(max_length=10) class Student(models.Model): username = models.CharField(primary_key=True, max_length=30) password = models.CharField(max_length=200) class question_solved(models.Model): q_id = models.CharField(primary_key=True, max_length=20) username = models.CharField(max_length=30) Thanks in advance. -
I want to create form fields in Django views.py rather then forms.py
I am creating my form in Form.py like this . class pdftabelModelForm(forms.ModelForm): class Meta: model = pdftabel_tool_ fields = ['apn', 'owner_name'] apn = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)") owner_name = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)") But due to some reasons like 'self' is not available in form.py . I can only access it in views.py. So I want to make it like class FieldForm(ModelForm): class Meta: model = pdftabel_tool_ fields = ( 'apn', 'owner_name',) And Now I want to make these fields as dropdown As I done in my forms.py. How can I do that ? kindly guide me. -
how to preprocess a local CSV file before upload
I'm working on a Django project where the user is able to upload a CSV file. What I want to do is that user can edit the local csv file , and apply the changes he wants to the csv values before upload. I have tried the javascript FileReader API but it seams that it does not offer the editing possibility. Is there a way to do so ? Is there some tutorials that can help ? Thank you -
Sort tasks in descending order
Actually, if I put {{ object.notes.all }} in my .html, it gave me the following list <QuerySet [<Note: Task #0000001>, <Note: Task #0000002>]> where Task 1 is older than Task 2. I would like the most recent tasks to appear first in the list. How could I modify {{ object.notes.all }} so that it works? -
How to create a custom email in Django
I searched about how to create custom emails and all I came across was cloud companies doing the magic for you at a fee. Is there any documentation or libraries any one can use in a Django project to come up with a custom email. -
Two Froms in Class based view of Django
I have two models, each model has it's own form. In a template page i would like to display two forms. But i can see that we can define only one model and form. class TicketView(ObjectEditView): form_class = forms.FirstForm model = First def get(self, request, pk): first = get_object_or_404(First, pk = pk) return render(request, 'my_folder/file.html', { 'first': first, 'form': self.form_class, }) But how can i pass my second form? form_classes = {forms.FirstForm, forms.SecondForm} some thing like this is possible? In template for first form i can display a comment field by {% render_field form.comment %} I would like to display second forms fields too like that. -
django.db.utils.IntegrityError: UNIQUE constraint failed: core_profile.user_id
I'm starting my first webproject with django, -I have created an APP "core" to handle registration and login -During the registration i want the user to submit some additional informations to create a Userprofile -I extended Django's default User model with OneToOne relation i'm gettin this error when i try to upload files Traceback: File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: core_profile.user_id) was the direct cause of the following exception: File "C:\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\djangoprojects\mysite\mysite\core\views.py" in upload_files 92. document.save() File "C:\Python36\lib\site-packages\django\db\models\base.py" in save 806. force_update=force_update, update_fields=update_fields) File "C:\Python36\lib\site-packages\django\db\models\base.py" in save_base 836. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Python36\lib\site-packages\django\db\models\base.py" in _save_table 922. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python36\lib\site-packages\django\db\models\base.py" in _do_insert 961. using=using, raw=raw) File "C:\Python36\lib\site-packages\django\db\models\manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python36\lib\site-packages\django\db\models\query.py" in _insert 1060. return query.get_compiler(using=using).execute_sql(return_id) File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 1099. cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute 80. return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\utils.py" … -
Parsing xml file in django
I've an xml document on my project folder and i've problem with extraction of values of an attribute of an element. My xml file looks like this : <?xml version="1.0" ?> <results filename="/home/maker/media/image" syncfile="/home/maker/media/synchro.xml"> <readbit number="1" frame="10" bit="0" score="-0.483138" status="n" /> <readbit number="2" frame="20" bit="1" score="0.416175" status="n" /> <readbit number="3" frame="30" bit="0" score="-0.457450" status="n" /> <readbit number="4" frame="40" bit="1" score="0.597008" status="y" /> .... </results> What i tried in my view to get all values of the attribut bit: def parse(request): xmldoc = minidom.parse('synchro.xml') readbitlist = xmldoc.getElementsByTagName('readbit') elements = [] for s in readbitlist : x = s.attributes['bit'].value elements.append(x) return render(request, 'parse.html', {'values': values}) In my template: <html> <head> <title> Mark </title> </head> <body> {% for element in values %} <p> {{ element }} </p> {% endfor %} </body> -
How to have my users add song to an album in django
I am trying to be able to add songs through a form but keep getting the NOT NULL constraint failed: post_song.album_id. as of right now i can only songs ramdomly and they aren't connected to the original album from django.db import models from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth.models import User class Album(models.Model): creator = models.CharField(max_length=250) album_name = models.CharField(max_length=250) album_photo = models.FileField() author = models.ForeignKey(User, blank=True, null=True, related_name ='album_post') category = models.ManyToManyField(Category) def get_absolute_url(self): return reverse('post:detail', kwargs={'pk': self.pk}) def __str__(self): return self.creator + ' - ' + self.album_name class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song_name= models.CharField(max_length=1000) def __str__(self): return self.song_name views.py class SongAdd(CreateView): model = Song fields = ['song_name'] details page {% block body %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'post/form-template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> {% endblock %} -
django strange warning for urlconf
Django behaves as I hoped and expected, but gives me a warning. It seems my use-case was not thought about. Which confuses me, so my question: do I miss any problems waiting for me, or did the developers miss this use case. I want the url person/<slug>/ to point to a detail view, and the url persons/ to point to the list view. It is more human-readably-correct than beginning with persons/ in the detail view too. I use include to make the code neater, something like: url(r'^person', include([ url(r'^s/$', views.foo), url(r'^/(?P<slug>[\w-]+)/form/$', views.form), url(r'^/(?P<slug>[\w-]+)/$', views.bar), ])), now django tells me, that the slash at the beginning is unneccesary - which is wrong, leaving it out leaves me with reversed urls person<slug> with no slash in between. I do not see why this should be bad style. The warning is: WARNINGS: ?: (urls.W002) Your URL pattern '^/(?P<slug>[\w-]+)/form/$' [name='person_form'] has a regex beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. -
Django-ViewFlow: How to add CRUD views to flow
I've recently come across the Viewflow library for Django which I appears to be a very powerful tool for creating complex workflows. My app is a simple ticketing system were the workflow is started by creating a Ticket, then a user should be able to create zero or more WorkLog's associated with the ticket via a CRUD page(s), similar to the standard Django admin change_list/detail. What should the template for the list view look like? I would like to have the UI integrated into the library's frontend. The flow clearly utilises the following views: 1) CreateView for Ticket 2a) ListView of WorkLog's, template has controls 'back', 'add' (goes to step 2b), 'done' (goes to step 3). 2b) CreateView for WorkLog 3) End Code: models.py: class TicketProcess(Process): title = models.CharField(max_length=100) category = models.CharField(max_length=150) description = models.TextField(max_length=150) planned = models.BooleanField() worklogs = models.ForeignKey('WorkLog', null=True) class WorkLog(models.Model): ref = models.CharField(max_length=32) description = models.TextField(max_length=150) views.py: class WorkLogListView(FlowListMixin, ListView): model = WorkLog class WorkLogCreateView(FlowMixin, CreateView): model = WorkLog fields = '__all__' flows.py: from .views import WorkLogCreateView from .models import TicketProcess @frontend.register class TicketFlow(Flow): process_class = TicketProcess start = ( flow.Start( CreateProcessView, fields = ['title', 'category', 'description', 'planned'] ).Permission( auto_create=True ).Next(this.resolution) ) add_worklog = ( flow.View( … -
Why newly created project doesn't display built-in API Django documentation?
I have a problem described in this post I have no idea what is the reason of the problem so I decided to create a new project both in Docker like without it. In both cases I get the same problem. To wit to newly created project I add only to urls.py: from rest_framework.documentation import include_docs_urls API_TITLE = 'API title' API_DESCRIPTION = '...' urlpatterns = [ url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)) ] and in Docker requirements.txt I add coreapi. In case of project without Docker I install via virtualenv pip3 install coreapi. That is all what in my opinion I should do in order to get a view like at the top of this site from documentation Obviously at http://localhost:8000/docs/ However in both cases I get TemplateDoesNotExist at /docs/ rest_framework/docs/index.html Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/site-packages/django/contrib/admin/templates/rest_framework/docs/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/site-packages/django/contrib/auth/templates/rest_framework/docs/index.html (Source does not exist) (in virtualenv there is only different path) Does anyone have an idea what might be wrong? If more details will be needed I will add it immediately to this post, just let me know. UPDATE When I add rest_framowork to INSTALLED_APPS I get: AttributeError at /docs/ 'NoneType' object has … -
How to filter a model through multiple forms?
I have a single Car model which I'd like to filter through interdependent ModelChoiceField's: class Car(models.Model): make = models.CharField(max_length=50) model = models.CharField(max_length=50) platform = models.CharField(max_length=50) Forms.py: class MakeSelectForm(forms.ModelForm): make = forms.ModelChoiceField(queryset=Car.objects.values_list('make',flat=True).distinct()) class Meta: model = Car fields = ["make"] class ModelSelectForm(forms.ModelForm): model = forms.ModelChoiceField(queryset=Car.objects.values_list('model',flat=True).distinct()) class Meta: model = Car fields = ["make", "model"] Views.py: def make_select_view(request): form = MakeSelectForm() make = None if request.method == "POST": form = MakeSelectForm(request.POST) if form.is_valid(): make = form.cleaned_data['make'] return render(request, "reviews/makeselect.html", {"form": form, "make": make}) def model_select_view(request, make): form = ModelSelectForm() model = None if request.method == "POST": form = MakeSelectForm(request.POST) if form.is_valid(): model = form.cleaned_data['model'] return render(request, "reviews/modelselect.html", {"form": form, "model": model}) URL's: urlpatterns = [ url(r'^$', views.make_select_view, name="make-select"), url(r'^(?P<make>\w+)/$', views.model_select_view, name="model-select"), ] Makeselect.html: <form action="{% url 'reviews:model-select' make %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Select" /> </form> Now, I have to pass "make" argument of the first form when posted, to the second view, and then use it to filter through Car instances with that make. But here all I pass is "None", and get Select a valid choice. That choice is not one of the available choices. error in the second form. Any suggestion or feedback will … -
Docker service exposed port connection times out
I have an image that exposes a django app on port 8000 In case A , i create a one node swarm, then deploy a service to the swarm using docker service create --name django -p 8000:8000 --hostname django myrepo/myimage:mytag Then i try to use curl localhost:8000 to inspect the service, but the connection seems to hang Creating a simple container from the same image with docker run -p 8000:8000 -d myrepo/myimage:mytag will return a response from the previous curl command Any idea what the issue is? Thanks -
Scrapy doesn't respect LOG_FILE settings
I'm running Scrapy spider as a Celery task. The problem is that Scrapy doesn't log into the file scrapy.log. It logs into the Celery log which. Moreover, I can see DEBUG levels inside Celery log and I don't know if it's because of celery settings or scrapy settings. [2017-07-17 05:49:20,848: WARNING/Process-4:1] 2017-07-17 05:49:20 [spider_1] INFO: Skipping telephone request... [2017-07-17 05:49:22,277: DEBUG/Process-4:1] Crawled (200) https://w... I've set Celery logging level to info: celery worker -A realestate_scanner -l info --logfile=logs/celery.log --purge And I've set scrapy LOG_LEVEL and LOG_FILE in SCRAPY settings.py: LOG_LEVEL = 'INFO' LOG_FILE = django_dir+'/logs/scrapy.log' The scrapy project is inside one of my Django app. This is celery.py: from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'realestate_scanner.settings') app = Celery('realestate_scanner') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) And I have Django in DEBUG mode. Do you know what to do? How to set celery loglevel to INFO and Scrapy to log to it's own file. -
Add a button in a Django ModelForm
I have created a simple form in which the user is specifying the name of a (Bloomberg)Ticker. In a second field the user is entering an address of a webpage. Of course, she/he can manually correct it but I would like to offer him/her a button such that the app suggests the name of the page based on the content of first Ticker field, e.g. the user enters "CARMPAT FP Equity" and then the app suggests correctly https://www.bloomberg.com/quote/CARMPAT:FP # forms.py from django.forms import ModelForm, ValidationError from pybloomberg.bloomberg import valid_ticker from .models import Symbol class SymbolAdminForm(ModelForm): # Have a button next to address field... class Meta: model = Symbol fields = '__all__' def clean(self): cleaned_data = self.cleaned_data ticker = cleaned_data.get('bloomberg_symbol') return cleaned_data def react(self): # extract the content for the bloomberg_symbol field address = ... # manipulate the content for the address field self.... = address -
Debugging issue with cronjob
I've got a script written for django I can call with python manage.py getimages I've added a line in crontab -e to run it */1 * * * * python /home/sammy/revamp/manage.py getimages and it has made this log in /var/log/syslog Jul 17 10:38:01 samuel-pc CRON[24486]: (sammy) CMD (python /home/sammy/revamp/manage.py getimages) There is however a problem since when this script is run it adds images to a model and after waiting I ran it and it does so. Need someone who can help me debug the issue. -
Overriding the clean() function in BaseInlineFormSet
I am trying to override the clean() function in the BaseInlineFormSet to check for some value first ... if it exceeds the limit it raise a ValidationError but what happens is when the user validate the condition it stops at the raise part and nothing happen. the form isn't saved and the error is not raised.. any explanation? class BaseDetailFormSet(forms.BaseInlineFormSet): def clean(self): super(BaseDetailFormSet, self).clean() if any(self.errors): return for form in self.forms: product = form.cleaned_data['product'] if form.cleaned_data['quantity_sold'] > product.quantity_in_stock: raise forms.ValidationError('not enough products') #code stops here note: i am sure that it enters the if part so i am sure it stops at the raise line -
Django: Limit user "can change/delete" permission based on one-to-one field
So I added a one-to-one field to extend the Django auth user model: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) division = models.ForeignKey(Division, on_delete=models.CASCADE) What I want to archieve is that every Employee has permission to change other Employee objects, but limited to those from the same division they belong to. Now each employee has a 'can change' permission for both the all of the Employee and all of the User objects. I managed to filter the django admin change list on the OneToOneField, so each employee only gets to see the employees from their owns division in the change list. Problem is, if they manually type in the URL for changing a user from another division, they are able to change/delete this user. Likewise they can even change/delete the Superuser (user 1). Navigating to: http://localhost:8000/admin/auth/user/1/change/ will do the trick. My idea to fix this was to override the auth user change method, adding a 'division-or-superuser' check, but that seems hacky. I would prefer to limit access to the change URL on the basis of division, but I haven't found a way to archieve this yet. Thanks for any suggestions! -
Django model for single elimination tournament
I have a function which returns a bracket list that represents a single elimination tournament. def determine_bracket(m): def divide(arr, depth, m): if len(complements) <= depth: complements.append(2 ** (depth + 2) + 1) complement = complements[depth] for i in range(2): if complement - arr[i] <= m: arr[i] = [arr[i], complement - arr[i]] divide(arr[i], depth + 1, m) arr = [1, 2] complements = [] divide(arr, 0, m) return arr To illustrate; schedule = determine_bracket(16) is returning a bracket list like following (You can consider each number as a team); [[[[1, 16], [8, 9]], [[4, 13], [5, 12]]], [[[2, 15], [7, 10]], [[3, 14], [6, 11]]]] I have Django model that represents this tournament matches. class MatchKnockout(models.Model): team_a = models.ForeignKey(Team, related_name="team_a") team_b = models.ForeignKey(Team) round = models.IntegerField(default=1) status = ( ('Not Started', 'Not Started'), ('Finished', 'Finished') ) date = models.DateTimeField(null=True) match_status = models.CharField(choices=status, max_length=40, default='Not Started') team_a_score = models.IntegerField(null=True) team_b_score = models.IntegerField(null=True) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True) However, I couldn't figure it out how to traverse through this bracket list and insert all matches according to rounds to the database. Actually, I achieved to insert first round matches but because we don't know the winners yet I couldn't do anything for other … -
'NoneType' object has no attribute 'to_bytes'
New on python and having a hard time with solving error codes. I have a form which adds rows to a postgresql databse. the form has an autofield which is primary key inside my models.py. Adding rows as such works, and the uniqueid fields counts up like inteded (1,2,3,...) models.py: class forwards(models.Model): uniqueid = models.AutoField(primary_key=True) user = models.CharField(max_length = 150) urlA = models.CharField(max_length = 254) counterA = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0')) urlB = models.CharField(max_length = 254) counterB = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0')) timestamp = models.DateTimeField('date created', auto_now_add=True) shortcodeurl = models.CharField(max_length = 254) forms.py: class AddUrlForm(forms.ModelForm): class Meta: model = forwards # fields = '__all__' exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"] The goal is to use the primary key value (which should be an integer according to here), transform it into "bytes" and then do a bytes-to-base64 conversion to create a shortcode-url. I want to store this shortcode inside the table. I try to do this in the views.py views.py def forwardthis(request): forwardform = AddUrlForm(request.POST or None) if forwardform.is_valid(): forward = forwardform.save(commit=False) forward.user = request.user.username uniqueid_local = forward.uniqueid print(uniqueid_local) uniqueid_local_bytes = uniqueid_local.to_bytes(3, byteorder='big') shortcodeurl_local = urlsafe_base64_encode(uniqueid_local_bytes) forward.shortcodeurl = shortcodeurl_local forward.save() My Problem: I don't succeed in creating this shortcode URL and am …