Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upgrading Python in Django cartridge in Openshift to install Quantlib-Python
I am using the Django cartridge in Openshift. This cartridge has Python version 3.3.2. Is there a way to upgrade the python to 3.6? I am trying pip install QuantLib-Python in ssh console. It gives me the following error: Collecting QuantLib-Python Could not find a version that satisfies the requirement QuantLib-Python (from versions: ) No matching distribution found for QuantLib-Python. I did the same install in my Windows machine which has a Python version 3.6. Hence I feel that I will be able to my pip install if I upgrade the python. I would appreciate any suggestion. Thanks. -
Did you forget to register or load this tag in django
I tried to insert image of wine in wine_list .html and I get this error that Invalid block tag on line 21: 'static'reviews\images\download(1).jpg'', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Here is the code for wine_list {% extends 'base.html' %} {% block title %} <h2>Wine list</h2> {% endblock %} {% block content %} {% if wine_list %} {% load static %} <div> {% for wine in wine_list %} <div> <h4><a href="{% url 'reviews:wine_detail' wine.id %}"> {{ wine.name }} { <div class="w-col w-col-3 download"> <a href="#"><img class="img-rounded" src="{% static'reviews\images\download(1).jpg'%}" alt="CEe"></a> </div> } </a></h4> <h5>{{ wine.review_set.count }} reviews</h5> <h5> average rating</h5> </div> {% endfor %} </div> {% else %} <p>No wines are available.</p> {% endif %} {% endblock %} here is also the code for views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .models import Review, Wine from .forms import ReviewForm import datetime from django.contrib.auth.decorators import login_required def review_list(request): latest_review_list = Review.objects.order_by('-pub_date')[:9] context = {'latest_review_list': latest_review_list} return render(request, 'reviews/review_list.html', context) def review_detail(request, review_id): review = get_object_or_404(Review, pk=review_id) return render(request, 'reviews/review_detail.html', {'review': review}) def wine_list(request): wine_list = Wine.objects.order_by('-name') context = {'wine_list': wine_list} return render(request, 'reviews/wine_list.html', context) def wine_detail(request, wine_id): wine β¦ -
Editing django database on same page without moving to other view function
I have a details page that displays the details of the parts and has option for adding stock of that part and list of stock that has already been added def part_details(request,pk): temp =check_session_exist(request) if temp != True: return HttpResponseRedirect(temp) my_list=populate_nav_bar() //displaying navigation bar temp_list = models.part_list.objects.get(part_id=pk) // get stock information if request.method == 'POST': //adding stock of the current part form_entered=forms.part_stock_form(request.POST) if form_entered.is_valid(): temp = models.part_stock() temp.part_id = models.part_list.objects.get(pk=pk) temp.entry_date = form_entered.cleaned_data['entry_date'] temp.supplier = form_entered.cleaned_data['supplier'] temp.amount = form_entered.cleaned_data['amount'] temp.save() return HttpResponseRedirect(reverse('parts:part_details',args=[pk])) else: print("invalid field") return render(request, 'part_details.html', {'part_temp': temp, 'my_list': my_list, 'part_stock_form': form_entered}) return render(request,'part_details.html', {'part_temp':temp_list,'my_list':my_list,'part_stock_form': forms.part_stock_form}) now I want o to edit the stock from the same page where do I put the function for this. can't I just call the function for it without redirecting it to other view and redirecting back to the same view. does javascript provide a function for adding/editing database? -
Send button with certain features
Javascript $(function(){ $('.select-another-button').each(function(){ $(this).bind('click', function(e) { $(this).attr('disabled','true'); //disables the button $('#overlay').show(); //after disabling show the overlay for hover setTimeout(function(){ $(this).attr('disabled','false'); //enables after 5mins $('#overlay').hide(); //hide the overlay }, 300000); e.preventDefault(); fileBrowser(this); return false; }); }); }); $("#overlay").hover(function(){ $('#message').show(); },function(){ $('#message').hide(); }); CSS .title-actions { float: right; height: 50px; margin-top: 13px; } .title-actions a { transition: background 0.3s ease; } .title-actions a.btn { padding: 2px 14px; line-height: 26px; max-height: 28px; position: relative; top: -1px; margin-left: 8px; } .title-actions a:hover { background: #4382b5; } .title-actions span { color: #444; background: #e6e6e6; padding: 6px 10px; border-radius: 3px; float: none; position: relative; margin-left: 6px; } .title-actions .btn { padding: 2px 14px; line-height: 26px; max-height: 28px; position: relative; top: -1px; margin-left: 8px; } .title-actions .btn-icon { background: transparent; position: relative;il color: #3e5366; text-align: center; display: inline-block; padding: 0 !important; transition: color 0.3s ease; box-shadow: none !important; margin-top: -16px; margin-left: 6px; } .title-actions .btn-icon i { font-size: 35px; line-height: 20px; position: relative; top: 12px; } .title-actions .btn-icon:hover { color: #4382b5; background: transparent; } .title-actions .badge .material-icons { font-size: 1.2em; line-height: 0; position: relative; top: 4px; } .wrapper { display: inline-block; } HTML <div class="wrapper"> <div id="overlay"></div> <a href="#" title="{% trans "Send email - rejected file(s)" %}" β¦ -
issue cycling through forms with different names in django views
I am working on a project and i am having an issue with djago form templates and it only returning one part of the form. So what is happening is: I have a ModelForm that contains two fields which are amount and description. Within the view I cycle through a list of users. for every user in the loop it creates a form with the users username prefix and then passes the list of forms into the html template. The issue that i am having is that all of the forms and their prefixes are passing to the html tempalte, but when it is submitted, only the last form is passed back to be proccessed. I have an example below and the file info that is related to this issue. Here are the passed in forms that were created in the view before html template is displayed: omarform <tr><th><label for="id_omar-amount">Amount:</label></th><td><input id="id_omar-amount" name="omar-amount" step="0.01" type="number" value="0.0" /></td></tr> <tr><th><label for="id_omar-description">Description:</label></th><td><input id="id_omar-description" maxlength="250" name="omar-description" type="text" /></td></tr> haniform <tr><th><label for="id_hani-amount">Amount:</label></th><td><input id="id_hani-amount" name="hani-amount" step="0.01" type="number" value="0.0" /></td></tr> <tr><th><label for="id_hani-description">Description:</label></th><td><input id="id_hani-description" maxlength="250" name="hani-description" type="text" /></td></tr> ranaform <tr><th><label for="id_rana-amount">Amount:</label></th><td><input id="id_rana-amount" name="rana-amount" step="0.01" type="number" value="0.0" /></td></tr> <tr><th><label for="id_rana-description">Description:</label></th><td><input id="id_rana-description" maxlength="250" name="rana-description" type="text" /></td></tr> Here is what is displayed β¦ -
Dockerized Angular 4 and Django is compiled successfully but localhost:4200 is not working
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. At this moment my files looks as shown below. I am note sure if this is done properly? When I try docker-compose up I get information that both frontend with Angular 4 and backend with Django started successfully. Unfortunately when I open http://localhost:4200 it doesn't work (localhost:8001 seems working): Safari can't open the page because the server unexpectedly dropped the connection My logs: django_1 | Django version 1.11, using settings 'project.settings' django_1 | Starting development server at http://0.0.0.0:8001/ django_1 | Quit the server with CONTROL-C. angular_1 | ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 ** angular_1 | Time: 20657ms angular_1 | chunk {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 232 kB {4} [initial] [rendered] angular_1 | chunk {1} main.bundle.js, main.bundle.js.map (main) 222 kB {3} [initial] [rendered] angular_1 | chunk {2} styles.bundle.js, styles.bundle.js.map (styles) 11.6 kB {4} [initial] [rendered] angular_1 | chunk {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 4.41 MB [initial] [rendered] angular_1 | chunk {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered] angular_1 | webpack: Compiled successfully. Structure of my files: βββ Backend β βββ AI β β βββ __init__.py β β βββ __pycache__ β¦ -
Django Model self referencing M2M field
I'm trying to get a Django model to automatically construct a typical __str__(self) value for itself (in the model definition), but based on 3 ManyToMany Fields. Unlike when using basic field types (as in the first two models), this doesn't appear to work for M2M fields (see the third model). The model migrates fine, but causes errors when being referenced in the admin. Any help much appreciated, thanks! class Party(models.Model): name=models.CharField("Party", max_length=150) def __str__(self): # __unicode__ on Python 2 return self.name class Meta: ordering = ('name',) class ValCharBehav(models.Model): name=models.CharField("Value / Character / Behaviour", max_length=150, unique=True) def __str__(self): # __unicode__ on Python 2 return self.name class ValCharBehavWithPeople(models.Model): vcb=models.ManyToManyField(ValCharBehav, verbose_name="Value / Character / Behvaiour") bywhom=models.ManyToManyField(Party, verbose_name="By Whom", blank=True, related_name="valCharByWhomReverseAccessor") towhom=models.ManyToManyField(Party, verbose_name="To Whom", blank=True, related_name="valCharToWhomReverseAccessor") def __str__(self): # __unicode__ on Python 2 return self.vcb.name+": by: "+self.bywhom.name+", to: "+self.towhom.name -
How to improve performance of multi field search in MongoDB?
I have a collection (~900k of docs and counting). The doc scheme you can see in attachment. I want to search by almost every field in any sub document in any field combination. -
Query to retrieve neighbors is too slow
I have a set of ORM models representing a directed graph, and I'm trying to retrieve all the adjacent nodes to a given nodes ignoring edge direction: class Vertex(models.Model): pass class Edge(models.Model): orig = models.ForeignKey(Vertex, related_name='%(class)s_orig', null=True, blank=True) dest = models.ForeignKey(Vertex, related_name='%(class)s_dest', null=True, blank=True) # ... other data about this edge ... The query Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() returns the correct result, but in my case it takes far too long to execute. Typically for my application there will be around 50-100 vertices at any given time, and around a million edges. Even reducing it to only 20 vertices and 100000 edges, that query takes about a minute and a half to execute: for i in range(20): Vertex().save() vxs = list(Vertex.objects.all()) for i in tqdm.tqdm(range(100000)): Edge(orig = random.sample(vxs,1)[0], dest = random.sample(vxs,1)[0]).save() v = vxs[0] def f1(): return list( Vertex.objects.filter( Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() ) t1 = timeit.Timer(f1) print( t1.timeit(number=1) ) # 84.21138522100227 On the other hand, if I split the query up into two pieces I can get the exact same result in only a handful of milliseconds: def f2(): q1 = Vertex.objects.filter(edge_orig__dest=v).distinct() q2 = Vertex.objects.filter(edge_dest__orig=v).distinct() return list( {x for x in itertools.chain(q1, q2)} ) t2 = timeit.Timer(f2) print( t2.timeit(number=100)/100 ) # β¦ -
Error trying to list all objects in django databse
I am trying to list all out all objects in terminal. This is the model for my object: from django.db import models class Game(models.Model): gameId = models.CharField(max_length=250) date = models.CharField(max_length=250) time = models.CharField(max_length=250) awayId = models.CharField(max_length=250) awayCity = models.CharField(max_length=250) awayName = models.CharField(max_length=250) awayAbr = models.CharField(max_length=250) homeId = models.CharField(max_length=250) homeCity = models.CharField(max_length=250) homeName = models.CharField(max_length=250) homeAbr = models.CharField(max_length=250) isUnplayed = models.BooleanField() isInProgress = models.BooleanField() isCompleted = models.BooleanField() awayScore = models.CharField(max_length=250) homeScore = models.CharField(max_length=250) def __str__(self): return str(self.gameId) I then try and run this in terminal: Game.objects.all() To which i get this error: TypeError: str returned non-string (type NoneType) I have already created some data in terminal like this: >>>a = Game(gameId="1",date="2016-05-01",time="1:10PM",awayId="136",awayCity="San Fran",awayName="Giants",awayAbr="SF",homeId="127",homeCity="New york",homeName="Yankees",homeAbr="NYY",isUnplayed=False,isInProgress=False,isCompleted=True,awayScore="4",homeScore="6") >>> a.Save() Thanks for any advice!! -
AWS and Django: "Couldn't import Django"
I am new programming in Django. I do a local demo and it runs without problem but the next step is deploying the Django application on AWS Elastic beanstalk, I am trying that. I have this Enviroment: ~/Python_Env/MiEntorno And this Project: ~/ProyectosDjango/Refugio My current Django project structure is this: requirements.txt .ebextensions |-01-django_env.config .elasticbeanstalk |-config.yml .gitignore custom_storage.py manage.py Refugio |__init__.py |-settings |-urls.py |-wsgi.py |-apps |-templates |-static I have this error when i execute this command: (Mi Entorno) /ProyectosDjango/Refugio> manage.py collectstatic or manage.py runserver "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" I put this in my -01-django_env.config: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "Refugio.settings" PYTHONPATH: "/opt/python/current/app/Refugio:$PYTHONPATH" "aws:elasticbeanstalk:container:python" WSGIPath: "Refugio/Refugio/wsgi.py" and in setting I edit the database and add this: STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' AWS_STORAGE_BUCKET_NAME = 's3.refugioprueba.com' AWS_ACCESS_KEY_ID = 'xxx' AWS_SECRET_ACCESS_KEY = 'yy/xxx/' STATICFILES_STORAGE = 'custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' AWS_S3_CUSTOM_DOMAIN = '%s.s3-us-west-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_SECURE_URLS = False from boto.s3.connection import ProtocolIndependentOrdinaryCallingFormat AWS_S3_CALLING_FORMAT = ProtocolIndependentOrdinaryCallingFormat from boto.s3.connection import S3Connection S3Connection.DefaultHost = 's3.us.west-1.amazonaws.com' STATIC_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIA_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION ) WSGI_APPLICATION = 'Refugio.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ebdb', 'USER': 'root', β¦ -
Google Maps API JS Marker - Django
In Django, I am trying to populate the google maps api by rendering the template with info from views. I can get the results to return to the template however I am having difficulty implementing it into the javascript tag with Django. Any suggestions. I would like the django data to return into the addmarker function in JS Python - Django Views def maps_multi(request): address_list = CustomerOrder.objects.filter(city__icontains = 'CA').distinct() # pulls all unique addresses in California address_list1 = address_list[0:3] # temporarily select first three addresses from list to test geolocator = GoogleV3() add_list=[] for x in address_list1: add_city = x.city location = geolocator.geocode(add_city) add_list.append(location) print(add_list) context = {'location': add_list} return render(request, 'orderdisplay/maps_multi.html', context) //JAVASCRIPT // New map var map = new google.maps.Map(document.getElementById('map'), options); // INSERT Lat Lng via django here addMarker({coords:{lat:33.6846, lng:-117.8265}}); addMarker({coords:{lat:34.0522, lng:-118.2437}}); addMarker({coords:{lat:33.9533, lng:-117.3962}}); // Add Marker Function function addMarker(props){ var marker = new google.maps.Marker({ position: props.coords, map:map, icon:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png' }); } } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=*****&callback=initMap"> </script> -
I dont know how to modify my template tag to support vimeo too
I dont know how to modify if i use a vimeo link to make it embed. Template TAG: @register.filter(name='youtube_embed_url') def youtube_embed_url(value): match = re.search(r'^http(?:s?):\/\/(?:(www|m)\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?ββ[\w\?ββ=]*)?$', value) if match: embed_url = 'http://www.youtube.com/embed/%s' %(match.group(2)) res = embed_url return res return '' youtube_embed_url.is_safe = True Template use: <div class="embed-responsive embed-responsive-16by9 post-video"> <iframe class="embed-responsive-item" src="{{ post.video|youtube_embed_url|safe }}" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen"></iframe> </div> -
Passing from django formset to
This is my first Django project and this little bit turned out to be quite hard. I am making an itinerary generator by using formsets. These can be duplicated (I already know at least how to do it by working out the management form and all). For every event (it's someone traveling) I have passed information about the starting date and ending date, which is displayed on the form like this: Date 1 [Form 1][Form 2], Date 2 [Form 3][Form 4]. My problem is that in the end, when I put it back into the view, I would like to use json.dumps to turn it into an array, with the idea that the code is more readable and usable. Something like this: { "28-June-2017": [ {"time": "8:00", "Breakfast": "b", "responsible": "Person1"}, {"time": "18:00", "activity": "Dinner", "responsible": "Person1"} ], "29-June-2017": [ {"time": "8:00", "activity": "Breakfast", "responsible": "Person2"}, {"time": "12:00", "activity": "Lunch", "responsible": "Person"} ] } Now, I have solved everything but this so far. I have thought of passing the variable to the template and generate an input where the date can be added for each formset (thus repeating data for every input) and then doing something on the view in β¦ -
Issue setting specific modelform field's name django
I am working on a project and i want to know if anyone can help me with an issue that I was having while building my project. I have a ModelForm that asks a user for an amount and description based on a model. Within the template file, I want to loop through objects saved in the database and for each of the users, I want the form to be displayed and change the inputs name to add the username in the input name: default now = amount(decimalField) and description(charfield) desired = usernameamounta combination of cycled username and amount and usernamedescriptiona combinationn of cycled username and description this makes it so that within the view, I can cycle through the same username list and get the correct field name by doing the same process as i did when changing the field input name... Right now I manually create the form in my html file because i couldnt figure out how to do it using the form that was passed through, With the form i created, i was able to create the results that i want but when i try to do the same thing with the form that is passed, β¦ -
How to move a directory out of ./virualenvs and into my project in PYTHONANYWHERE
Just for the record - I feel so stupid asking this question. I can not move a directory out of; home/username/django18/lib/python35/site-packages into my Django project here; home/username/my_project I did a; pip install django-allauth to install AllAuth for my project, which in turn dropped it in the above directory, not my project. To be neat and organised... I would like my AllAuth diretory to sit in the main directory of my project.. I have tried using the bash terminal, but can not get to that directory from it. -
How do I set up Django 1.11 with Python 3.6.1 using Apache 2.4 on Ubuntu 16+
I'd like to know how to quickly and simply set up Django on Ubuntu. I am not an absolute beginner and I have some working knowledge of Django, Python, and Linux Shell Commands (Ubuntu) so the instructions can be quick and to the point. -
how to install Django with pip on Mac?
when I have tried to install pip by executing following command:----> Last login: Fri Jul 7 01:20:24 on ttys000 Suryakants-Mac:~ suryakantkumar$ sudo easy_install pip Password: Searching for pip Best match: pip 9.0.1 Processing pip-9.0.1-py2.7.egg pip 9.0.1 is already the active version in easy-install.pth Installing pip script to /usr/local/bin error: [Errno 2] No such file or directory: '/usr/local/bin/pip' Suryakants-Mac:~ suryakantkumar$ please help me to solve this problem. -
Heroku/Django Connection refused: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
2017-07-06T19:55:10.932781+00:00 heroku[web.1]: Starting process with command `python manage.py runserver 0.0.0.0:5303 --noreload` 2017-07-06T19:55:13.876394+00:00 app[web.1]: Performing system checks... 2017-07-06T19:55:13.876416+00:00 app[web.1]: 2017-07-06T19:55:13.904755+00:00 app[web.1]: System check identified some issues: 2017-07-06T19:55:13.904757+00:00 app[web.1]: 2017-07-06T19:55:13.904758+00:00 app[web.1]: WARNINGS: 2017-07-06T19:55:13.904773+00:00 app[web.1]: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DEBUG. 2017-07-06T19:55:13.904774+00:00 app[web.1]: 2017-07-06T19:55:13.904775+00:00 app[web.1]: System check identified 1 issue (0 silenced). 2017-07-06T19:55:13.928308+00:00 app[web.1]: Traceback (most recent call last): 2017-07-06T19:55:13.928310+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection 2017-07-06T19:55:13.928486+00:00 app[web.1]: self.connect() 2017-07-06T19:55:13.928488+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect 2017-07-06T19:55:13.928614+00:00 app[web.1]: self.connection = self.get_new_connection(conn_params) 2017-07-06T19:55:13.928615+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection 2017-07-06T19:55:13.928745+00:00 app[web.1]: connection = Database.connect(**conn_params) 2017-07-06T19:55:13.928746+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect 2017-07-06T19:55:13.928863+00:00 app[web.1]: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) 2017-07-06T19:55:13.928866+00:00 app[web.1]: psycopg2.OperationalError: could not connect to server: Connection refused 2017-07-06T19:55:13.928867+00:00 app[web.1]: Is the server running on host "localhost" (127.0.0.1) and accepting 2017-07-06T19:55:13.928867+00:00 app[web.1]: TCP/IP connections on port 5432? 2017-07-06T19:55:13.928868+00:00 app[web.1]: 2017-07-06T19:55:13.928870+00:00 app[web.1]: 2017-07-06T19:55:13.928870+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2017-07-06T19:55:13.928871+00:00 app[web.1]: 2017-07-06T19:55:13.928872+00:00 app[web.1]: Traceback (most recent call last): 2017-07-06T19:55:13.928898+00:00 app[web.1]: File "manage.py", line 22, in <module> 2017-07-06T19:55:13.928981+00:00 app[web.1]: execute_from_command_line(sys.argv) β¦ -
How to create an executable portable version of a django project
I wish to create a peer to peer network (communications done via HTTP) of nodes running a django project of mine. Is there anyway I can package my django project with a suitable web server and SQLite such that I can distribute an executable version of it to users which they can then run with one click? Thanks. -
How to test your django model using shell
I am trying to learn Django and have a very simple question that I am not able to get around with. I have coded my Django model as: class Work(models.Model): STATES = ( ('STARTED', 'started'), ('IN_PROGRESS', 'running'), ('FINISHED', 'completed'), ('ERROR', 'Error'), ) owner = models.ForeignKey("auth.User") temp = models.CharField(max_length=50, null=True, blank=True) current_run = models.CharField(max_length=50, null=True, blank=True) completion_percentage = models.IntegerField(blank=True, null=True) status = models.CharField(choices=STATES, max_length=50, blank=True, null=True) I have regenerated the db and now I want to use it Django views. But, before that is there a way to test it using python manage.py shell? I am trying to do: d_ = Work.objects.create(owner='admin') I get the error ValueError: Cannot assign "'admin'": "Work.owner" must be a "User" instance. Currently, I have userid as 'admin' in Users. I have tried doing few things to get around the error but I keep getting some kind of error because of the owner field (which is set to foreign key of auth.User). Any help will be appreciated here. Thank you! -
User Provided CSV in Django Web Project
I'm using Django to host a web application, and I would like to obtain a CSV file from the user, and process this information (using Python). I am currently using this line of code in the HTML to obtain the CSV file: <input type="file" accept="text/csv" id="mycsv"> Where in the Django project should I obtain the information from the CSV file, and how would I go about doing this? (I know the question is broad and doesn't give context for my specific project, but I figure that once I know how to access the data in the CSV I can figure the rest out). -
Dynamically structuring models django
I'm pondering a structure for an example that I am constructing and cannot figure out the optimal model structure. Basically I have a HTML canvas that I am building dynamically from a model. The current structure I have a Template and an Element model. Template contains a background image for the canvas and the Element model will have a ForeignKey back to the Template model. Element currently could be either a text Element or an image Element it also contains the x,y positions of the Element in the canvas I want to be able to dynamically create different canvases (at different urls) based on information that will be provided without having to continually create more Element instances. It seems to me there should be a third model involved here but what relationship is optimal? -
Translating formatted strings in Django not working
I have problem with translating formatted strings in Django using django.utils.translations. Only strings without format (%s or {}) are working. My locale/en/LC_MESSAGES/django.po file: msgid "foo" msgstr "bar" #, python-format msgid "foo %s" msgstr "bar %s" #, python-format msgid "foo %(baz)s" msgstr "bar %(baz)s " #, python-brace-format msgid "foo {}" msgstr "bar {}" #, python-brace-format msgid "foo {baz}" msgstr "bar {baz}" First string is working: >>> from django.utils import translation >>> translation.activate('en') >>> translation.ugettext('foo') 'bar' But rest is not: >>> translation.ugettext('foo %s' % 'bax') 'foo bax' >>> translation.ugettext('foo %(baz)s' % {'baz': 'bax'}) 'foo bax' >>> translation.ugettext('foo {}'.format('bax')) 'foo bax' >>> translation.ugettext('foo {baz}'.format(baz='bax')) 'foo bax' No mater if I use ugettext_lazy, gettext or gettext_lazy - same story, not translated output. Any idea why formatted strings are not working? Django 1.11.3 Python 3.5.3 -
Django renamging App and migrations
I have django app named "app1" with models and migrations files I rennamed this app to "app2" and I fixed all imports, urls ... but I have a probleme with migrations files and data in tables how can I write migrations with de correct way to ensure New installation =>create the new tables Update old versions => create new tables, move data, remove olds tables PS : there is several tables with many FK here My progress , I ma not sure that I am in the good way remove All old migrations makemigrations to generate new migrations files after this 2 steps I can install my application, but still have probleme with old version Question: what is the best way to migrate data ? PS: I dont use south