Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django raising ValueError: invalid literal for int() with base 10 on POST
Django is consistently throwing a ValueError on every POST request to the server. From cruising around forms and SE, it seems like this an issue with my Django models. However, I'm not sure why the models would throw this error or why they would be called by Django since this is thrown in a POST event. View in question: def channel(request, channel): user_form = weblog_userForm(request.POST or None) if request.method == 'POST' and user_form.is_valid(): nickname = user_form.cleaned_data['nickname'] message = user_form.cleaned_data['message'] password = user_form.cleaned_data['password'] postDetails = {} ... process request and eventually ... return HttpResponse(json.dumps(postDetails), content_type="application/json") My application models: class Line(models.Model): message = models.TextField(blank=True, default="") nick = models.CharField(max_length=50) hostname = models.CharField(max_length=300) channel = models.CharField(max_length=200) timestamp = models.DateTimeField(auto_now_add=True) LINE_TYPES = ( ('PMSG', 'PRIVMSG'), ('SMSG', 'SOCKETMSG'), ('WMSG', 'WEBMSG'), ('NTCE', 'NOTICE'), ('ACTN', 'ACTION'), ('JOIN', 'JOIN'), ('PART', 'PART'), ('QUIT', 'QUIT'), ('NICK', 'NICK'), ('TPIC', 'TOPIC'), ) msgType = models.CharField(max_length=4, choices=LINE_TYPES, default='PRIVMSG') def __str__(self): return self.message class banned_ips(models.Model): bannedIp = models.GenericIPAddressField() Traceback: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/weblogs/log/views.py", line 96, in channel json_data = serializers.serialize("json", list(reversed(Line.objects.filter(id__gt=latest_line_id, channel=channel).order_by('-id')[:100]))) … -
Django gunicorn Can't connect to socket as user
Gunicorn shows me socket failed to connect when run as user, but when run as root it worked flawlessly. Below is the command. cd /home/myuser/web/myproject source /home/myuser/myvenv/bin/activate /home/myuser/myvenv/bin/gunicorn myproject.wsgi:application --name myproject --workers 3 --user=myuser --group=www-data --bind=unix:/home/myuser/myvenv/run/gunicorn.sock where Django project path: /home/myuser/web/myproject (which contains manage.py) Python virtualenv path: /home/myuser/myvenv When run as root: [2017-12-27 23:25:43 +0000] [24336] [INFO] Starting gunicorn 19.7.1 [2017-12-27 23:25:43 +0000] [24336] [INFO] Listening at: unix:/home/myuser/myvenv/run/gunicorn.sock (24336) [2017-12-27 23:25:43 +0000] [24336] [INFO] Using worker: sync [2017-12-27 23:25:43 +0000] [24339] [INFO] Booting worker with pid: 24339 [2017-12-27 23:25:43 +0000] [24340] [INFO] Booting worker with pid: 24340 [2017-12-27 23:25:44 +0000] [24377] [INFO] Booting worker with pid: 24377 I killed the process, and made sure it does not exist in ps -A | grep gunicorn. Then I tried to run same command as myuser. Below is the error when I run the command. [2017-12-27 23:21:30 +0000] [23965] [INFO] Starting gunicorn 19.7.1 [2017-12-27 23:21:30 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:31 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:32 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:33 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:34 +0000] [23965] [ERROR] Retrying in 1 second. [2017-12-27 23:21:35 +0000] [23965] [ERROR] … -
How to login using django & mongodb
I have coding challenge must use technologies: - Python/Django - Backend : Django - Frontend : Angular - Database : MongoDB I found some problems in login, in django how i can login using database mongodb views def auth_login(request, on_success='/', on_fail='/account/login'): user = authenticate(username=request.POST['email'], password=request.POST['password']) if user is not None: login(request, user) return redirect(on_success) else: return redirect(on_fail) Error : settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
How can I implement EAV in Django?
Can Django implement EAV? If so, how would you go about doing so? I am new to Django so I am trying to learn this early on so I do not waste time attempting it on my own. -
Django REST Framework custom headers in request object
I have a problem viewing incoming custom headers from requests when I'm creating a new API view via the @api_view decorator. My custom API view looks like this: @api_view(['GET']) def TestView(request): print(request.META) return Response({'message': 'test'}) What I'm expecting is doing something like curl --request GET \ --url http://localhost:8000/test \ --header 'custom: test' I'd see my custom header called custom to appear in the output. Instead, it's not there at all. From the documentation, it says the following for the request.META field: A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples: Whereas, they don't appear at all in my output. Am I missing something here? If it's relevant, I register my URL as such: urlpatterns = [url(r'test', views.TestView, name='test'), ...] My end goal is to write a custom permission class that will parse the custom header and do something related to authentication with it, and either allow or deny the request. My POC here is just to show the basic example of what I'm dealing with. I can provide the output of the print(request.META) but it's just a wall of text without my expected header present. -
Recording temporarily before payment
I am working on a workflow to create an order. Here is what I got so far from django.db import models from django.utils.translation import ugettext_lazy as _ from django_fsm import FSMField, transition from ev5.core.models import TimeStampedModel class Order(TimeStampedModel): STATE_CHOICES = ( ('start', _('Start')), ('received', _('Received')), ('completed', _('Completed')), ('approved', _('Approved')), ) date_order = models.DateTimeField(_('Order date')) customer = models.ForeignKey('customers.Customer') state = FSMField(...) def get_id_display(self): return '#{0.8d}'.format(self.pk) def __str__(self): return _('Order {} ({})').format(self.get_id_display(), self.get_state_display()) @transition(field=state, source='start', target='received') def received(self): pass @transition(field=state, source='placed', target='completed') def completed(self): pass @transition(field=state, source='completed', target='approved') def approved(self): pass I need to implement a standard workflow with three linear steps to handle, i.e. Select Plan & Preference, Personal Information, and Review & Payment. 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. Roughly, an account and an order will be recorded at the end step of the workflow if the payment is accepted. Hence, during the transition, I don't want the information … -
When I center Navbar the text becomes squished
I would like my navbar to be centered and always be shown at the top of the screen however whenever i think I've fixed it something goes wrong this time the text text is mushed. I would like it to be strait across. Also sometimes when I try to fix it the "Home" button and the image overlap. Thank You. How it looks centered How I would like it to look, but not centered <!doctype html> <html lang="en"> <head> <title>The Benjamin Project | Home</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="/static/assets/css/animate.css"> <link rel="icon" href="/static/assets/img/favicon.ico"> <!-- site icon --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="/static/assets/script.js"></script> <style> @font-face { font-family: Panton; src:url("/static/assets/font/Panton-LightCaps.otf"); } body { margin: 0; padding: 0; background-color: #8CD28C; overflow-x: hidden; min-height:75px; line-height:75px; } .navbar { margin: 0; border-radius: 0; background-color: #8CD28C; /*bg color for tabs on navbar*/ color: #606060; /*text color for tabs on navbar*/ padding: 50px 0px 50px 0px; font-size: 2em; font-family:Panton; border: 0; animation-duration: 1.5s; } .navbar-default .navbar-nav .active a, .navbar-default .navbar-nav .active a:focus, .navbar-default .navbar-nav .active a:hover { color: #606060; /*text color for active*/ background-color: #8CD28C; /*bg color for active*/ font-weight: bold; } .selected { text-decoration-line:underline; } .navbar … -
Django Custom instanciation of model with custom form
I'm currently doing my forms for my app that works with the following three model classes: the app manages lobbies, a lobby has a many to many relationship with signatures, and a signature has a one to one relationship with users. I don't want my users to manipulate the signatures, it's just a class that stores other datas and that will execute other pieces of code later. How can I create a form that would propose all the standard lobby fields, but also a choice fields displaying users that I would use in the end to instanciate my signatures procedurally? I hope it's clear enough. Thanks in advance. -
Ansible uri call with Django JWT token
I would like to call django server with ansible: I have called: - name: Check status 200 uri: url: https://{{ rest_server }}/api/users/api-token-auth/ method: POST headers: Content-Type: "application/json" body: '{"username": "username", "password": "password"}' return_content: yes register: token and I get the token. Now I would like to use this token for the next call, but I can't figure out how this is working.... I try - name: Check that LOGIN returns a status 200 uri: url: https://{{ rest_server }}/api/users/auth/ method: POST headers: Content-Type: "application/json" Authorization: "JWT {{ token.content[token] }}" body: '{"username": "user", "password": "pass"}' return_content: yes register: webpage but I get error: "msg": "The task includes an option with an undefined variable. The error was: ansible.utils.unsafe_proxy.AnsibleUnsafeText object has no element {u'cookies': {}, u'vary': u'Accept', u'access_control_allow_headers': u'Access-Control-Allow-Origin, Content-Type, X-CSRFToken, Authorization, Access-Bw, Content-Disposition', u'access_control_allow_methods': u'GET, DELETE, POST, PUT, OPTIONS', u'access_control_allow_credentials': u'true', u'content': u'{\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hcmtvLnphZHJhdmVjQHJlc3VsdC5zaSIsImV4cCI6MTUxNTAxNDE1OSwidXNlcl9pZCI6NCwidXNlcm5hbWUiOiJtYXJrby56YWRyYXZlY0ByZXN1bHQuc2kifQ.otlXbiuXnDJPiLrEKdMTKBgBMbvIGApBVH_aPI5mSd4\"}', 'failed': False, u'json': {u'token': u'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hcmtvLnphZHJhdmVjQHJlc3VsdC5zaSIsImV4cCI6MTUxNTAxNDE1OSwidXNlcl9pZCI6NCwidXNlcm5hbWUiOiJtYXJrby56YWRyYXZlY0ByZXN1bHQuc2kifQ.otlXbiuXnDJPiLrEKdMTKBgBMbvIGApBVH_aPI5mSd4'},.... What is the right way to do it? -
pgettext in jinja2 django templates
I have configured the Jinja environment with env.install_gettext_translations(translation, newstyle=True) and the jinja2.ext.i18n extension. I can only use the _(), _gettext() and ngettext() functions in my jinja2 templates. I want to use pgettext() (django docs) as well to add a context to the translatable strings. Is there an extension that does so or am I missing something? -
Ensure User Entered Integer
I am new to Django, and I recently created a system where users can look up a record based on a number. It's just a simple search. The system numbers have leading zeros, and I want the system to recognize the numbers with or without the zeros. I have been able to implement this system and I am converting the number the user specifies with the following code: def get_queryset(self): queryset = super(SearchResultsView, self).get_queryset() search_query = int(self.request.GET.get("q")) if search_query: queryset = Book.objects.filter(Q(request_number__icontains=search_query)).distinct() The code above works fine, as long as the user enters a number. If they typo and include letters, I get invalid literal for Base10. I understand the error, a letter is not an INT. I have spent most of the afternoon looking for how to prevent this error and I can't find what I'm looking for. I have tried to do something like: if search_query: try: queryset = Book.objects.filter(Q(request_number__icontains=search_query)).distinct() except ValueError: q = 0000000 return queryset But the letters are still interpreted and then I receive the invalid literal for Base10 error again. How can I prevent the letters from causing a problem with my query based on a number? I have also figured out that if … -
Django TinyMCE ImageLists when using HTMLField
I'm struggling to get the imagelists and linklists working in TinyMCE on Django when using a HTMLField. The documentation says: somefield = forms.CharField(widget=TinyMCE(mce_attrs={'external_link_list_url': reverse('someviewname')}) But I'm using the HTMLField so have to approach it differently. I've looked at How to increase width of editor in django-tinymce HTMLField? and am getting the same init error as suggested. Has anyone been successful with this? -
Remove data from the database when the remove button of a datatable is clicked
I am using a datatable to dispay information for the user and it is generated a delete button per row. I would like to delete the row data from the database when the user click on it. How can I do that? HTML .. $('#id_data').DataTable({ destroy: true, data:data_array_data, "bLengthChange": false, //"bAutoWidth": false, "scrollX": true, "order": [[ 22, "desc" ]], "aoColumns" : [ {title:'User', sWidth: '10px', className:'dt-center' }, {title:'Business', sWidth: '10px', className:'dt-center' }, ... {title:'Revenue', sWidth: '10px', className:'dt-center' }, {title: "",sWidth:'5px',className:'dt-center', "bSortable": false, "mRender": function() { return'<button class="btn btn-danger" id="btn_item_' + itemIndex++ + '"' + ' name="mybtndelete"">Delete</button>'; }, }, ] }); Views @login_required def remove_register(request): instance = MyModel.objects.get(id=pk) "How can I obtain the pk from the datatable?" instance.delete() -
How can I get the current user's group in forms.py in Django?
I have a scenario where i need to pass the logged-in user's groud name and get the list users in that group. forms.py -- in the below code i need to pass the user's group instead of Banglore class UpateTaskMaster(forms.ModelForm): def __init__(self, *args, **kwargs): super(UpateTaskMaster, self).__init__(*args, **kwargs) users = User.objects.filter(groups__name='Banglore') self.fields['processor'].choices = [(user.pk, user.get_full_name()) for user in users] class Meta(): model = TaskMaster fields = ["sid","tasktype","task_title","task_description","datacenter","status","priority","sourceincident","processingteam","duedate","pid","errorincident",'processor'] widgets = { 'sid': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'task_title':forms.Textarea(attrs={'class': 'materialize-textarea'}), 'task_description':forms.Textarea(attrs={'class': 'materialize-textarea'}), 'sourceincident': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'pid': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'errorincident': forms.TextInput(attrs={'class': 'form-control mr-sm-2'}), 'duedate' : forms.TextInput(attrs={'class': 'datepicker'}), } -
How to override value of read-only field in view depending on query param?
I have this model that has a read-only field where I calculate some property. class BlastEvent(Event): tonnes = models.FloatField() blast_type = models.ForeignKey(BlastType) @property def size(self): return self.tonnes / BlastEvent.objects.all().aggregate(Max('tonnes'))['tonnes__max'] This is my serializer: class BlastEventSerializer(serializers.HyperlinkedModelSerializer): size = serializers.ReadOnlyField() included_serializers = {'blast_type': BlastTypeSerializer} blast_type = ResourceRelatedField( queryset=BlastType.objects, related_link_view_name='blastevent-blasttype-list', related_link_url_kwarg='pk', self_link_view_name='blastevent-relationships' ) class Meta: model = BlastEvent fields = ('url', 'id', 'tonnes', 'blast_type', 'size') class JSONAPIMeta: included_resources = ['blast_type'] And this is my view: class BlastEventViewSet(EventViewSet): queryset = BlastEvent.objects.all() serializer_class = BlastEventSerializer Now I need to re-calculate and override this read-only field depending on query parameter. I'm not sure where is the proper place to do it. I tried to do it in get_queryset() method of my view like this: class BlastEventViewSet(EventViewSet): queryset = BlastEvent.objects.all() serializer_class = BlastEventSerializer def get_queryset(self): queryset = self.queryset instrument_id = self.request.GET.get('instrument_id') if instrument_id: for e in queryset: e.size = e.size + Instrument.objects.get(pk=instrument_id).distance return queryset but it doesn't work. It says 'AttributeError: can't set attribute': Traceback: File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/nargiza/virtualenvs/myenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 86. return self.dispatch(request, … -
overriding django formset initial data dynamically
Ok im new to django So ive got a situation where i want a formset to have dynamic initial data So basically here is what im looking for. each form in the formset to have a different UserID and a set of groups permission which they can choose from based from the initial data here is my form class assignGroupPermissionToUser(forms.ModelForm): UserID = forms.ModelChoiceField(queryset=None) Groups = forms.ModelMultipleCHoiceField(queryset=None, widget=FilteredSelectMultiple("Groups") class Meta: model=User def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) Userid = kwargs.pop("UserID") self.fields['UserID'].queryset =User.objects.get(UserID=Userid) Permissions = kwargs.pop("Groups") listofPermission = None for each perm in permission: listofPermission |= Permissions.objects.filter(GroupID=perm) self.fields['Groups'].queryset = listofPermission the data i wanna pass is built into a list like so it is called completeList > completeList =[['13452',{'group1':'Admin','group2':'FrontDesk'}],['3532','group1':'Supervisors','group2':'ReadOnly;}]] where the first value in each nested loop is the UserID, and the dictionary is the groups they can choose from. override method in View.py .... form = assignGroupPermissionToUser() assignment = formset_factory(form,extra=0) formset = [ assignment.__init__(completeList[x][0],completeList[x][1]) for x in range(len(completeList))] then i get an error that str object has no 'is_bound' field line 58 of formset.py im trytin to get this data to show up on each form and based on the user it will be all different but everything i try to override it fails … -
Django admin panel - Inlines do not show on production server, but do show on local server
Recently I started using the inline functionality for Django admin panels. It just makes it so much easier to add objects. The picture below shows that it allows an admin to add a module while creating a training: Django admin panel with working inlines However, once I push the code to production, the inlines functionality stops working. It simply does not show. My server makes use of Gunicorn and Nginx. Initially I thought that Nginx does not know where to find the static files, but this is not the problem. However, if I run a server via Django with python manage.py runserver 0.0.0.0:8001, then it does work. Additionally, if I run the server via Gunicorn by binding it to 0.0.0.0:8001, then it works as well. This makes me think that the problem is Nginx, but I have no idea where to search. Please help me out :). Kind regards, Nicky -
Django Admin ChoiceField and Button submit to custom admin site (A form in a form)
I would like to generate a contract (as a printable html file) out of the change form of a customer (defined as model) in the django.contrib.admin interface. This contract should be displayed as html file in a different view. So my idea is to have a Dropdown (forms.ChoiceField) with a Submit button in the admin form of a model. If you click on the button then a custom admin site (or HttpResponse, doesn't matter now) will be opened depending on the selected choice. So for example, if I select "Contract one" and click on the button, a page with the template from contract one will be displayed in a new page. But all this should be inside the change_forms.html in a seperate fieldset. What I have so far: A ModelForm with an extra field 'contract' and rendering the button with url reverse as forced html output. admin.py class AnimalAdmin(admin.ModelAdmin): form = AnimalForm list_display = ( 'name', 'customer', ) ordering = ('name',) fieldsets = ( (None, { 'fields': ( ('name', 'species'), ('customer', 'breed'), ) }), (_('Vertrag'), { 'fields': ( ('contract'), ('animal_contract'), ) }), ) readonly_fields = ('animal_contract',) def process_contract(self, request, animal_id, *args, **kwargs): return self.process_action( request=request, animal_id=animal_id, action_title='Contract Generation', ) def … -
What's difference between url() and reverse() methods in Django?
I have some method, and after successful form submitting i need to make some redirect to another page. How can i do this? return HttpResponseRedirect(reverse('goods:results', args=(item.id,))) or return HttpResponseRedirect(url('polls:results', question.id))? What's the main difference by using these two ways? -
Managing state and transitions
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. How to check what is the next view that the user should go? Could someone explain to me roughly how can I do it? Does the following website is a great solution for that little workflow? P.S. I am working with Django 1.11 and python 3.4. -
Django - "IOError: [Errno 9] Bad file descriptor" when loaddata a fixture during tests
Traceback (most recent call last): File "py2env/local/lib/python2.7/site-packages/django/test/testcases.py", line 1036, in setUpClass 'database': db_name, File "py2env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "py2env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "py2env/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "py2env/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "py2env/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 198, in load_label fixture.close() IOError: [Errno 9] Bad file descriptor The size of the fixture is 24KB. The exception happens when running tests and happens sporadically. Django 1.11.8 Mac OSX & Linux Note: Wrapping 'loaddata.py, line 198' with try & catch IOError. Setting a breakpoint and continuing immediately prevents the exception. Like this: try: fixture.close() except IOError as e: import pdb; pdb.set_trace() Overriding loaddata command as suggested here didn't help. -
That page number is less than 1 Django
I have read almost all the thread related to a similar error message and none of them offered a solution to my problem. I a story and for each story there are chapters. The idea is that there will be a chapter per page but I keep getting the same error message "EmptyPage at /story/1/page/1/" when I try pagination. I have multiple chapters for each story and I still get page number is less than 1. views.py def post(request, id_story, page=1): story = Story.objects.get(id=id_story) chapters = story.chapter_set.all() paginator = Paginator(chapters, 1) try: chapters = paginator.page(page) except PageNotAnInteger: chapters = paginator.page(1) except EmptyPage: chapters = paginator.page(paginator.num_pages) return render(request, 'single.html', {'story': story, 'chapters': chapters}) models.py class Story(models.Model): Lang =( ('LA', '-LANGUAGE-'), ('Ar', 'ARABIC'), ('Ot', 'OTHER') ) title = models.CharField(max_length=250, null=False) author = models.ForeignKey(User, on_delete=models.CASCADE) summary = models.TextField(max_length=1000, null= False) pub_date = models.DateField(auto_now_add=True, blank=False, null=False) update_time = models.DateField(null=True) has_chapter = models.BooleanField(default=False, editable=False) lang = models.CharField(choices=Lang, default=Lang[0], max_length=3) story_cover = models.FileField() def __str__(self): return self.title + " - " + self.author.username class Chapter(models.Model): story = models.ForeignKey(Story, on_delete=models.CASCADE) chapter_number = models.IntegerField(editable=False, default=1) title = models.CharField(max_length=250, null=True) chapter = models.TextField() def save(self, *args, **kwargs): number = Chapter.objects.filter(story=self.story).count() self.chapter_number = number + 1 story = self.story if … -
Django admin list_display model method
I have this model.py: class Topping(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name class Base(models.Model): name = models.CharField(max_length=32) slug = models.SlugField(primary_key=True) class Advanced(models.Model): toppings = models.ManyToManyField(Topping) class Mymodel(Base, Advanced): ... def toppings_list(self): list_top = Advanced.toppings return list_top I want to show the list of toppings (preferably formatted, so a list only of the field name of the Topping model) in my Admin, so: class MymodelAdmin(admin.ModelAdmin): #list_display = (..., model.Mymodel.toppings_list(), ...) #Error: missing 1 required positional argument: 'self' #list_display = (..., model.Mymodel.toppings_list(self), ...) #Error: self is not definited list_display = (..., model.Mymodel.toppings_list, ...) #Gibberish: <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x0387FFD0> Only the last one works but don't gives nothing useful. I tried these too (I want format the list before to display): class MymodelAdmin(admin.ModelAdmin): mylist=model.Mymodel.toppings_list #I don't change nothing for now #mylist=[t for t in model.Mymodel.toppings_list] #Error: 'function' object is not iterable list_display = ('mylist') #core.Topping.None again, the last one works but don't gives nothing useful (also Topping isn't None) Thank you -
How do I make a input from the user to search for something in django/python?
I'm relatively new in python/django thing. Having 3 models with some fields for example: class Card(models.Model): id = models.AutoField(primary_key=True) cardtype_id = models.CharField(max_length=10) holder_name = models.CharField(max_length=100) card_number = models.IntegerField(default=0) email = models.EmailField(blank=True) birthday = models.DateField(blank=True, default=None) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(default=timezone.now) strip = models.CharField(max_length=20, default="strip") def __str__(self): return self.holder_name class Transaction(models.Model): id = models.AutoField(primary_key=True) description = models.CharField(max_length=100) class CardTransactions(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) value_date = models.DateTimeField(default=timezone.now) created = models.DateTimeField(default=timezone.now) description = models.CharField(max_length=200, blank=True) table_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) discount = models.DecimalField(max_digits=7, decimal_places=2, blank=True) net_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) doc_number = models.CharField(max_length=20, blank=True) How can I ask the user to input, for example, the "card_number" and print out the "description" on a HTML page? -
'TemplateDoesNotExist at /' error during local development
I am following two scoops of django and mozilla tutorial for deploying my app. I set up a virtual env and base setting, local setting,etc and when i ran the command : ./manage.py runserver 0:8000 --settings=Books.settings.local the browser showed the error, template home not found... I think there might be some problem due to the env, i am not sure. base.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '2z9y' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ALLOWED_HOSTS = ['127.0.0.1', 'localhost','https://hackingonlineeducation.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'star_ratings', 'crispy_forms', #my_apps 'newsletter', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Books.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Books.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, …