Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding cloumns to an existing django table witha . postgreSQL db
Ive been searching around for how to do this an di think i broke my table I tried adding dealership = models.ForeignKey('Employee', null=True) To the field to the models.py, since i noticed thats where my other column fields were, and now the entire table is gone. After some more research i saw that its supposed to be added to the migrations location and then run $ python models.py migrations My question is how do i properly add the column, the db already has the information for the column data i cant imagine its that difficult to simply pull that info and how do i get my table back? The table seems to have vanished after i added to the models.py manually and when i tried undoing it just never came back. -
Save object data in list and use in parameter
I need to use the object details of obj to save in a list or some sort to use as a parameter in my send_order_verification() function. def order(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): obj = form obj.save() send_order_verification(order_details, obj.email) This is my send_order_verification() function: def send_order_verification(order_details, email): return send_mail( ('Thank you for your order #{0}', x), ('Name: {0}\nEmail: {1}\nTelephone: {2}', x, y, z), [settings.EMAIL_SEND_TO], ['{0}' % email] ) How could this be done? I tried with order_details = [obj.name, obj.email, obj.telephone] but can't access it with order_details[0] and so forth. -
Django app only works on Debug=True Heroku
I thought I had this solved but I guess not. I've got my Django app on Heroku, and it works perfectly with DEBUG = True but does not work with DEBUG = False. This tells me that I have a problem with my static files, as Django doesn't support static files during DEBUG = False. For that, I'm using Whitenoise. Would someone mind reviewing my settings files to see where I've gone wrong. First my file structure: POTRTMS | +---config | | | urls.py | views.py | wsgi.py | +---settings | | | | | base.py | | local.py | | production.py base.py import os from django.utils import timezone import dj_database_url from decouple import config from .aws.conf import * import django_heroku GOOGLE_MAPS_API_KEY = config('GOOGLE_MAPS_API_KEY') EASY_MAPS_GOOGLE_MAPS_API_KEY = config('GOOGLE_MAPS_API_KEY') BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] print(STATICFILES_DIRS) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Application definition INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn … -
using foreign key set in django models django rest framework
I am having an interesting problem. I am using the foriegn key call in the relations mananger. I.e. if I want all the objects from a related model known as hamsters the call would be hamsters_set now here is a working model attached to a serializer everything is working in this implementation. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True) class Meta: model = SearchCity fields = ('pk','city','searchneighborhood_set') read_only_fields =('pk','city', 'searchneighborhood_set') but with this new model in which I am trying to do the same thing, I am getting an attribute error class Room(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) online = models.BooleanField(default=False) description = models.CharField(max_length=1000, blank=True, null=True) privateroom = models.BooleanField(default=False) semiprivateroom = models.BooleanField(default=False) seatedcapacity = models.CharField(max_length=10, null=True, blank=True) standingcapacity = models.CharField(max_length=10, null=True, blank=True) minimumspend = models.PositiveSmallIntegerField(blank=True, null=True) surroundsoundamenity = models.BooleanField(default=False) outdoorseatingamenity = models.BooleanField(default=False) stageamenity = models.BooleanField(default=False) televisionamenity = models.BooleanField(default=False) screenprojectoramenity = models.BooleanField(default=False) naturallightamenity = models.BooleanField(default=False) wifiamenity = models.BooleanField(default=False) wheelchairaccessibleamenity = models.BooleanField(default=False) cocktailseatingseatingoption = models.BooleanField(default=False) classroomseatingoption = models.BooleanField(default=False) ushapeseatingoption = models.BooleanField(default=False) sixtyroundseatingoption = models.BooleanField(default=False) boardroomseatingoption = models.BooleanField(default=False) theaterseatingoption = models.BooleanField(default=False) hallowsquareseatingoption = models.BooleanField(default=False) class RoomImage(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) order = models.PositiveSmallIntegerField(blank=True, null=True) imageurl = … -
All urls not showing up on django.rest_framework documentation
This is my main urls.py urlpatterns = [ url(r'^', include_docs_urls(title='Foot The Ball API')), url(r'^admin/', admin.site.urls), url(r'^api/v1/aggregator/', include('aggregator.urls')), url(r'^api/v1/bouncer/', include('bouncer.urls')), ] These are the urls in bouncer.urls urlpatterns = [ url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout'), url(r'^register/(?P<location_id>[\w.-]+)/$', RegisterView.as_view(), name='register'), url(r'^location/$', LocationView.as_view(), name='location'), ] I'm using rest_framework.documentation. Strangely only login and logout view show up in the documentation home page. Can someone help as to what's going on here? -
Nginx, Django, and Gunicorn still receiving nginx default page
I am having trouble setting up my webserver to serve up my Django web application. I read this tutorial to help me get started, but alas my server only shows the default nginx "welcome page". My gunicorn_start file looks like this: source /home/ubuntu/blog/my_blog/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec /home/ubuntu/blog/my_blog/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=$SOCKFILE \ --log-level=debug \ --log-file=- My nginx sites-avaliable file looks like this: upstream my_site_server{ server unix:/home/ubuntu/blog/Website/my_site/my_site.sock; } server { listen 80; server_name 13.229.113.194; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/ubuntu/blog/Website/my_site/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://my_site_server; break; } } } GUnicorn does create the my_site.sock file, but nginx seems to be denied when trying to read it. The error being: 2018/03/13 19:50:11 [error] 17713#0: *1 connect() to unix:/home/ubuntu/blog/Website/my_site/my_site.sock failed (111: Connection refused) while connecting to upstream, client: 74.43.49.203, server: goggleheadedhacker.com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/blog/Website/my_site/my_site.sock:/", host: "goggleheadedhacker.com" 2018/03/13 19:50:24 [error] 17713#0: *3 connect() to unix:/home/ubuntu/blog/Website/my_site/my_site.sock failed (111: Connection refused) while connecting to upstream, client: 74.43.51.94, server: goggleheadedhacker.com, … -
Django dynamic/runtime migrations: what's up?
I am aware that it is widly deprecated or documented in way too old posts, but I think I've got good reasons to be willing to update some of my Django models dynamically, and repercut corresponding changes into my PostgreSQL database. TL;DR What's the latest/neatest/most-django2.0-consistency-compliant way to do this? Is it at least possible or documented in any fashion? This approach only allows model creation, not deletions. I have read about django-mutant, is this module out-of-date? Can we dynamically create and resolve individual migrations? In the end, this would mean nothing but using django as a plain (yet nice and powerful) wrapper around psql, right? If I trust this post, people will first try to stop me. For this reason, I'll develop my motivation here: My core models (1) are a set of django-canonical, consistent, append only, archive tables, whose structure is simple, fixed forever and explicitly described as regular django models. No fancy stuff here. Do not panic. These non-fancy, consistent archives (1) actually describe the evolution of.. a database (2). (Thus my need for meta-* stuff.) The latter database (2) is more volatile, its shape and content will change over time. However, every change to it (2) is … -
How do I set up an AngularJS-driven form to work with Django password reset functionality?
I'm working on a web page with AngularJS v1.5.6. This page has other forms. I want to add a "Reset password" form to this page. Ideally, the form might look something like this: <div ng-app="app" ng-controller="Ctrl"> <form method="post" name="resetPWForm" ng-submit="resetPW(resetPW.email)"> <small>{{ resetPW.msg }}</small> <input placeholder="Email" type="email ng-model="resetPW.email"> </form> </div> I'd like resetPW() to go something like this: $scope.resetPW = function(email){ $http.post( {"email":email}, "path/for/resetting/email") }.then(function(response){ if(response.success==false){ $scope.resetPW.msg = "There was a problem. Please try again."; return; } alert("Success! Check your email for a link to finish resetting your password."); }); I've seen this Django password reset for tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html. But I'm unsure how I'd apply it to my situation. My questions is how would I set up urls.py and views.py to handle this? -
Handling duplicates in django models
This is my location object class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) class Meta: unique_together = ('country', 'city') This is the view in which I create a location, class LocationView(views.APIView): def post(self, request): serializer = LocationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now while saving the new location if the database throws duplication error, then I want to not write the new value but fetch the already existent data and return it as a success response message. In sense I want to add another else clause. I'm not sure how to do this in django. Any help appreciated. -
How to save multiple files under in 1 django model
I'm fairly new to Django. I have a model copy, the model copy will contain a student test copy and a mark, usually, i would use a FileField and save the copy to the object, but my problem is that a copy could contain many files (page 1, 2, 3 etc) I was thinking about using a CharField instead that contains the path to a folder that contains the files for that copy, but I don't have a very good idea on how to do that and if you have a better way I would for you to share. here is my model class VersionCopie(models.Model): id_version = models.CharField(db_column='id_Version', primary_key=True, max_length=100) numero_version = models.IntegerField(db_column='numero_Version', blank=True, null=True) note_copie = models.FloatField(db_column='note_Copie', blank=True, null=True) emplacement_copie = models.CharField(db_column='emplacement_Copie', max_length=10000, blank=True, null=True) id_copie = models.ForeignKey('Copie', models.CASCADE, db_column='id_Copie', blank=True, null=True) i just need to know what kind of path i would save to "emplacement_copie" -
pip install mod_wsgi failed. Window server 12, python 3.6.4 64 bit vc++14
I am trying to deploy my django app to a win server12 64bit. The latest apache is installed on the server( from apacheloung distro). build tool is vc15 build tool. Python 3.6.4 64bit. I follow the instruction of https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst But I kept getting the error message like .... src/server\mod_wsgi.c(4417): error C2065: 'wsgi_daemon_process': undeclared identifier src/server\mod_wsgi.c(4417): error C2223: left of '->group' must point to struct/union src/server\mod_wsgi.c(6052): warning C4244: 'return': conversion from '__int64' to 'long', possible loss of data error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe' failed with exit status 2 ---------------------------------------- Command ""d:\program files\python36\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\ccsadmin\AppData\Local\Temp\pip-build-3ktbwpy9\mod-wsgi\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --recor d C:\Users\ccsadmin\AppData\Local\Temp\pip-aw2siwjx-record\install-record.txt -- single-version-externally-managed --compile" failed with error code 1 in C:\Users\ccsadmin\AppData\Local\Temp\pip-build-3ktbwpy9\mod-wsgi\ I have researched online and couldn't find anything similar to my situation. I have compiled successfully on my dev machine(win 10, python 3.64 32 bit) Please advise. -
Why do I get 'this field is required' error in Django models, is there error in my code?
So I am trying to make User form where A user can Upload picture using File-field in models. I am choosing a picture still it says this field is required (after submiting the form) and unloads the pic. models.py: class Incubators(models.Model): # These are our database files for the Incubator Portal incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=100) logo = models.FileField() verify = models.BooleanField(default = False) def get_absolute_url(self): return reverse('main:details', kwargs={'pk': self.pk}) incubator-form.html <form method="post" novalidate> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> I have added the following code in site's main urls.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And added the following to settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have even created media folder in the project directory. I have another class with same FileField which works fine. The problem is only in this class. -
502 Bad Gateway Django/nginx/gunicorn
I have deployed my app but when I try to access the url the browser responses me: 502 Bad Gateway Nginx log: 2018/03/13 19:46:10 [error] 15183#15183: *178 connect() failed (111: Connection refused) while connecting to upstream, client: My IP, server: example.com, request: "GET /favicon.ico HTTP/2.0", upstream: "http://127.0.0.1:8000/favicon.ico", host: "example.com", referrer: "https://example.com/" gunicorn service: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/opt/viomapp_project/viomapp ExecStart=/opt/viomapp_project/bin/gunicorn --access-logfile - --workers 5 - -bind unix:/opt/viomapp_project/viomapp/viomapp.sock viomapp.wsgi:application [Install] WantedBy=multi-user.target gunicorn status active (running) and without errors. nginx status without errors. nginx/sites-available: server { # SSL configuration listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; ssl_certificate /etc/letsencrypt/live/viomapp.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/viomapp.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot root /usr/share/nginx/www; index index.html index.htm; # Make site accessible from http://localhost/ server_name viomapp.com www.viomapp.com; location /static/ { alias /opt/viomapp_project/viomapp/static/; expires 30d; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://127.0.0.1:8000; proxy_pass_header Server; proxy_set_header X-Real-IP $remote_addr; # proxy_set_header X-Scheme $scheme; proxy_connect_timeout 10; proxy_read_timeout 10; # proxy_set_header SCRIPT_NAME /; } } server { if ($host = www.viomapp.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = viomapp.com) { return 301 https://$host$request_uri; … -
How to reinstall requirements.txt
I'm working in this shared Django project, a colleague is the owner of the repo in Github. The problem I am facing right now is that he added raven to his packages and in github the requirements.txt file is updated, however when I tried with git pull, locally, my requirements.txt does not have raven added. He told me that I have to reinstall requirements.txt so I tried with pip freeze > requirements.txt but nothing change. How can I update my requirements.txt file according the updates made from Github? -
django rawsql postgres nested json/jsonb query
I have a jsonb structure on postgres named data where each row (there are around 3 million of them) looks like so: [{"number": 100, "key": "this-is-your-key", "listr": "20 Purple block, THE-CITY, Columbia", "realcode": "LA40", "ainfo": {"city": "THE-CITY", "county": "Columbia", "street": "20 Purple block", "var_1": ""}, "booleanval": true, "min_address": "20 Purple block, THE-CITY, Columbia LA40"}, .....] I would like to query the min_address field the fastest possible way. In Django I tried to use: APModel.objects.filter(data__0__min_address__icontains=search_term) but this takes ages to complete (also, "THE-CITY" is in uppercase, so, I am having to use icontains here. I tried dropping to rawsql like so: cursor.execute("""\ SELECT * FROM "apmodel_ap_model" WHERE ("apmodel_ap_model"."data" #>> array['0', 'min_address']) @> %s \ """,\ [json.dumps([{'min_address': search_term}])]) but this throws me strange errors like: LINE 4: @> '[{"min_address": "some lane"}]' ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. I am wondering what is the fastest way I can query the field min_address by using rawsql cursors. -
Python 3 Timedelta OverflowError
I have a large database that I am loading into an in-memory cache. I have a process that does this iterating through the data day by day. Recently this process has started throwing the following error: OverflowError: date value out of range for the line start_day = start_day - datetime.timedelta(days = 1) This is running in Python 3.4.3 on Ubuntu 14.04.5 Thanks! -
Python Migrate issue while setting up Django site
I am trying to learn Django however when I run python manage.py runserver I get Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/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 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/devopsguy/djangogirls/mysite/settings.py", line 108 TIME_ZONE = "Asia/Calcutta' ^ SyntaxError: EOL while scanning string literal I am new to Django and python so am clueless about what I broke. Any help would be greatly appreciated. -
Is it possible to create view with list of objects and forms to update?
I'm trying to solve my problem with django for last 2 days, I've searched many reddit posts/ git repos / stack questions and I've achieved nothing. I'm learning django and doing a project to help me in my current job. My goal is to make detail view of model "Partner" where I'll list all it's "PartnerMugs" models.py class Partner(models.Model): partner_name = models.CharField(max_length=255) class Meta: ordering = ["partner_name"] def __str__(self): return self.partner_name def get_absolute_url(self): return reverse("partners:detail", kwargs={"pk":self.pk}) class PartnerMug(models.Model): partner = models.ForeignKey('Partner', on_delete=models.CASCADE) pattern = models.ForeignKey('patterns.Pattern', on_delete=models.CASCADE) xs_amount = models.IntegerField(default=0) xl_amount = models.IntegerField(default=0) class Meta: ordering = ["partner"] def __str__(self): return str(self.partner) + " " + str(self.pattern) def get_absolute_url(self): return reverse('partners:detail', args=[self.partner.pk]) The problem is that I have no idea how to put form for each "PartnerMug" object in my list. I tried to do something with inlineformset_factory, but I didn't find the way how to put it in my for loop. form.py class PartnerForm(forms.ModelForm): class Meta: model = Partner fields = ['partner_name'] class MugAmountForm(forms.ModelForm): class Meta: model = PartnerMug fields = ['xs_amount','xl_amount',] MugAmountFormSet = inlineformset_factory(Partner, PartnerMug, form=MugAmountForm, extra=0) For now my Class Based View looks like this(it's based on github repo): view.py class PartnerDetailView(ModelFormMixin, DetailView): model = Partner form_class = … -
Django - update or create obj must be an instance or subtype of type
I have an update or create method in my form valid function and im getting the error, when I submit the form. Im not sure as to why? super(type, obj): obj must be an instance or subtype of type Full trace: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/itapp/itapp/config/views.py" in device_details 151. form = DeviceSubnetForm(request.POST) File "/itapp/itapp/config/forms.py" in __init__ 135. super(DeviceSubnet, self).__init__(*args, **kwargs) Exception Type: TypeError at /config/device_details/2/7 Exception Value: super(type, obj): obj must be an instance or subtype of type This is the function within the view if request.method == 'GET': form = DeviceSubnetForm() else: # A POST request: Handle Form Upload form = DeviceSubnetForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): subnet_data = form.save(commit=False) obj, record = DeviceSubnet.objects.update_or_create( defaults={ 'subnet' : subnet_data.subnet, 'subnet_mask' : subnet_data.subnet_mask, 'subnet_type' : SubnetTypes.objects.get(subnet_data.subnet_type) }, subnet=subnet_data.subnet, subnet_mask=subnet_data.subnet_mask, subnet_type=SubnetTypes.objects.get(subnet_data.subnet_type) ) print(obj.id) return 'Valid' -
Filling form with csv file data Django
What I am trying to do is filling Django form with data coming from CSV file. Idea is to let user choose whether he wants to fill a form by himself or do this by uploading data from csv file. I have been looking for a tip on stackoverflow for some time already and haven't found anything else then saving data to django-models and retrieve them later on. I don't want to save the file anywhere neither. I don't want to use django models to save the data and then upload them into a form and I was wondering - is there any way to accomplish such? Simple code to explain this a bit more: #template.html <form action="/generate/" method="post"> First name: {{ form.first_name }}<br> Last name: {{ form.last_name }}<br> <input type="submit" value="Submit" /> </form> <form method="POST" action="/upload" enctype="multipart/form-data"> <div class="form-group"> <label for="inputFile">File input</label> <input type="file" name="inputFile"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> I would like to 2nd form reads the file and somehow fill with data the upper one on the same page / template to allow further validating and actions under this view. Does anyone have any ideas ? -
Filtering in ManytoManyField
How to make a choice only from users who are in the group created in the admin panel? owner = models.ManyToManyField(User, verbose_name = 'Исполнитель') -
Django customize ForeignKey way of instances returnment
I have a need to create custom field, that is very similar to a ForeignKey field but has specific logic. Two main tasks are: Each related model of this CustomForeignKey has regular ForeignKey field to the model itself and my purpose is to return one of this instances depending on some parameter (date for example). Maybe it would be more clear with some example: class Author(models.Model): name = models.CharField(max_length = 30) surname = models.CharField(max_length = 60) publication = CustomForeignKey(Publication) class Publication(models.Model): title = models.CharField(max_length = 50) text = models.TextField() date = models.DateTimeField() source = models.ForeigKey('self', related_name='references') I want calls to SomeAuthor.publication be performed like SomePublication.references.order_by('date').first(). Real goal is more difficult, but the sense is nearly the same. Second thing is about lookups. When I filter objects by this CustomForeignKey, I would like to have same logic as in previous point. So Author.objects.filter(publication__title = 'Some Title') should make filtering by the fist object ordered by date from references related manager. I read the documentation about creating custom fields in django, but there are no good examples about custom relational fields. In django.db.models.fields.related as well, I didn't find which methods should I redefine to achieve my goal. There are to_python and from_db_value, … -
ChoiceBlock consisting of other Wagtail blocks?
I'm trying to construct the carousel model: class Carousel(blocks.StructBlock): heading = blocks.CharBlock(required=False) carousel = blocks.ListBlock( blocks.StructBlock([ ('slide', blocks.StreamBlock([ ('image', ImageChooserBlock()), ('video', EmbedBlock())]), ), ('description', blocks.RichTextBlock()), ]) ) Every slide consists of one image or video and a description. I'm using StreamBlock in here because I couldn't find any other more suitable structural block type which would allow to the user to choose between image and video. Ideally I need something similar to the ChoiceBlock, except that the choices argument should expect other block types. Is that feasible? Or at least is there a way to limit how many sub-blocks might be inserted from within the StreamBlock? -
Best practice to divide a django project into applications
I want to know how to divide a project having a hierarchical structure into applications. Let's say that I'm trying to build up something like github.com for example. In github.com, an account has some repositories, which have some features like code, issues or pull requests. And those features have references to other features. In this case, which is an application and which is not? At that time, should I put applications in the root directory or in an application directory as sub-applications? -
celery tasks: update state after try & except block
I have celery 4.1.0, django 1.11.11, rabbitMQ and Redis for results. @shared_task(bind=True) def one_task(self): try: ... some db stuff here ... except BaseException as error: self.update_state(state='FAILURE', meta={'notes': 'some notes'}) logger.error('Error Message ', exc_info=True, extra={'error': error}) So, when my code runs into except block self.update_state does not work but logger works... Actually, I'm not sure if @shared_task(bin=True) it's right... What I want to do it's catch exceptions(through try & except blocks) of my python code, change states and terminate the tasks manually. So, any advise/help?