Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Conflicting 'basket_vouchers' models in application 'basket'
I'm new to Oscar and tried finding the answer to my problem in the forum. I think this has been partially covered before, but I can't seem to find an answer for this particular case. (Versions: Django==1.9.12, django-oscar==1.3) I've forked the 'basket' app (into 'myoscar.basket') per the Oscar docs at http://django-oscar.readthedocs.io/en/releases-1.3/topics/fork_app.html However, when I create my class (see below) and try running the server I get this error (see below). I would greatly appreciate any help or guidance here. RuntimeError: Conflicting 'basket_vouchers' models in application 'basket': <class 'oscar.apps.basket.models.Basket_vouchers'> and <class 'myoscar.basket.models.Basket_vouchers'>. Here is my models.py: from oscar.apps.basket.models import AbstractBasket class Basket(AbstractBasket): def add_product(self, product, quantity=1, options=None): ###################### # Do some stuff # ###################### return line, created from oscar.apps.basket.models import * # noqa -
AND-condition in when-clause of Django's case
Basically, the question is what Django's syntax is for something like: Case (when ( A=1 And B=1), then 1....) -
Open the Django project on git in Visual Studio 2015
I have a Django project on git repository. I would like to open this project with Visual Studio 2015 and continue. There is no "Python" option list of project types in the Create Project from Existing Code Files Wizard window. What should I do to have the python option listed? Or How to open this project? -
Is there any way to create real-time database with django
I am creating an mobile app for both Android and IOS, I am using Django Rest Framework. I am using nginx and gunicorn on the server side. My project database is postgresql. I know little about Django DDP and SwampDragon libraries. However I really don't know are these libraries create realtime database with Django Rest Framework usage or is there any way to create a realtime database using another library? If so, can anybody explain me step by step how can I use these libraries because their documentation is not good enough and I could not find a good tutorial. -
Django shell ORA-00904
I have a legacy database from oracle that has fields. If I run Orders.objects.count() I get the correct amount. When I run Orders.object.all() I get this error but haven't found a solution online. class Orders(models.Model): account_obj_db = models.BigIntegerField(blank=True, null=True) account_obj_id0 = models.BigIntegerField(blank=True, null=True) account_obj_type = models.CharField(max_length=1020, blank=True, null=True) account_obj_rev = models.BigIntegerField(blank=True, null=True) order_payload_buf_size = models.BigIntegerField(blank=True, null=True) total_entitlement_count = models.BigIntegerField(blank=True, null=True) currency_code = models.BigIntegerField(blank=True, null=True) >>> from home.models import Orders >>> Orders.objects.all() Traceback (most recent call last): File "/home/user/dev2/lib/python3.5/site- packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/user/dev2/lib/python3.5/site- packages/django/db/backends/oracle/base.py", line 481, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-00904: "ORDERS"."ID": invalid identifier -
Django and Apache2 not serving
I can't get my website to be served for the life of me. I've tried nearly everything I can find. I'm running Ubuntu 16.04. Here is the modified block of apache2.conf: # Sets the default security model of the Apache2 HTTPD server. It does # not allow access to the root filesystem outside of /usr/share and /var/www. # The former is used by web applications packaged in Debian, # the latter may be used for local directories served by the web server. If # your system is serving content from a sub-directory in /srv you must allow # access here, or in any related virtual host. <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> #<Directory /srv/> # Options Indexes FollowSymLinks # AllowOverride None # Require all granted #</Directory> WSGIPythonPath /home/ubuntu/myproject:/home/ubuntu/myproject/myprojectenv/lib/python3.4/site-packages Alias /static /home/ubuntu/myproject/static Alias /media /home/ubuntu/myproject/media <Directory /home/ubuntu/myproject/static> Require all granted </Directory> <Directory /home/ubuntu/myproject/media> Require all granted </Directory> WSGIScriptAlias / /home/ubuntu/myproject/myproject/wsgi.py <Directory /home/ubuntu/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/ubuntu/myproject:/home/ubuntu/myproject/myprojectenv/lib/python3.4/site-packages WSGIProcessGroup myproject -
Python doesn't pick up django or tweepy
I'm running linux mint and trying to use tweepy and django but I'm getting errors. I am pretty sure Django used to work on my machine but I'm not sure what changed. I've got Python 3 installed on my machine as well. I've got a python directory in usr/local/bin, and then another in usr/local/lib, which contains a python 2.7, python 3.4, python 3.5 directory. The python 2.7 in the /lib directory doesn't seem to have a python.exe, but a bunch of modules and files. In the dist-packages here, tweepy is in this directory along with django and their associated files. I dont know what to do to get this to work.. here is my error: >>> import sys >>> print(sys.path) ['', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages'] >>> quit() kenny@kenny-Surface-Pro-3 /usr/local/lib/python2.7/dist-packages $ python Python 2.7.12 (default, Sep 18 2016, 23:40:58) [GCC 4.9.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tweepy Traceback (most recent call last): File "<stdin>", line 1, in <module> File "tweepy/__init__.py", line 14, in <module> from tweepy.api import API File "tweepy/api.py", line 12, in <module> from tweepy.binder import bind_api File "tweepy/binder.py", line 11, in <module> import requests File "requests/__init__.py", line 60, … -
Django oscar Failed lookup for key [basket] in <WSGIRequest GET >
I am new to django-oscar and this is the first time I tried launching a website with it. I am facing the following stack trace when trying to load a webpage (localhost:8000). I tried to search a lot on the internet but I couldn't find any solution. Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.9 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'compressor', 'widget_tweaks', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.promotions', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.promotions', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2'] Installed Middleware:<br> ['django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware'] Template error: In template /Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/oscar/templates/oscar/promotions/home.html, error at line 0 Failed lookup for key [%s] in %r 1 : {% extends "layout_2_col.html" %} 2 : {% load i18n %} 3 : 4 : {% block navigation %} 5 : {% include "partials/nav_primary.html" with expand_dropdown=1 %} 6 : {% endblock %} 7 : 8 : {% block header %}{% endblock %} 9 : 10 : {% block column_left %} Traceback: File "/Users/rohit.rawat/.virtualenvs/env/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup 879. current = current[bit] During handling of the above exception ('WSGIRequest' object is not subscriptable), another exception … -
How to Initialize a django form with values from a model
I am making a shopping website, I am trying to initialize my products update form with the product information but I cant get the information from the model into the form. models function def get_product_details(product_id): product_details = Products.objects.filter(name=rproduct_id).select_related('name', 'description','price','qty') return product_details form.py class UpdateProductForm(forms.Form): name = forms.CharField( max_length=200, required=True, label="* name:", widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}), ) description = forms.CharField( max_length=200, required=True, label="* description:", widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}), ) price = forms.IntegerField( label="* price:", widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}), ) qty = forms.IntegerField( label="* Qty:", widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}), ) view.py def update_risk(request,product_id): product_details = get_product_details(product_id) name = form.cleaned_data['name'] description = form.cleaned_data['description'] price = form.cleaned_data['price'] qty = form.cleaned_data['qty'] form = UpdateProductForm(product_details) return render( request, template_name = 'products/forms/update_product_form.html', dictionary = { 'form':form, 'instr_text':instr_text } ) update form <form method="POST" action="{% url 'products:update'%}"> {% csrf_token %} {{ form.name }} {{ form.description }} {{ form.price }} {{ form.qty }} </form> -
django makemessage DjangoUnicodeDecodeError
I'm using django translation, and I have an error when i try to make ./manage.py makemessages --locale es This is the error: DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xbc in position 32: invalid start byte. You passed in '<HTML>\n<HEAD> \n\t<TITLE> meta \xbc\xd0\xc5\xd2\xaa\xba\xa8\xcf\xa5\xce\xa1G\xa4\xa4\xa4\xe5\xba\xf4\xad\xb6 </TITLE>\n\t<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=big5">\n</HEAD>\n<BODY>\n\n\xb3o\xacO\xa4@\xad\xd3\xc1c\xc5\xe9\xa4\xa4\xa4\xe5\xba\xf4\xad\xb6\xa1I<br>\n(This page uses big5 character set.)<br>\ncharset=big5\n\n</BODY>\n</HTML>' (<type 'str'>) someones have a idea? -
Django custom Model.Fields
I am trying to create a Model Fields that is basically a AutoField, but in base 36. Here my definition: class AutoBase36Field(models.AutoField): description = _("AutoField on base36") @staticmethod def base36encode(number): try: number = int(number) except: raise TypeError('number must be an integer') if not isinstance(number, int): raise TypeError('number must be an integer') if number < 0: raise ValueError('number must be positive') alphabet, base36 = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ''] while number: number, i = divmod(number, 36) base36 = alphabet[i] + base36 return base36 or alphabet[0] @staticmethod def base36decode(string): if string is None: return None return int(string, 36) def to_python(self, value): if value is None: return value try: return self.base36encode(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) def from_db_value(self, value, expression, connection, context): if value is None: return value return self.base36encode(value) def get_prep_value(self, value): if value is None: return None return self.base36decode(value) And here is a Model class I am using: class Content(models.Model): mzk_id = AutoBase36Field(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') name = models.TextField() I have a test failing: def test_incrementation_of_content_mzk_id(self): content1 = Content(name="a") content1.save() mzk_id_1 = int(content1.mzk_id, 36) As mzk_id is kept as an integer. Basically when creating the incremented field, Django doesn't go through to_python()... I am not sure why... Does anyone … -
Insert CSV file into SQL Server (not import!)
I would like to store CSV files in SQL Server. I've created a table with column "myDoc" as varbinary(max). I generate the CSV's on a server using Python/Django. I would like to insert the actual CSV (not the path) as a BLOB object so that I can later retrieve the actual CSV file. How do I do this? I haven't been able to make much headway with this documentation, as if mostly refers to .jpg's https://msdn.microsoft.com/en-us/library/a1904w6t(VS.80).aspx -
SMTPSenderRefused at /accounts/register/ ERROR
The exact error is : SMTPSenderRefused at /accounts/register/ (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError') settings.py """ Django settings for bookstore_project project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ 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__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-e#&s_h13286vuond2r&!1d79ne!hji0-^!x4tommre5@j*d=-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'store', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', '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 = 'bookstore_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'bookstore_project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/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.10/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', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', … -
django timeseries postgres beginner
I'm writing small application in django in order to learn databases and web etc. The application should display players data and record statistics over time. To answer questions such as: How many random battles palyer has played in last month/week/day? - graph What players left/entered clan? - etc. I've been searching and reading and I found these suggestions: MongoDB, InfluxDB, PostgreSQL, RedisDB, or from packages django-timeseries, django-reversion. I did not find my approach to be good and I probably, can anybody suggest me which database to use and how models should look like then a bit? Data is being downloaded from 3rd party API as jsons. Structures which are downloaded: Player.json { "501435906": { # this is PlayerID "last_battle_time": 1484160229, "statistics": { "all": { "battles": 70555 }, "random": { "battles": 67361 } } }, # then next players continue } clan.json { "500004323": { # clan ID "members": [ { "account_id": 501435906, # PlayerID same as in Player.json "account_name": "Player1", "joined_at": 1447589992, "role": "private", "role_i18n": "Private" },] "name": "Full Clan Name", "tag": "TAG", } stronghold.json { "500323931": { # PlayerID "stronghold_skirmish": null, "total_resources_earned": 0, "week_resources_earned": 0 }, # next player follows } My approach: Merge data together { "500004323": { … -
Django Polymoprhic
I want to implement models using inheritance and I've found this package django-polymorphic. But I was reading about inheritance in django models and almost on every page I found they recommend using abstract = True in parent model. Which will duplicate fields for subclasses, resultsing in making queries faster. I've done some testing and found out that this library doesn't use use abstract varaible: class Parent(PolymorphicModel): parent_field = models.TextField() class Child(Parent): child_field = models.TextField() This results in: Parent table: | app_parent| CREATE TABLE `app_parent` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_field` longtext NOT NULL, `polymorphic_ctype_id` int(11), PRIMARY KEY (`id`), KEY `app_polymorphic_ctype_id_a7b8d4c7_fk_django_content_type_id` (`polymorphic_ctype_id`), CONSTRAINT `app_polymorphic_ctype_id_a7b8d4c7_fk_django_content_type_id` FOREIGN KEY (`polymorphic_ctype_id`) REFERENCES `django_content_type` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | Child table: | app_child | CREATE TABLE `app_child` ( `parent_ptr_id` int(11) NOT NULL, `child_field` varchar(20) NOT NULL, PRIMARY KEY (`parent_ptr_id`), CONSTRAINT `no_parent_ptr_id_079ccc0e_fk_app_parent_id` FOREIGN KEY (`parent_ptr_id`) REFERENCES `app_arent` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | Should I use my own classes which uses abstract field or should i stick with this? -
How to save part of URL in Django?
I want to save part of a URL in the save method for example : I have this link from youtube: www.youtube.com/watch?v=wMXHHuEGuO8 but i just want to save this part : wMXHHuEGuO8 how can i do that in Django? -
How to handle infrequently changed business parameters
I'm new to business programming, so forgive me if this is a naive question. How should one handle (in a Django project) business parameters which are not quite constant strings, such as the business's bank account number, or a string of government-dictated boilerplate which must appear on certain commercial invoices). There are about twenty of these things I've identified so far. I'm thinking of a database table BusinessParameters containing a key (e.g. "bank_account_number"), a value, the creation date, and of course an auto id. When (say) an invoice object is generated, should one copy the current value of these strings into the invoice object (which will result in lots of duplicated data, though not enough to seriously cost on a modern computer), or should one use a ForeignKey relation with no reverse relation (related_name='+') and models.PROTECT? In the latter case it is vital that rows in this table cannot ever be updated, so that an invoice object will always reflect what the customer who it was sent to actually saw at that time. The following (test) code seems to accomplish this: class BusinessParameters( models.Model): # test an unmodifiable row key = models.CharField( max_length=40) value = models.CharField( max_length=400) date = models.DateField( … -
Django Views Get POST Data
I have a hidden form in the Dajngo (1.10) template and would like to pass data to views.py. I followed the usual way however the result of getting data is nothing. Could you advise what has gone wrong and how to fix it? Many thanks. The code is as below for reference: template: <form style="display: hidden" action="/exRpt/" method="POST" id="#form99"> {% csrf_token %} <input type="hidden" id="var199" name="var199" value=""/> <input type="hidden" id="var299" name="var299" value=""/> </form> <script> $(document).on('click', '.exWord', function(){ $("#var199").val("ExWord"); $("#var299").val("1,4,10"); $("#form99").submit(); window.location.href = "/exRpt/" }); </script> views.py: def exRpt(request): in_type = request.POST.get('var199') in_news = request.POST.get('var299') ... response = HttpResponse(f.getvalue(), content_type='application/vnd.ms-word') response['Content-Disposition'] = 'attachment; filename=SelectedNewsReport.docx' return response -
Changing the background-color of a jumbotron from bootstrap in django
I am very new to web development and Django. I am following a tutorial called "Try Django 1.8". In this code I am supposed to change the background-color of jumbotron to #155A1E. If I press shift + refresh in google chrome, the color shows up then it changes back to gray. When I inspect the code in google chrome, I can see in the styles tab that the background-color in the .jumbotron{} has a strike-through. Also there is another verion of .jumbotron{} in the styles tab that has a background-color and has a check. If I uncheck the box, the color gets fixed. How can I fix this in Django? {% extends "base.html" %} {% load crispy_forms_tags %} {% block head_title %}Welcome | {{ block.super}}{% endblock %} <style> {% block style %} .jumbotron { background-color: #155A1E; } {% endblock %} </style> {% block jumbotron %} <div class="jumbotron"> <div class='container'> <div class="row"> <div class='col-sm-6'> <h1>Try Django 1.8</h1> <p>Some text here!!! This text should be long so that we can test the columns in the webpage. So here we go. We are trying to make this line as long as possible.</p> <p> <a class="btn btn-lg btn-primary" href="" role="button">Join us &raquo;</a> </p> </div> … -
django loading an html page into a tab using ajax after a for loop in the template
im working on a nav where my main page load a series of tabs based on the beneficio objects, using a for loop, the problem is that after de for loop only show the last register (Sobreviviente) in the tab, and the rest of data will no show someone say i need use ajax but i can't make it work some one can help me please my model class Beneficio(models.Model): autor = models.ForeignKey('auth.User') OP_DEP = ( ('Afiliacion', 'Afiliacion'), ('Bienestar y Seguridad Social', 'Bienestar y Seguridad Social'), ('Beneficios del Trabajador', 'Beneficios del Trabajador'), ('Créditos', 'Créditos'), ('SISA', 'SISA'), ('Inversora', 'Inversora'), ) dependencia = models.CharField( max_length=100, choices=OP_DEP, default='AA' ) beneficio = models.CharField(max_length=100, unique=True) texto = HTMLField('Texto') fecha_creacion = models.DateTimeField(default=timezone.now) fecha_publicacion = models.DateTimeField(blank=True, null=True) def __str__(self): return self.dependencia my view def bafiliacion(request): afi = Beneficio.objects.filter( fecha_publicacion__lte=timezone.now()) return render(request, 'noticias/beneafiliacion.html', {'afi': afi}) def detalle3(request, pk): bene = get_object_or_404(Beneficio, pk=pk) return render(request, 'noticias/detalle3.html', {'bene': bene}) my template <div class="Beneficios"> <div class="container-fluid"> <div class="col-md-4"> <ul class="nav nav-tabs tabs-left"> {% for item in afi %} <li><a href="#{{item.beneficio}}" data-toggle="tab"> {{item.beneficio}}</a></li> {% endfor %} </ul> </div> <div class="col-md-8"> <div class="tab-content"> {% for item in afi %} <div class="tab-pane" id="{{item.beneficio}}">{{item.texto|safe}}</div> {% endfor %} </div> </div> i also try this and doesn't … -
Postgres Server Error 500
I'm using django 1.9,gunicorn,nginx and postgres as database for my website. My site is up and running but when i try to login as admin or user i get server error 500 on webpage and on terminal i get "is the server running on host 139.62.45.246 and accepting tcp/ip connections on port 5432". I thought there might be a problem in postgres.conf and pg_hba.conf. But there are 2 host all all....one for IPv4 and one for IPv6 in pg_hba.conf. I can't figure out how to edit pg_hba.conf. Please use above's IP to explain. One more thing will it solve the problem or i might need to do something else? -
How to get a name of the class from class declaration
I have a next model class MyClass(models.Model): # fields When I try to get __class__ it returns 'ModelBase'. What I actually need is to find a method of how to get a class name for models.MyClass. Is it possible without having an instance of it? -
Django modelformset_factory - initial data change in between POST
I am setting up a formset by doing the following: ``` section_qs = book.section_set.all().order_by('position') existing_positions = section_qs.values_list('position', flat=True) initial = [] num_fields = 10 for position in range(num_fields): if not position in existing_positions: initial.append({ 'book': book, 'position': position}) SectionFormSet = modelformset_factory(models.Section, form=forms.SectionForm, extra=len(initial)) formset = SectionFormSet(request.POST or None, queryset=section_qs, initial=initial) ``` I was wondering how to deal with the following scenario: Person A is opening the page with the formset and starts editing section at position 1 - not saving the formset at this point. Person B is opening the same page - the formset gets initiated the same way as in 1. Person B is also editing the section at position 1 and saves the formset. Person A is finally saving the formset - but now the initialisation of SectionFormSet has changed due to the fact that section_qs loads the Section from 2. The POST data (outdated in regards to position) gets now saved with another section at position 1. I am now wondering if I do anything wrong in regards to initialising the formset? If not then the only way I can see to avoid this problem is by validating each section inside SectionForm and making sure that … -
Django save multiple modelforms in view
I am probably missing something very obvious here, but can't get this to work. I have 2 models (Organization and Address), 2 forms (One for each model) and 1 view where I want to save the Organization with the Address as the child. Models: class Address(models.Model): address = models.CharField(max_length=255, verbose_name=_("Address")) postal_code = models.CharField(max_length=20, verbose_name=_("Postal_code")) city = models.CharField(max_length=255, verbose_name=_("City")) class Organization(models.Model): name = models.CharField(max_length=100, verbose_name=_("Name")) address = models.OneToOneField(Address, on_delete=models.CASCADE, verbose_name=_("Address")) owner = models.ForeignKey("users.User", related_name="organizations", verbose_name=_("Owner")) Forms: class AddressForm(forms.ModelForm): class Meta: model = Address fields = ["address", "postal_code", "city"] def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.disable_csrf = True class OrganizationForm(forms.ModelForm): class Meta: model = Organization fields = ["name", ] def __init__(self, *args, **kwargs): super(OrganizationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.disable_csrf = True And finally the view class OrganizationCreateView(LoginRequiredMixin, TemplateView): template_name = "organizations/organization_form.html" def get_organization_form(self, data=None): return OrganizationForm(data) def get_address_form(self, data=None): return AddressForm(data) def get(self, request, *args, **kwargs): ctx = self.get_context_data(organization_form=OrganizationForm(), address_form=AddressForm()) return self.render_to_response(ctx) def post(self, request, *args, **kwargs): organization_form = self.get_organization_form(data=request.POST) address_form = self.get_address_form(data=request.POST) if organization_form.is_valid() and address_form.is_valid(): return self.forms_valid(organization_form, address_form) return self.forms_invalid(organization_form, address_form) def forms_valid(self, organization_form, address_form): address = address_form address.country = "DE" address.save() organization = organization_form organization.save(commit=False) organization.owner = self.request.user … -
PyCharm docker debugging error
I'm trying to get the latest version of PyCharm to successfully debug Django running inside Docker. However I'm having trouble setting up the remote python interpreter and I get an error as soon as I try to start the debugger. Can't run remote python interpreter: com.github.dockerjava.api.exception.InternalServerErrorException: {"message":"the working directory 'C:/Program Files (x86)/JetBrains/PyCharm 171.2613.10/jre64/jre/bin' is invalid, it needs to be an absolute path"} The path, in my eyes looks pretty absolute, so I'm guessing its something else. I'm not even sure who or what is causing the error. The docker container (because of the JSON response) or PyCharm. Running PyCharm 2017.1 Docker for Windows (docker version 1.13.0) Any thought of what I might be missing/having problem with?