Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to uploads images on a web server. django
I want to display images on my "web site" and I can't find a mistake. In other posts i saw that need to upgrade settings.py but i set MEDIA_ROOT and MEDIA_URL as in example but it isn't helps me. settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' view def news(request): context = RequestContext(request) ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=3) if request.method == 'POST': form = NewsForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if form.is_valid() and formset.is_valid(): post_form = form.save(commit=False) #post_form.user = request.user post_form.save() for forma in formset.cleaned_data: try: image = forma['image'] photo = Images(post=post_form, image=image) photo.save() messages.add_message(request, messages.SUCCESS, "!!!") except KeyError: pass return redirect("main") else: print(form.errors, formset.errors) else: form = NewsForm() formset = ImageFormSet(queryset=Images.objects.none()) try: page_num = request.GET.get('page') except KeyError: page_num = 1 images = Images.objects all_news = News.objects.all() paginator = Paginator(all_news, 10) try: pages = paginator.page(page_num) except InvalidPage: pages = paginator.page(1) return render_to_response("mainpage.html", {'form': form, 'formset': formset, 'pages': pages, 'news': images}, context) and templete {% block content %} {% for new in pages %} <h2>{{ new.title }}</h2> <img src="{{ new.image.url}}"> {% endfor %} <form action="" method="post" enctype="multipart/form-data"> {% include "generic/form.html" %} <input type="submit" value="создать"> </form> {% endblock %} where is problem? -
Django load txt file dataset to model when page is served - strategy
I am developing a server in Django with the following layout: Network drive (Contains txt files) A1234.txt A1873.txt A8394.txt View1 (Provides a hyperlink list of the available files on a network drive) A1234.txt A1873.txt A8394.txt View2 (Generates a view of data when link from view1 is clicked) A1234.txt row col value 1 1 10 1 2 30 2 1 24 2 2 03 Because the text files are large, continuously generated, and numerous, I do not want to keep them on the server / load them all to model. Only when the link in view1 is clicked do I want the server to go fetch the appropriate file and generate the view. As an added bonus, view1 should continuously add links as the txt files are generated on the network drive (preferably without re-loading the view1 page). I realize this is pseudo-code - thank you for any and all suggestions. -
Django Rest Framework add object with foreign key and depth = 1
Using Django Rest Framework, I am attempting to add a model object via POST, specifying the id of an existing object to which the new object should have a foreign key. Works. If I add a depth=1 to the new object's serializer however, so that I get the foreign key target in a GET, the POST to add a new object fails with a mysql error 'IntegrityError: (1048, "Column 'reportdefinition_id' cannot be null")', even though I specify a valid foreign key id in my POST. I can work around this by leaving the depth = 1 out and retrieving the reportdefinition separately in my client, but that's cumbersome. (I found two related questions, but neither answers mine: Django REST - Create object with foreign key using serializers Need to show Foreign Key Object in Details by Django Rest Framework) Models (I've not shown irrelevant fields): class ReportDefinition(models.Model): name = models.CharField(max_length=254, blank=True, null=True) class ReportRun(models.Model): status = models.IntegerField(default=2) reportdefinition = models.ForeignKey(ReportDefinition) Serializers: class ReportDefinitionSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = models.ReportDefinition fields = ("id","name") class ReportRunSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: depth = 1 model = models.ReportRun fields =("id","status","reportdefinition") If I remove 'depth = 1', the POST works. class ReportRunSerializer(serializers.ModelSerializer): … -
Updating/disposing invalid cache keys
I'm using redis for caching in a django app. I'm also using Django Rest Framework, and here is my problem. I'm using the cache system like this: from django.views.decorators.cache import cache_page urlpatterns = [ ... url(r'^some_url/$', cache_page(CACHE_TTL)(SomeView.as_view()) ... ] Here, SomeView is a class that inherits from APIView. Now imagine we make a request to this url and we receive a json object containing one instance of whatever this url returns. Then we proceed to delete (using django's admin interface) that object, and make the request again. The expected result is an empty json object, but what I'm receiving is the same object unchanged, the same happens if a new object is added, the response still only one object. After some time (the TTL of the request in cache) the result is correct. So, how can I tell django that a cache entry it is no valid any more? -
How to apply the "collapse" style to a TabularInline object in the admin area?
When defining the fieldsets for the add view and change view for a model in the admin area, it's possible to minimise a section like this: fieldsets = ( ('First Heading', { 'classes': ('collapse',) 'fields': ('one', 'two') }), ('Second Heading', { 'fields': ('three',) }), ) The important bit being 'classes': ('collapse',). I've added a TabularInline object to one of the admin screens. Basically when I'm editing a User I can see a tabulated list of his friends. I'd like the TabularInline object to initially be collapsed, similar to 'classes': ('collapse',). Is this possible? Thank you. -
TemplateDoesNotExist at /contactos/
hi everyone i have problems with my view i get TemplateDoesNotExist at /contactos/ in the browser i using django 1.10 and folowing a tutorial from the definitive guide to django: web development done right 1.8 this is my view from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.shortcuts import render def contactos(request): errors = [] if request.method == 'POST': if not request.POST.get('asunto', ''): errors.append('Por favor introduce el asunto.') if not request.POST.get('mensaje', ''): errors.append('Por favor introduce un mensaje.') if request.POST.get('email') and '@' not in request.POST['email']: errors.append('Por favor introduce una direccion de email valida.') if not errors: send_mail( request.POST['asunto'], request.POST['mensaje'], request.POST.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contactos/gracias/') return render(request, 'formulariocontactos.html', {'errors': errors}) my url from django.conf.urls import url from . import views app_name = 'contactos' urlpatterns = [ url(r'^$',views.contactos, name ='contactos'), ] enter image description here sorry about my english -
How to hide all labels from modelformset_factory generated inputs?
I have following code in forms.py class MCQuestionForm(forms.ModelForm): class Meta: model = models.MultipleChoiceQuestion fields = ('prompt',) def __init__(self, *args, **kwargs): super(MCQuestionForm, self).__init__(*args, **kwargs) self.fields['choice'] = forms.ModelChoiceField(queryset=self.instance.choice.all(), widget=forms.RadioSelect, empty_label=None) MCQuestionFormSetForUser = modelformset_factory(models.MultipleChoiceQuestion, fields=('prompt',), form=MCQuestionForm, extra=0, widgets={ 'prompt': forms.TextInput( attrs={'readonly': True, 'class': 'borderless'}) } ) When I place "MCQuestionFormSetForUser" as formset.as_p in a template both prompt field and choices get corresponding labels. How can I hide them? -
Handling static files with nginx in a docker container
I am fairly new to nginx and I have a quick question on how to serve static files when using nginx. I got my django app running with ssl certificates but when I try to make it redirect from http to https and when I change from listen 80 to listen 8000 because when I run uwsgi I use command = /usr/local/bin/uwsgi --http :8000 --module website.wsgi in supervisor, so I thought I have to change it, however,when I try to enter the website it does not load and when I check the logs I get [error] 10#10: *2 open() "/home/docker/code/website/admin/css/login.css" failed (2: No such file or directory), request: "GET /static/admin/css/login.css HTTP/1.1". My nginx.conf file looks like this: upstream django { server 192.168.99.100:8000; # for a web port socket (we'll use this first) } # configuration of the server server { #listen 80 default_server; listen 443 ssl; listen 8000; # the domain name it will serve for server_name 192.168.99.100; # substitute your machine's IP address or FQDN rewrite ^ https://$server_name$request_uri? permanent; charset utf-8; ssl on; ssl_certificate /home/docker/code/certificate.crt; ssl_certificate_key /home/docker/code/key.key; # max upload size client_max_body_size 75M; # adjust to taste access_log /var/log/nginx/lb_access.log; error_log /var/log/nginx/lb_error.log; # Django media location /media { alias /home/docker/persistent/media; … -
Django model for either video OR image
I'm creating a model which the user has the option of either uploading an image, or using a video link (mostly youtube). What would be the best way to implement this? I'm not sure how to have a OR field.. :S -
Django-- valueError: path too long for windows
I am using django server to test my web-application. When I try to upload the excel file in a form and send it to the server, it raises valueerror. ValueError: stat: path too long for Windows I am using windows of course. Is there some fix that will solve this window problem? -
Django and nginx with docker compose - static files are not loaded
I know that several similar questions have been asked, but I have not managed to find a proper answer anywhere. I want to dockerize my Django app. The app works fine in the docker container but the static files (images, css etc.) are not loaded. My docker-compose.yml: version: '2' services: web: build: . command: ./start.sh volumes: - .:/app - /app/www/static ports: - "8000:8000" env_file: .env nginx: build: ./nginx links: - web ports: - "0.0.0.0:80:80" volumes_from: - web The start.sh script python manage.py makemigrations --noinput python manage.py migrate --noinput python manage.py collectstatic --noinput exec gunicorn audiobridge.wsgi:application --bind 0.0.0.0:8000 --workers 3 The Dockerfile for the web container: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app ADD requirements.txt /app/ RUN pip install -r requirements.txt ADD . /app/ Then I have an nginx/ directory in my project which has the following Dockerfile: FROM nginx COPY sites-enabled/audiobridge /etc/nginx/sites-enabled/ and inside nginx/sites-enabled there is the nginx configuration file: server { listen 80; server_name 127.0.0.1; charset utf-8; location /static { alias /app/www/static/; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } -
Save object if necessary, otherwise use existing
There is a Scheduler model in my project. This Scheduler model says how often do user wants to do some action with an item. There may be many items and users so I want to spare some space and querying times. Each item has one Scheduler object assigned to itself. class Scheduler(models.Model): monday = models.BooleanField(default=False) tuesday = models.BooleanField(default=False) wednesday = models.BooleanField(default=False) thursday = models.BooleanField(default=False) friday = models.BooleanField(default=False) saturday = models.BooleanField(default=False) sunday = models.BooleanField(default=False) hour_1 = models.BooleanField(default=False) hour_2 = models.BooleanField(default=False) hour_3 = models.BooleanField(default=False) hour_4 = models.BooleanField(default=False) hour_5 = models.BooleanField(default=False) hour_6 = models.BooleanField(default=False) hour_7 = models.BooleanField(default=False) hour_8 = models.BooleanField(default=False) hour_9 = models.BooleanField(default=False) hour_10 = models.BooleanField(default=False) hour_11 = models.BooleanField(default=False) hour_12 = models.BooleanField(default=False) hour_13 = models.BooleanField(default=False) hour_14 = models.BooleanField(default=False) hour_15 = models.BooleanField(default=False) hour_16 = models.BooleanField(default=False) hour_17 = models.BooleanField(default=False) hour_18 = models.BooleanField(default=False) hour_19 = models.BooleanField(default=False) hour_20 = models.BooleanField(default=False) hour_21 = models.BooleanField(default=False) hour_22 = models.BooleanField(default=False) hour_23 = models.BooleanField(default=False) hour_24 = models.BooleanField(default=False) def save(self,*args,**kwargs): scheduler = Scheduler.objects.filter(**{x:y for x,y in self.__dict__.iteritems() if x.startswith('hour') or x.endswith('day')}) if scheduler: return scheduler super(Scheduler, self).save(*args, **kwargs) When user creates a new item and sets schedule, I want Django to check, whether there exists such Scheduler object. If yes, don't create new Scheduler with same attributes, instead of that assign existing object … -
Trying to Increment a dyanmic url
I have a dynamic URL that takes the id of a model in the address. #urls url(r'^story/(?P<id>\d+)/$', views.story, name='story') Is there a way to make a link that increments the id? -
Increment a value in models.py and website behaves accordingly
I am new to Django and I've got the hang of the basics so far but I am trying to do something that the tutorials I learnt from haven't taught me and basically what I want to do is, I have a field in my models.py called delegates_num and that field is a counter for the number of delegates which sign up for a particular course. I want to be able to increment that field by 1 each time someone signs up for a particular course, the courses being [ITIL, Change Management, Management of Risk, Programme Management, PRINCE2] So for example, if the user books an ITIL course, the counter for that course will be incremented by 1. Each course has a limit of 15 spaces so a condition somewhere which says something like: if course.name = 'ITIL' && if delegates_num > 15 redirect user to 'course is full page' else submit registration form and increment delegates_num by 1 I would be extremely grateful for any help, here's the code so far: class Course(models.Model): MY_CHOICES = ( ('Open', 'Open'), ('Closed', 'Closed'), ('Fully Booked', 'Fully Booked'), ) course_name = models.CharField(max_length=40) course_code = models.CharField(max_length=40) price = models.CharField(max_length=40, default='add price') topic_details = models.TextField(max_length=200) … -
How to change only text inside td of table table using JQuery
I am trying to update the text inside a cell that contains also an input box. In line $(ib).closest('td').prop('textContent',888); I am assigning the value 888 to the text but this results in assignment of cell's text to "888" but also for some reason deleting the input box. My code (Django template): {% extends "base.html" %} {% block head_scripts %} <script type="text/javascript" src="/static/script/api_recs.js"></script> <script type="text/javascript" src="/static/script/site_filter.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"/> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.min.css"/> <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script> {% endblock %} {% block title %} Schedule Match {% endblock %} {% block styles %} <style type="text/css"> tfoot { display: table-header-group; } </style> {% endblock %} {% block content %} <table id='pm_table' class="display" cellspacing="0" width="100%"> <thead> <tr> {% for col_name in table_headers%} <th>{{col_name}}</th> {% endfor %} </tr> </thead> <tfoot> <tr> {% for col_name in table_headers%} <th>{{col_name}}</th> {% endfor %} </tr> </tfoot> <tbody> {% for data_row in table_data%} <tr> {% for item in data_row%} <td>{{item}}</td> {% endfor%} </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function() { var SITE_ID_COL = 0; var PRIORITY_COL = 3; var IS_SCHEDULED_COL = 4; // priority input box $("#pm_table td:nth-child(" + PRIORITY_COL + ")").each(function() { // $(this).children().css('visibility', 'hidden'); … -
graphene-django - How to filter?
I use graphen-django for build a GraphQL API. I have succesfully create this API, but I can't pass a argument for filter my response. This is my models.py: from django.db import models class Application(models.Model): name = models.CharField("nom", unique=True, max_length=255) sonarQube_URL = models.CharField("Url SonarQube", max_length=255, blank=True, null=True) def __unicode__(self): return self.name This is my schema.py: import graphene from graphene_django import DjangoObjectType from models import Application class Applications(DjangoObjectType): class Meta: model = Application class Query(graphene.ObjectType): applications = graphene.List(Applications) @graphene.resolve_only_args def resolve_applications(self): return Application.objects.all() schema = graphene.Schema(query=Query) My urls.py: urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', authviews.obtain_auth_token), url(r'^graphql', GraphQLView.as_view(graphiql=True)), ] As you can see, I also have a REST API either. My settings.py contains this: GRAPHENE = { 'SCHEMA': 'tibco.schema.schema' } I follow this: https://github.com/graphql-python/graphene-django When I send this resquest: { applications { name } } I've got this response: { "data": { "applications": [ { "name": "foo" }, { "name": "bar" } ] } } So, it's works! But when I try to pass an argument like this: { applications(name: "foo") { name id } } I have this response: { "errors": [ { "message": "Unknown argument \"name\" on field \"applications\" of type \"Query\".", "locations": [ { "column": … -
python Django angular materials form
How can I make material design form in Django And submit values of each input box I. I got this when I search" > http://forms.viewflow.io/ I tried, but failed. -
How To Run A Basic Python Script With Nginx On Ubuntu?
I've Searched A Lot About "How To Run Python Scripts Using Nginx On Ubuntu" But Couldn't Find Anything Helpful, I Have A Simple Hello World Script: #!/usr/bin/python print "<h1>Hello, World</h1>" And Saved As hello.py I Know For "Apache" We Add : <Directory /var/www/html> Options ExecCGI Indexes FollowSymlinks MultiViews AllowOverride None Order allow,deny allow from all AddHandler cgi-script .py </Direcory> And Apache Can Run The Script As Well, Is There Any Alternative Way To Do This On Nginx Without Using Any Framework Like Django Or Flask? -
Session authentication with Angular 2
I've been looking all around for Session based authentication with Angular 2. I am building an application that has Django on backend and Angular 2 on the frontend. To keep the process simple i am trying to implement django session authentication. // Angular 2 authentication service import { Injectable } from "@angular/core"; import { Headers, Http, Response } from "@angular/http"; import "rxjs/add/operator/toPromise"; import 'rxjs/add/operator/map' import { AppSettings } from "../../app.settings"; @Injectable() export class UserAuthService { private headers = new Headers({'Content-Type': 'application/json'}); private loginUrl = `${AppSettings.BACKEND_URL}` + '/api/v1/users/login/'; constructor( private http: Http ) { } login(username, password) { let data = { username: username, password: password }; return this.http.post(this.loginUrl, data, this.headers) .map((response: Response) => response.json()); } } # Django Login view def login(self, request): username = request.data['username'] password = request.data['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) serializer = self.serializer_class(user) return Response(serializer.data, status=status.HTTP_200_OK) raise AuthenticationFailed I am successfully calling backend api and view returns the successful response. request.user gets update after the login but when i try to call the other APIs using Angular or directly browse django rest api user is not login. -
SQlite3 Populate new column with another column's previous rows values
I want to achieve almost exactly what's given in this question, but the LEAD and LAG functions are unsupported in SQlite3. I want to fill a column of the existing table, with the values of another column but offset by one row I've searched for quite a while, but I cannot find a suitable alternative. Assuming there are 100 rows of data, and the new column is already created (and full of junk values), the below code for me yields no result at all. The values remain as junk (unchanged). The most I've managed travelling down this rabbit hole, is this: for i in range(1, 99): cur.execute('''UPDATE myTable SET a = (SELECT CASE WHEN id > 1 THEN b ELSE 0 END AS b FROM myTable WHERE id = %d) ''' % i) As per my understanding of the above, 1. IF id < 1, a = 0 2. IF id > 1, a = b, where id = i, and i trails behind by 1. I'm just looking for a push in the right direction, the above code is typed out and may not be syntactically correct. I'm currently working on an SQlite3 server on Django, which will explain … -
CommandError: You appear not to have the 'cqlsh' program installed or on your path
In Django with Cassandra , while running the #python manage.py dbshell Casssandra is running and we could able to run the #python manage.py sycn_cassandra and it created the tables in the DB. But dbshell failes with following error . Same command ran in dos prompt " CommandError: You appear not to have the 'cqlsh' program installed or on your path." -
Define cron-like model in Django
I'm working on a project where each item has it's own schedule - it can be period (each 5 hours) or timing like every monday morning. For now, I've added a frequency attribute. The problem is that this attribute can hold only period (do something each x hours etc.). I would like to change this model to be able to hold all informations you can do in celery crontab (the minimum period could be hour). Is there some best practise how to make such models or store such info? class Timing(models.Model): frequency = models.PositiveIntegerField() active = models.BooleanField(default=True) last_scan = models.OneToOneField('Scan') I was thinking about storing CharField which would look like celery crontab definition - "crontab(hour=2, minute=0)" would be every day at 02:00 am etc, "crontab(minute=0, hour='*/3')" would be each 3 hours. But I'm not sure if this isn't too much unefficient. What would you do? -
Decorators for class-based views that use class variables in Django
I have a class-based view that is inherited by other views: class EditProfileAttribute(View): ThisModel = models.Model def get(request, model_id): instance = self.ThisModel.objects.get(id=model_id) if instance.user != request.user: return HttpResponseForbidden("Forbidden.") # do some editing here, save forms, etc. return HttpResponse("Edited") class EditAddressView(EditProfileAttributeView): ThisModel = Address class EditLinkView(EditProfileAttributeView): ThisModel = Link Now in my models.py file: class Address(models.Model): user = models.ForeignKey(User) address = models.TextField(max_length=100) class Link(models.Model): from_user = models.ForeignKey(User, related_name='from_link') to_user = models.ForeignKey(User, related_name='to_link') The class EditAddressView works because the User field is explicitly called user, but the class EditLinkView does not because it requires instance.from_user instead of instance.user. (Let's just say I can't rename from_user). What I'd like to do is to transform the instance.user != request.user part into a decorator where the syntax user is not required, but I can't figure out how to reference self.ThisModel. Is what I want even possible? -
RelatedObjectDoesNotExist during form validation
I have an issue that makes me crazy I have model class Property1(CommonInfo): unit = models.ForeignKey(Unit) is_true = models.BooleanField(default=False) propertytype = models.ForeignKey(Propertytype, related_name='propertytype') date = models.DateTimeField(null=True, blank=True) followup_date = models.DateTimeField(null=True, blank=True) quantity = models.PositiveSmallIntegerField() def __str__(self): return self.propertytype def clean(self): model = self.__class__ if (self.unit) and model.objects.filter(unit=self.unit, propertytype=self.propertytype ).exclude(id=self.id).count() == 1: raise ValidationError('Same property cant be assigned more then ones') for this model I have form class Property1Form(forms.ModelForm): class Meta: model = Property1 fields = ['unit','propertytype','is_true','date','followup_date','quantity','description'] def __init__(self, *args, **kwargs): super(Property1Form, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance: self.fields['unit'].required = False self.fields['unit'].widget.attrs['disabled'] = 'disabled' And I have a view def property_new(request,pk,uri): unit = get_object_or_404(Unit, pk=pk) title = 'property' uri = _get_redirect_url(request, uri) if request.method == "POST": form = Property1Form(request.POST) form.unit = unit if form.is_valid(): properties = form.save(commit=False) properties.unit = unit properties.save() messages.add_message(request, messages.SUCCESS, str(properties.unit) + "-SUCCESS Object created sucssefully") return redirect(uri) else: form = Property1Form(initial={'unit': unit}) return render(request, 'object_edit.html', {'form': form, 'title':title, 'extend': EXTEND}) However, after creating new property I always get RelatedObjectDoesNotExist at *** Property1 has no unit. Error triggered during execution of if form.is_valid(): What is the problem? -
Django : Web hosting
I am looking for the best web hosting solution for my website. It's developed with Django 1.9 and it uses Channels (redis, asgi...). I have already tested AlwaysData but Channels it's not supported... I am living in France and my web site will receive 8000 visitors per month (on average). I want to precise that I am very beginner in system configuration. I want easy (and fast) instalation of my website Currently, I hesitate between WebFaction, DigitalOcean, GoDaddy and Heroku. What is the best ? Thank you