Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : OperationalError: near ")": syntax error postgre to sqlite
I decided to use a sqlite3 db for some of my django tests using LiveServerTestCase(How to have Django test case and Selenium server use same database?) Here is my settings.py : DATABASES = { 'test': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'my_db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } But when i run my tests.. : Using existing test database for alias 'test'... Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 74, in … -
Showing ManyToManyField in Django Admin Site
I'm going through the Mozilla's django tutorial. They're basically creating a public library. They do not really talk about ManyToMany relationships, and have set it up so that one book can only have one author. While going through this tutorial, I decided to instead of copying their local library, to go ahead and try to create the basic functionality of IMDB. So that I do not end up just basically copying and pasting the code and not learning anything. I have set it up in a way that a show can have many creators using the ManyToMany field. In my class Creator I have two variables first_name and last_name. I have another class Show that has a bunch of other variables. Now inside my admin.py of the app called show, I want it so that in my ShowAdmin, it will display the creators in the admin table. The problem lies in the fact that Django does not support ManyToMany because it's a huge load to query. Now my possible solution is to: 1) create an empty array 2) loop through the first_name array and add it to the empty array. 3) loop through the last_array and add it to the … -
Django: how to access JsonResponse dictionary in jquery?
Jquery $('#id_buysell').on('change', function(){ console.log("buysell"); var $id_buysell = $('#id_buysell').val(); console.log($id_buysell); $.ajax({ method: "GET", url: "/myportfolio/add_transaction", data: { buysell: $id_buysell } }); }); Views def add_transaction(request): if request.method == "GET": if request.is_ajax(): print("ajax test") #print(request.GET.get) print(request.GET.get('coin')) print(request.GET.get('buysell')) data = { 'view_buysell': request.GET.get('buysell'), 'view_coin': request.GET.get('coin') } form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price) return JsonResponse(data) How do I access that dictionary sent from JsonResponse(data) in views to my jquery file? I have a limited understanding of jquery and front end development in general. I know that this will be sent through a JSON-encoded response, but have not been able to find the right answer when searching. -
Resources to put a web application online?
I'm a trainee developer, who is making his first steps in web development. I don't understnd how to put something online, once I have built an entire web application. I'm currently mounting a web server and I'd like to understand what I'm doing. I'm building a blog with django. I'm setting the URLs, the IP address, and the database. I'm following the Djangogirls tutorial. Any resource where I can learn more about what I'm doing? I'm just following the tutorial mechanically and I don't like it. Any book or online course? Something in Udemy? How did YOU learn about it? Thank you! -
setting gaffer + Profile with Django on VPS
I have a Django 2.0 application deployed on VPS with virtual environment setup using pipenv. At present, using this command to run the application from terminal in background. /root/.local/bin/pipenv run /home/user/.local/share/virtualenvs/app.application.com-IuTkL8w_/bin/gunicorn myapp.wsgi:application & Now, I want to configure using Procfile and gaffer. I added a file Procfile to root of the application directory with command web: gunicorn myapp.wsgi --log-file - --log-level debug and trying to load it with gaffer $ cd myproject $ gaffer load Procfile but it is giving error as Traceback (most recent call last): File "/usr/local/bin/gaffer", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/gaffer/cli/main.py", line 252, in main cli.run() File "/usr/local/lib/python3.6/site-packages/gaffer/cli/main.py", line 193, in run config = Config(self.args) File "/usr/local/lib/python3.6/site-packages/gaffer/cli/main.py", line 87, in __init__ api_key=api_key, **self.client_options) File "/usr/local/lib/python3.6/site-packages/gaffer/httpclient/server.py", line 22, in __init__ super(Server, self).__init__(uri, loop=loop, **options) File "/usr/local/lib/python3.6/site-packages/gaffer/httpclient/base.py", line 86, in __init__ self.client = HTTPClient(loop=loop) File "/usr/local/lib/python3.6/site-packages/gaffer/httpclient/base.py", line 42, in __init__ self._io_loop = IOLoop(_loop=loop) File "/usr/local/lib/python3.6/site-packages/gaffer/tornado_pyuv.py", line 54, in __init__ self._waker = Waker(self._loop) File "/usr/local/lib/python3.6/site-packages/gaffer/tornado_pyuv.py", line 28, in __init__ self._async.unref() AttributeError: 'pyuv._cpyuv.Async' object has no attribute 'unref' Exception ignored in: <bound method HTTPClient.__del__ of <gaffer.httpclient.base.HTTPClient object at 0x7f96746c5b00>> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/gaffer/httpclient/base.py", line 50, in __del__ self.close() File "/usr/local/lib/python3.6/site-packages/gaffer/httpclient/base.py", line 54, in close if not … -
Nginx proxy pass with django's APPEND_SLASH
Django has the APPEND_SLASH setting which transforms urls like x/y into x/y/ and returns 301 Moved Permanently redirecting to x/y/. nginx is set to proxy_pass requests like myserver.com/myapp/url to myserver.com:myport/url, django is listening on myport. What happens is: nginx receives a request to myapp/x/y, rewrites the url and proxy_pass-es x/y to django, django returns 301 redirecting to x/y/ which results in 404 on myserver.com/x/y/ because the myapp part of the url is lost. I don't want to hardcode myapp in django in any way because it's a part of nginx config. I tried proxy_set_header Host myserver.com/myapp in nginx and a middleware before CommodMiddleware in django to manage redirects, but myserver.com/myapp is not a valid domain name and django throws an exception. How can I setup nginx + django so that redirects from django go to the correct url while django knows nothing about nginx config? -
Why DjangoRF serializer is_valid is false?
My class class SprintSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField() class Meta: model = Sprint fields = ('id', 'name', 'description', 'end', 'links', ) In my shell,I populated a serializer with data serializer = SprintSerializer(data=({'name':'JHolmes','description':'ambassador','end':'2019-01-27T15:17:10.375877'})) Then serializer.data {'name': 'JHolmes', 'description': 'ambassador', 'end': '2019-01-27T15:17:10.375877'} serializer.validated_data {} serializer.is_valid() False Why is an instance serializer False? -
Django generic class view model change
In generic UpdateView, if you need to dynamically change the form depending on the passed object you can use this function (as in this answer): def get_form_class(self): if self.object.pk == 1: return MyForm else: return OtherForm Is there a similar function if i want to change the model? where model is: class SomeUpdateView(generic.UpdateView): login_required = True template_name = '...' model = SomeModel ## i need it dynamic form_class = SomeForm success_url = reverse_lazy('some_url') -
Use custom loader for a certain file extension in django
I have the following custom loader specific for .xml files. How can I use it as a default loader for all .xml files. from django.template.loaders.filesystem import Loader from io import StringIO from lxml import etree class XMLLoader(Loader): """Custom XML file loader""" def get_contents(self, origin): data = super(XMLLoader, self).get_contents(self, origin) parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(StringIO(data), parser) return etree.tostring(tree.getroot()) -
paginator is not working in django
I've followed the official docs to use paginator in Django and it not working, it shows the right page count but on every page, the whole list displayed instead of slicing it into many pages views.py def home(request): current_user = request.user all_dress = Item.objects.all().filter(dress_active=True).order_by('-created_at') all_good = Item.objects.all().filter(dress_special=True) all_name = Name.objects.all() all_ads = Ads.objects.all() #pig paginator = Paginator(all_dress, 3) # Show 12 dress per page page = request.GET.get('page') dresss = paginator.get_page(page) context = { 'all_dress': all_dress, 'all_name': all_name, 'current_user': current_user, 'all_good':all_good, 'all_ads':all_ads, 'dresss':dresss, } return render(request, 'fostan/index.html',context) HTML <div class="row"> <div class="col"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div> <div class="col"> <div dir="ltr"> <div class="pagination" align="left"> <span class="step-links" align="left"> {% if dresss.has_previous %} <a href="?page=1">&laquo; first </a> <a href="?page={{ dresss.previous_page_number }}"> previous</a> {% endif %} <span class="current"> Page number {{ dresss.number }} of {{ dresss.paginator.num_pages }} </span> <br> {% if dresss.has_next %} <a href="?page={{ dresss.next_page_number }}">next </a> <a href="?page={{ dresss.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> </div> <div class="col"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div> </div> I have 9 items, and I asked the paginator to show only 3 items per page, the result is 3 pages with the same 9 items on every page! -
Django : confirm that data is saved
when I do the following in my view : b=caisse(id_facture=idf,montantdeb=f.cleaned_data.get('montantdeb'),montantcred=f.cleaned_data.get('montantcred'),sens_operation=s,type_tiers=f.cleaned_data.get('typeTiers'),tiers=tier,date_operation=f.cleaned_data.get('dateOperation'),numpiece=num) b.save() I need to know , how can I test after save() execution, if the data is really saved, so I can show to the user that his data is saved successfuly. Thank You in advance -
Deploy django on Debian causes "ImportError No module named 'albuta' "
I'm trying to deploy Django project on Debian server with Apache2 and mod wsgi. I have created albuta.conf inside /etc/apache2/ and enabled it with a2ensite, and my wsgi file locates at /var/www/albuta/albutaenv/albuta/albuta/wsgi.py This is my albuta.conf file <VirtualHost *:80> ServerName albuta.net ServerAdmin natiq@vahabov.com DocumentRoot /var/www/albuta Alias /static /var/www/albuta/albutaenv/albuta/static Alias /media /var/www/albuta/albutaenv/albuta/media Alias /robots.txt /var/www/albuta/albutaenv/albuta/robots.txt WSGIPassAuthorization On WSGIDaemonProcess albuta python-home=/var/www/albuta/albutaenv python-path=/var/www/albuta WSGIScriptAlias / /var/www/albuta/albutaenv/albuta/albuta/wsgi.py \ process-group=albuta application-group=%{GLOBAL} <Directory /var/www/albuta/albutaenv/albuta/albuta> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> And this is error message that I read in /var/log/apache2/errors.log ImportError: No module named 'albuta' Target WSGI script '/var/www/albuta/albutaenv/albuta/albuta/wsgi.py' cannot be loaded as Python module. Exception occurred processing WSGI script '/var/www/albuta/albutaenv/albuta/albuta/wsgi.py'. ... -
Retrieve value from the database, as empty json {} or Null, male separate cases
I retrieve an column/record value from a table for an associated model. The value can be Null or an empty json {} I have the following code: cat = Cat.objects.order_by('?')[0] if cat.path is None: It is catching both situations, but I want to have separate cases. -
deployment error - django to elastic beanstalk
I am trying to deploy a django app to AWS using elastic beanstalk but it is saying that my requirements.txt is invalid when I run eb deploy. Can someone please help? Do I need to create eb virtual environment inside conda virtual env ? Or i can use any one ? Is it the same thing ? -
Django model validation - field required if RADIO button equals some_value
I have been trying to add some validation to a model: require a VAT field only if the checkbox is set to Company (value: 1). I have this model in Django: class CustomerInformation(models.Model): """CustomerInformation model is used to storing client data information.""" company_name = models.CharField( _('Company name'), max_length=200 ) order_type = models.PositiveSmallIntegerField( _('Order type'), choices=TICKET_ORDER_CHOICES ) . . nip_number = models.CharField( _('NIP'), max_length=10 ) . . class Meta: ordering = ('id',) verbose_name = _('Customer data') verbose_name_plural = _('Customers data') def __str__(self): return self.company_name def clean(self): """Override model clean() method.""" if self.nip_number and not nip.is_valid(self.nip_number): raise ValidationError({'nip_number': _('Incorrect NIP format')}) Later, front-end is all rendered in React, here's part of the code displaying the form: export const PrincipalPartRepairForm = ({ genFieldProps, intl }) => { const _t = intl.formatMessage; const ORDER_TYPES = [ [TICKET_PRIVATE_PERSON, _t(messages.privatePerson)], [TICKET_BUSINESS, _t(messages.company)] ]; return ( <fieldset className="quote-me-form-fieldset-space gr-pad25-row" > <legend className="gr-pad25">{_t(messages.principal)}</legend> <ul className="gr-6 gr-12@tablet-mobile quote-me-form-space@tablet-mobile gr-pad25 clearfix"> <li> <FormChoiceGroup type="radio" values={ORDER_TYPES.map(mapValueArray)} isRequired={true} {...genFieldProps(ORDER_TYPE, 'customerinformation')} /> </li> <li> <RepairFormField label={_t(messages.companyOrName)} component={InputText} type="text" isRequired={true} {...genFieldProps(COMPANY_NAME, 'customerinformation')} /> </li> <li className="gr-6 gr-12@tablet-mobile"> <RepairFormField label={_t(messages.nip_vat)} isRequired={false} component={InputText} type="text" {...genFieldProps(NIP_NUMBER, 'customerinformation')} /> </li> </ul> and it looks like that: I have tried to tweak def clean(self) with something like if (self.order_type … -
Django - Creating a link that maps to multiple different pages?
I'm new to coding and I'm trying to create a link using Django (if possible) that sends the user to three different urls with equal probability of being to redirected to each one. Thus there is only one button to select but it can have three different results. I would like the link to simply be a bootstrap nav bar button. So far I have the following code that works just fine for a single basic html (surprise.html) url that I created: Relevant code in: Views: def surprise(request): return render(request, 'sitepages/surprise.html') Templates: <a class="nav-item nav-link" href="{% url 'surprise' %}">Surprise</a> urls.py: url(r'^surprise/', sitepages.views.surprise, name="surprise"), So this will redirect to a basic internal html page. But I was wondering if it's possible to add another href to the template code? Perhaps a new model would be necessary? I was thinking of using random.choice with three different urls in the list but it seems they need to be in str type and this is beyond me. Any suggestions or tips would be greatly appreciated. Thank You! -
django edit multiple id at once with selecting checkbox
I have items where I can easily edit one by one all working nice but in case I want to edit multiple id's at once via selecting with checkbox I am stuck and can't get it work. Where am I doing wrong ? Here is my codes: fast_edit.html -> I am passing variables via instance to field. <div class="row"> <div class="col-sm-12"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {%csrf_token%} {%for field in instance %} <table class="table"> <tbody> <tr> <td width="100"> {{field.label_tag}} </td> <td> {{field}} </td> </tr> </tbody> </table> {% endfor %} <div class="form-group"> <div class="col-sm-offset-6 col-sm6"> <button type="submit" class="btn btn-primary">Update FP Item</button> </div> </form> </div> </div> </div> </div> forms.py class FastFPForm(forms.ModelForm): class Meta: model = FP fields = ['FP_Item', 'P_1', 'P_2'] widgets = { 'FP_Item': Textarea(attrs={'cols': 50, 'rows': 3}), 'P_1': Textarea(attrs={'cols': 50, 'rows': 1}), 'P_2': Textarea(attrs={'cols': 50, 'rows': 1}), } view.py --> I am sending variables to fast_edit function def items_home(request): pfast_type = request.GET.get("pfast_type") item = request.GET.get("fastedit") ........ elif pfast_type and item: return fast_edit(pfast_type,item) Here is my function: def fast_edit(request,id=None): if not request.user.is_active: return render(request, 'login.html') else: instance=get_object_or_404(FP,id=item) form = FastFPForm(request.POST or None,instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.user_id = request.user.id instance.save() return HttpResponseRedirect(instance.get_absolute_url()) context={ 'FP' : … -
Iam executing the code from building django2 web applications. After changing sqlite db to postgresql iam getting this error.How to get rid of this?
Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "H:\MyMDB\django\config\settings.py", line 16, in <module> from django.db.backends.postgresql_psycopg2.base import ( ImportError: cannot import name 'BaseDatabaseValidation' SETTINGS.py: """ Django settings for config project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from django.db.backends.postgresql_psycopg2.base import ( DatabaseFeatures as BasePGDatabaseFeatures, DatabaseWrapper as BasePGDatabaseWrapper, DatabaseOperations as BasePGDatabaseOperations, DatabaseSchemaEditor as BasePGDatabaseSchemaEditor, DatabaseClient, DatabaseCreation as BasePGDatabaseCreation, DatabaseIntrospection, BaseDatabaseValidation, ) Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ SECURITY WARNING: … -
Nuxt app cannot access one REST API, but all others work
I have a web app with a Django backend and a NuxtJS front end running in docker. The backend uses REST framework JWT Auth to control access. My URLs file looks like this: urlpatterns = [ path('api/auth/login/', obtain_jwt_token), path('api/auth/verify/', verify_jwt_token), # other urls here ] These two methods work perfectly from postman when the docker container is running - I'm able to obtain and verify JWT tokens as expected. However, when the front end calls these methods the login method still works perfectly, but the verify method fails. There are a number of other methods in my app that also work fine when called from the front end. Here is the error i get: Error: connect ECONNREFUSED 127.0.0.1:8000 I find this really weird, as normally this message would imply some sort of CORS issue, but as the other methods work, I don't see how it can be the case here. Here's how I'm calling the login/verify APIs from my front end (in my store.js file). Whenever the user refreshes the page, nuxtServerInit retrieves the token from the browser cookie and attempts to call the verify method to get the user profile in the front end export const actions = { … -
Types and sub types in Django Models
This seems to be fairly simple but the solution doesn't feel intuitive enough to me. Could not find an SO post with this exact question though. I have a School model with a ManyToMany mapping to an Area model which then has a OneToMany mapping to a SubArea model. class School(models.Model): area = models.ManyToManyField(Area, blank=True) sub_area = models.ManyToManyField(Area, blank=True) class Area(models.Model): name = models.CharField(max_length=100, unique=True) class SubArea(models.Model): name = models.CharField(max_length=100, unique=True) area = models.ForeignKey(Area, blank=True) A School object can belong to one or more Areas and a specific SubArea within an Area but doesn't feel quite intuitive to put sub_area in the School model because I feel that it should somehow be coming 'through' the area field, though I could be wrong. Is the above an ideal way to model this? -
How to query the SerializerMethodField in list API view?
I have a PhysicalServerListSerializer, in it I have a server_status serializer method field. class PhysicalServerListSerializer(ModelSerializer): server_status = serializers.SerializerMethodField() class Meta: model = PhysicalServer fields = "__all__" depth = 1 def get_server_status(self, obj): if obj.task and obj.is_finish_task: return 'ok' if obj.task and not obj.is_finish_task: return 'ing' But I have a requirement, when I query it in the get method. http://localhost:8000/api/physicalserver/list/?server_status=ing it can not query out the server_status, how to solve this issue? -
Django Rest Framework related fields
I'm new to Django I want to get profile image from another model topic models.py class UserProfile(models.Model): user = models.OneToOneField(User) file = models.ImageField(upload_to='profile_image', blank=True) def __unicode__(self): return u'%s' % self.user class Topics(models.Model): user = models.ForeignKey(User) title = models.charField(max_length = 55) serializers.py User = get_user_model() class pic(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['file'] class UserInfo(serializers.ModelSerializer): username = pic(read_only=True) class Meta: model = User fields = ['username','first_name',] class TopicSerializer(serializers.ModelSerializer): user= UserInfo(read_only=True) class Meta: model=Topic fields = ('user','title',) I'm getting like this: "user": { "username": {}, "first_name": "" }, "title": "Django the title", Now I need every file field related to Topics field with the first name and email of the user. I want to like this: "user": { "username": "akash", "first_name": "Akash DK" "file":"static/imag.png" }, "title": "Django the title", Thanks in advance -
How to populate Django serializer?
I am new to Django.This is my model and serializer class Sprint(models.Model): name = models.CharField(max_length=100, blank=True, default='') description = models.TextField(blank=True, default='') end = models.DateField(unique=True) def __str__(self): return self.name or _('Sprint ending %s') % self.end And class SprintSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField() class Meta: model = Sprint fields = ('id', 'name', 'description', 'end', 'links', ) When I run code from shell serializer = SprintSerializer(data=('name':'JHolmes','description':'ambassador','end':'2019-01-27T15:17:10.375877')) I got File "<console>", line 1 serializer = SprintSerializer(data=('name':'JHolmes','description':'ambassador','end':'2019-01-27T15:17:10.375877')) ^ SyntaxError: invalid syntax What is the right way to populate serializer? -
Почему не работает ''for'' [on hold]
Подскажите, пожалуйста, почему не работает "for". У меня во views есть: def person_detail(request, person): pers = Abonent.objects.get(osrah=person) balans = pers.oplata_set.aggregate(sum=Sum('saldo')) saldo = pers.oplata_set.values_list('saldo', flat=True).order_by('-idoplata'), date = pers.oplata_set.values_list('from_date', flat=True).order_by('-idoplata'), name = pers.pib adress = pers.adress zip_list = zip( date, saldo) ctx = { 'name': name, 'saldo': saldo, 'adress':adress, 'date': date, 'balans': balans, 'zip_list': zip_list } return render(request, 'abonent/persons.html', ctx ) В persons.html: <table> {% for x, y in zip_list %} <tr> <td style ="border: 1px solid black;text-align: center"> {{x}}</td> <td style ="border: 1px solid black;text-align: center"> {{y}}</td> </tr> {% endfor %} </table> Все работает кроме "for", как если бы его и нету. Выводит в одной ячейке целый list. -
TemplateDoesNotExist at /testapp/athlete/create
I have a template on this path ais/demo/testapp/athlete/acruds/create.html And I think its correct but error is TemplateDoesNotExist at /testapp/athlete/create testapp/athlete/acruds/create.html, acruds/create.html why path is comma separated in error ? and still I am getting this issue My form.py is class AthleteForm(forms.ModelForm): class Meta: model = Athlete fields = '__all__' def __init__(self, *args, **kwargs): super(AthleteForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.layout = Layout( Tab( _('Basic information'), Field('name', wrapper_class="col-md-6"), Field('image', wrapper_class="col-md-6"), ) ) self.helper.layout.append( FormActions( Submit('submit', _('Submit'), css_class='btn btn-primary'), HTML("""{% load i18n %}<a class="btn btn-danger" href="{{ url_delete }}">{% trans 'Delete' %}</a>"""), ) ) My view.py file is class AthleteCRUD(CRUDView): model = Athlete template_name_base = 'acruds' # customer cruds => ccruds namespace = None check_login = True check_perms = True views_available = ['create'] fields = ['name', 'image'] # related_fields = ['invoice'] custom_forms = { 'add_': AthleteForm, # 'update_customer': CustomerForm, # 'add_addresses': AddressesForm, # 'update_addresses': AddressesForm, } modelforms = custom_forms and absolute path of template path is as follow /home/user/Desktop/ais/django-cruds-adminlte/demo/demo/templates/testapp/athlete/acrud/create.html