Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hosting Django website on sherd server (BlueHost)
i'ev created a website using Django 1.8 framework and python3.4 programming language. During the development process i was testing the website using my local severe, Now i want to upload my project in sherd server (BlueHost). So far: 1- created the server space and the link is : http://www.gadgetron.net 2- installed pip,setuptools,Django 1.8, rest framework and python 3.4 all in the home directory: /home8/gadgetr5 3- upload the Django project in the /home8/gadgetr5/public_html directory. 4- my website project in the blue hist server is: public_html |_cgi-bin |_src | |_manage.py | |_chatbot | |_settings.py |_static |_application.fcgi |_.htaccess (src is the django project that include the other needed files) 5- the application.fcgi includes: #!/home8/gadgetr5/python-3.4.3/python import sys, os # Add a custom Python path. sys.path.insert(0, "/home8/gadgetr5/Python-3.4.3/python") sys.path.insert(13, "/home8/gadgetr5/public_html/src") os.environ['DJANGO_SETTINGS_MODULE'] = 'chatbot.settings' from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false") 6- the .htaccess file: AddHandler fcgid-script .fcgi Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteRule ^(media/.*)$ - [L] RewriteRule ^(adminmedia/.*)$ - [L] RewriteCond %{REQUEST_URI} !(application.fcgi) RewriteRule ^(.*)$ application.fcgi/$1 [L] BUT when i run the command: gadgetr5@gadgetron.net [~]# python3 application.fcgi i get this ERORR: ImportError: No module named 'chatbot' or sometimes this ERORR: <h1>Bad Request(400)</h>WSGIServer: missing FastCGI part REQUEST_METHOD required by WSGI and when i vista the website there … -
Exclude a queryset from bigger queryset in django without hitting the database
I have a queryset of all objects of a model. Iterating over the objects, I am removing updating rows with value repetition in a column. So without having to hit the database again, i want to remove the updated rows from the bigger queryset. What is the most efficient way to do this? -
request.META does not contain header
I'm using djangorestframework with the following code: class RegistrationView(APIView): def post(self, request, format=None): print self.request.META.get('API_KEY') And it returns None (other headers such as Content-Type or User-Agent are OK). But this header definitely exists in request (this key is local-db only, so it's ok to paste it here): Why? -
How to match url case insensitively in django rest framework?
I have this line in a urls.py url(r'^(?i)(?P<datasource>[a-z]+)/$', views.OdbcConfigDatasourceDetail.as_view()), The (?i) is supposed to make the regex case insensitive. I suspect it is in fact searching case-insensitively, but that it is passing the named group datasource with case intact, which then causes lookup to fail. How can I either lowercase the named group or the lookup field before it gets passed? -
Model propery not working in django rest framework
I have a movie model: class Movie(models.Model): name = models.CharField(max_length=254, unique=True) language = models.CharField(max_length=14) synopsis = models.TextField() censor_rating = models.PositiveIntegerField(choices=CENSOR_TYPE) @property def is_screening(self): if self.showtime_set.all().count() > 0: return True else: return False And its Movie Serializer: class MovieSerializer(serializers.HyperlinkedModelSerializer): movie_id = serializers.IntegerField(read_only=True, source="id") is_screening = serializers.ReadOnlyField() class Meta: model = Movie depth = 1 fields = '__all__' Finally its ViewSet: class InTheatersViewSet(viewsets.ModelViewSet): queryset = Movie.objects.filter(is_screening=True) serializer_class = MovieSerializer However this is showing error: django.core.exceptions.FieldError: Cannot resolve keyword 'is_screening' into field. Choices are: censor_rating, id, language, name, synopsis How can I use the model propery as a filter with the django-rest-framework to get the list of Movie objects whose screening are true? -
Chrome does not execute js properly but firefox does it
Sorry for my english. Correct me if I wrong. This function execute properly in firefox but target browser is chrome and I dont know what's wrong myjs.js function addProduct(order_id) { $.ajax({ type: "post", data: $("#formProducts").serialize(), url: "/save/" + order_id, complete: function(){} }); $.ajax({ type: "get", url: "/add/product/" + order_id, complete: function(){ window.location.reload() }, }); } views.py def post(self, request: HttpRequest, *args, **kwargs): order = Order.objects.get(id=int(kwargs['order_id'])) try: comment = Comment.objects.get(order=order) comment.text = request.POST['comment'] except Exception as _: comment = Comment(text="", order=order) comment.save() for key, val in request.POST.items(): if "status" in key: idp = int(key.split("status")[1]) product = Product.objects.get(id=idp) product.status = val product.save() elif "provider" in key: idp = int(key.split("provider")[1]) product = Product.objects.get(id=idp) product.provider = val product.save() elif "med" in key: idp = int(key.split("med")[1]) product = Product.objects.get(id=idp) product.name = val product.save() elif "amount" in key: idp = int(key.split("amount")[1]) product = Product.objects.get(id=idp) product.amount = val product.save() elif "cost" in key: idp = int(key.split("cost")[1]) product = Product.objects.get(id=idp) product.cost = val product.save() elif "ITOG" in key: order.summary = val order.save() url_ref = request.session["url_ref"] return redirect(url_ref) def addProduct(request: HttpRequest, order_id): order = Order.objects.get(id=int(order_id)) product = Product(name="", amount=1, cost=0.0, order=order) product.save() return HttpResponse() Function must collect formdata and post it. Then make get request and reload page. Chrome … -
Why Django return form is invalid?
I have a problem whit a function, when I use the tag {{form.image_cliente}} always return a "form is invalid" and don't save nothing but if I use the tag {{form.as_p}} return a form is valid and save the field image_cliente, and I dont know why, I just want to display only the form.image_cliente in the template. This is my def function in my views: def subirIMGCliente(request, pk): clientes = get_object_or_404(Cliente, pk=pk) if request.method == 'POST': form = ClienteForm(request.POST, request.FILES, instance=clientes) if form.is_valid(): clientes = form.save(commit=False) if clientes.password == '': clientes.save(update_fields=['image_cliente']) print('yes'); return redirect('BackEnd:cliente') else: print('form in not valid'); else: form = ClienteForm(instance=clientes) return render(request, 'back/Modulo_cliente/imagenes_cliente.html', {'form': form }) -
Django API ignored exception in sessions module
I'm running a django rest framework server hosted on google cloud. Every hour or so I get a couple of these errors that I can't figure out: Exception ignored in: <function _get_module_lock.<locals>.cb at 0x7f50f275ebf8> Traceback (most recent call last): (no traceback provided) File "<frozen importlib._bootstrap>", line 191, in cb "KeyError: ('django.contrib.sessions.serializers',) There's no traceback since the error is caught and ignored. I've followed the code down to the cpython library in this method: def _get_module_lock(name): """Get or create the module lock for a given module name. Should only be called with the import lock taken.""" lock = None try: lock = _module_locks[name]() except KeyError: pass if lock is None: if _thread is None: lock = _DummyModuleLock(name) else: lock = _ModuleLock(name) def cb(_): del _module_locks[name] _module_locks[name] = _weakref.ref(lock, cb) return lock Has anyone seen this error before? I can't find any pattern of when this error comes in and can't manually reproduce it with any certainty. -
Adding prefix path to static files in Angular using angular-cli
I have an existing django project where I am serving static files over /static/ path. I am migrating a part of the application to angular2, to be specific mobile version of the site. Adding <base href="/"> to index.html loads static files www.example.com/main.js gets 404 here. Adding <base href="/static/"> to index.html loads static files correctly, but when the application bootstraps, it changes the url to /static/ (i am using routers), although my url should be /order/. is there a way of using base href as / but adding prefix to script and style files using angular-cli using version ng --version @angular/cli: 1.0.0-rc.0 node: 6.9.1 os: win32 x64 @angular/common: 2.4.9 @angular/compiler: 2.4.9 @angular/core: 2.4.9 @angular/forms: 2.4.9 @angular/http: 2.4.9 @angular/platform-browser: 2.4.9 @angular/platform-browser-dynamic: 2.4.9 @angular/router: 3.4.9 @angular/cli: 1.0.0-rc.0 @angular/compiler-cli: 2.4.9 -
Django - Slug field for model object not being applied to URL
I was watching a YouTube tutorial that showed how to use the id of a model object in the URL of a detailed view of said object, and tried to apply the same concept to the slug field by replacing all 'id' with 'slug' (the name of my model slug field). However this just happens to bring up an error - NoReverseMatch at /dashboard/ Reverse for 'campaign-detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?i)dashboard/campaigns/(?P/slug[-\w\d]+)/$'] views.py: def campaign_detail(request, campaignprofile_slug): if request.user.is_authenticated: campaignprofile = get_object_or_404(CampaignProfile, slug=campaignprofile_slug) return render(request, 'campaign-detail.html', {'campaignprofile': campaignprofile, 'slug': slug}) else: return redirect('/users/login/next?=') urls.py: url(r'^campaigns/(?P<slug>[-\w\d]+)/$', views.campaign_detail, name='campaign-detail') models.py for the model object I'm trying to display: class CampaignProfile(models.Model): user = models.ForeignKey(UserModel, related_name='campaignprofile', on_delete=models.CASCADE, null=True) campaign_title = models.CharField(max_length=50, verbose_name='Title') slug = models.SlugField(unique=True, blank=True, null=True) HTML Template a href tag: <a href='{% url "campaign-detail" slug %}'></a> Any potential solutions for this problem would be amazing thank you. -
still show IntegrityError to user even form validate successful
for example, I post some data like this: data_list = [ { "name": "xx", "phone": "12", }, { "name": "xx", "phone": "12", } ] this is the View: @transaction.atomic def post(): for data in data_list: form = form(data) form_list.append(form) try: if form_list_all_form_is_valid(): for form in fomr_list: form.save() return redirect(reverse(...)) except IntegrityError: logger.debug("name repeat") return render(request, tempalte_name, { "form_list": form_list, }) this is the template template: {% for form in form_list %} {{ form.error }} {% endfor %} After I catch the IntegrityError, as you know, form.is_valid() is true, even it's save failed, but I want to make form have error, of course I can do it like this: for data in data_list: form = form(data) if form is valid(): form.save() # here save directly else: form_list.append(form) if len(form_list): return render(request, tempalte_name, { "form_list": form_list, }) Is there any better way handle this, I am new django people, so help me, or hint me . -
Django breaking long lookup names on queries
Let's assume there is a line of code to perform a query using the Django ORM that contains a very long 'lookup name': QuerySet.filter(myfk__child__onetoone__another__manytomany__relation__monster__relationship__icontains=':P') I'd like to break the line to follow pep8, specially 79 character limit I know we can do something like: QuerySet.filter( **{ 'myfk__child__onetoone__another' '__manytomany__relation__monster' '__relationship__icontains': ':P' } ) But I'm wondering if there is another, maybe more pythonic/accepted, way ? -
Optimizing Django ManyToManyField('self', symmetrical=False)
So,... our model stores relations in Django models.ManyToManyField, namely: class Person(models.Model): providers = models.ManyToManyField( 'self', blank=True, symmetrical=False, related_name='my_friends' ) And then, let's say we want to filter objects based on some condition, up to Nth level. To be explicit, we want to: nested_object_ids = [] for f_1 in Person.objects.get(name='Mike'): nested_object_ids.append(f_1.id) for f_2 in f_1.suppliers.all(): nested_object_ids.append(f_2.id) ... for f_N in f_N.suppliers.all() nested_object_ids.append(f_N.id) Person.objects.filter(..., id__in=nested_object_ids) However, this takes a lot of time. What would be your suggestion how to optimize this query in Django? Thanks! -
formatting django crispy form from model form
I am using django-crispy-forms to generate a simple form which is shown in a jquery dialog box. My model is as follows: class DummyModel(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=150) time_points = models.PositiveIntegerField() more_text = models.CharField(max_length=100) class Meta: db_table = "dummy" I use the FormHelper object in my form class to customize some lookout as shown in the crispy forms documentation as follows: class DummyForm(ModelForm): def __init__(self, *args, **kwargs): super(DummyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Field('name', css_class='input-xlarge'), Field('description', rows="3", css_class='input-xlarge'), ) class Meta: model = DummyModel fields = ['name', 'description'] Now in my template, I do the following: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Dummy | Test {% endblock %} {% block content %} <div id="dialog" title="Edit" style="display: none;"> <form method="post" action=""> {% csrf_token %} {% crispy DummyForm %} <input type="submit" value="Submit Form"/> </form> </div> {% load static %} {% load render_table from django_tables2 %} <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> function EditDialog() { $( "#dialog" ).dialog(); return false; } </script> <div class="function-page"> <div class="table-form"> <div class="function-container"> {% render_table reviews %} </div> </div> </div> {% endblock %} The form is loaded when the EditDialog() javascript is called … -
Django multiple files upload only returns the last file
I am trying to post multiple files from a form to my django view. However, only the last file that was uploaded is posted. Html: <form enctype="multipart/form-data" role="form" method = "post"> {% csrf_token %} {% load bootstrap %} {{form|bootstrap}} <input type="file" id="upload" name="myfiles[]" multiple> <div id="upload_prev"></div> <button type="submit">{% trans "upload_lesson_plan" %}</button> </form> python: files = request.FILES.getlist('myfiles[]') print(files) Output: [<InMemoryUploadedFile: name_of_last_image>] Any idea how to fix this? I would really appreciate the help. Thanks in advance! -
Boolean field with choices
I want to have class with boolean field, which is set False on default. Then I can change this on True. Is my solution is OK. I use Django 1.6 class IsActive(models.Model): ACTIVE = 'T' DISABLE = 'F' ACTIVITY_TYPES = ( (ACTIVE, True), (DISABLE, False), ) isactive = models.BooleanField(default=ACTIVITY_TYPES[1][1]) def __unicode__(self): return str(self.isactive) -
Python Tuples ValueError: too many values to unpack
I'm trying to change my many if elif statements to dictionaries in my django view however I keep getting the error ValueError: too many values to unpack. Not sure what I'm doing wrong geo_lookup = { 'State': (State, ['name__in=searchVar'], [], []), 'County': (County, ['state__in=searchVar'], ['state__in=searchVar', 'name__in=filter2'], []), 'DMA': (Dma, ['state__in=searchVar'], ['state__in=searchVar', 'name__in=filter2'], []), 'CD': (Cd, ['state__in=searchVar'], ['state__in=searchVar', 'cd114fp__in=filter2'], []), 'Zip': (Zip, ['state__in=searchVar'], ['state__in=searchVar', 'county__in=filter2'], []), 'Zones': (zones, ['state__in=searchVar'], ['state__in=searchVar', 'dma__in=filter2'], ['state__in=searchVar', 'owner__in=filter3'], ['state__in=searchVar', 'dma__in=filter2, owner__in=filter3']), } lookup_model = geo_lookup[geogVar][0] filtering1 = geo_lookup[geogVar][1] logging.debug(filtering1) filtering2 = geo_lookup[geogVar][2] filtering3 = geo_lookup[geogVar][3] as_json = serialize('json', lookup_model.objects.filter(*filtering1)) if filter2 != 'All': as_json = serialize('json', lookup_model.objects.filter(**filtering2)) elif filter3 != 'All': as_json = serialize('json', lookup_model.objects.filter(**filtering2)) elif (filter2 != 'All') and (filter3 != 'All'): as_json = serialize('json', lookup_model.objects.filter(**filtering3)) return HttpResponse(as_json, content_type='json') -
Python - Consume soap webservice as response to my own webservice (suds and spyne)
I need to act as a "middleman" between two soap webservices. I'm writing my webservice with python 3.5.2, Spyne, Django, and Apache with mod_wsgi in daemon mode, and as my response I need to get data from another soap webservice, that I'm consuming with suds. If I consume the service that I'll use as response directly from Python + suds, I get the data OK, all goes well, but when I call this webservice from withing my own webservice, it always throws me an 'Http 404 Not Found' error the moment it tries to instantiate the Client class. Here is the consuming code that works: from suds.client import Client from suds.transport.https import HttpAuthenticated url = 'https://url.url/?wsdl' credenciais = dict(username='blablabla', password='blablabla') t = HttpAuthenticated(**credenciais) client = Client(url, transport=t) produtos = client.service.listarProdutos() print(produtos) I'm writing my webservice like this: from spyne import Application, rpc, ServiceBase, Unicode class Consulta325(ServiceBase): @rpc(Unicode, Unicode, _operation_name='consulta325', _out_message_name='Retorno', _returns=Retorno325_PF) def mensagem(ctx, token, cpf): ret = Retorno325_PF() try: url = 'https://url.url/?wsdl' credenciais = dict(username='blablabla', password='blablabla') t = HttpAuthenticated(**credenciais) client = Client(url, transport=t) (Of course this is only a part of the service) When it gets to client=Client(url, transport=t) it throws me the error. Any help would be appreciated! I … -
Converting function based view to class based view
function based def invoice_view(request): form = InvoiceForm(request.POST or None) if form.is_valid(): doctype = form.cleaned_data['format'] filename = fill_template( 'briefcase/invoice.odt', form.cleaned_data, output_format=doctype) visible_filename = 'invoice.{}'.format(doctype) return FileResponse(filename, visible_filename) else: return render(request, 'briefcase/form.html', {'form': form}) class based @method_decorator(login_required, name='dispatch') class invoice_view(LoginRequiredMixin, IndexView): form = InvoiceForm(request.POST or None) if form.is_valid(): doctype = form.cleaned_data['format'] filename = fill_template( 'briefcase/invoice.odt', form.cleaned_data, output_format=doctype) visible_filename = 'invoice.{}'.format(doctype) return FileResponse(filename, visible_filename) else: return render(request, 'briefcase/form.html', {'form': form}) The error I get return FileResponse(filename, visible_filename) SyntaxError: 'return' outside function What am I missing? -
AWS boto3 Unable to locate credentials python/django form.save()
I'm getting Unable to locate credentials error when I run do form.save() on a Django project using an Apache server but not getting the error when I run the same project in the Django development server (using python manage.py runserver). I'm saving media files to S3. I've run aws configure on the server and entered the same credentials but no still get the error. What am I missing? -
Using python's .index() on a django values_list(Flat=True) query
I'm trying to figure out what is the rank of a django model object within objects that meet the same criterias. My idea was to get a flat values_list of primary keys like this: [In the models.py page, in the Model "Risk", other linked models are Worktask and Type] my_list_of_filtered_pks = Risk.objects.filter( worktask__code = self.worktask.code, type__id = self.type.id ).values_list('pk', flat=True).order_by('pk') And then get the index of my particular instance using something like: rank = my_list_of_filtered_pks.index(self.pk) But i get an error saying that my my_list_of_filtered_pks has no attribute 'index' 'QuerySet' object has no attribute 'index' What am i missing here ? Thanks ! i'm relatively new to django .. ! -
How to run tests in django using database with data?
I want to test my views using data from postgres localhost database (with already loaded data). I'm using tox with pytest and pytest-django. My question: How to set up / connect to local database to get all the data model schema and data itself? Or maybe it is better to use factory_boy? Or to load whole data from .sql script (if yes, how)? Example of my test: def test_foo_view(custom_client_login): response = custom_client_login.get('/foo/bar/123/') assert response.status_code == 200 assert 'Transaction no. 123' in response.content But instead of getting status code 200 I get 404, which points that no data is in test database. But when I lunch runserver and go to that view ('localhost:8000/foo/bar/123/') I will get status 200 and html webpage with some data. Please help! I'm using: Django==1.7.11 pytest==3.0.6 pytest-django==3.1.2 tox==2.6.0 -
Django unpected IntegrityError with PostgreSQL
I am using postgreSQL with Django 1.10 and python 3.4. I have a Course model defined like this: class Course(models.Model): title = models.CharField(max_length=200, unique=True) content = models.TextField(max_length=200) Then i manually added unique index to the title column using the following command. CREATE UNIQUE INDEX title_unique on wiki_course (LOWER(title)); Lets say database already has "Programming Basics" as title. When I add "programming basics" to title and hit save , it shows me the following error. IntegrityError at /admin/wiki/course/add/ duplicate key value violates unique constraint "title_unique" DETAIL: Key (lower(title::text))=(programming basics) already exists. Request Method: POST Request URL: http://127.0.0.1:8000/admin/wiki/course/add/ Django Version: 1.10.5 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "title_unique" On the otherhand if i switch the database from MySQL and try again it would tell me Course already exists. Is there any way to achieve this behavior in PostgreSQL ? Please bare with me i am new to Django. Thanks -
How do you find out if a file is corrupted?
Earlier I found that a jpg, which was a scan of an important document was corrupted. I have no clue how it got corrupted. Since this file was managed by my app and never accounted that files might get corrupted one day, I want to know what is the standard practice to ensure the integrity of the file? There are many files and I want to spot the files that get corrupted and look at the backups to recover them proactively and do a reactive recovery. Based on what I gathered so far, md5 can be used to spot if a file is corrupted. So once a file is introduced to the system, I get a md5 hash. Then periodically, I run a process to check if all the file's md5 is consistent. This is part of an app that is written in Rails. But I would like a language agnostic solution(if feasible) as I have an old system in asp.net and I am building a new one in Django also. Or is there a specialised app that just does this? -
DictReader filenames returning blank list
I've got two functions right now in order to process csv files uploaded to my website, the first function, process_csv works fine and will correctly output the fieldnames, but when i pass the csvfile to the flexRead function, writer_list returns as a blank list. All of the code in try and exceptions are running properly and not causing errors. I cant seem to figure out where ive gone wrong, any help would be great! import io import csv import sys def flexRead(csvfile): writer_list = [] try: f = io.StringIO(csvfile.read().decode('utf-8')) except: writer_list.append(sys.exc_info()) # create a DictReader object from f try: f = csv.DictReader(f) except: writer_list.append(sys.exc_info()) writer_list.append(f.fieldnames) for row in f: writer_list.append(row) return writer_list def process_csv(request, csvfile): errors_found = [] f = io.StringIO(csvfile.read().decode('utf-8')) f = csv.DictReader(f) #appending f.fieldnames to my errors found allows me to see the fieldnames #on the website, and this function correctly gets the fieldnames #errors_found.append(f.fieldnames) try: flex = flexRead(csvfile) except: errors_found.append(sys.exc_info())