Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Tastypie - Why does Tastypie object authorization not work?
I am new to Django and Tastypie and trying to work out how the API authorization works following the documentation here. As far as i can tell it does not work. When I make a POST request to an object NOT owned by the request user it returns true when it should not (i haven't tried DELETE or PUT but I imagine it is the same). Either I have implemented it wrong (probable) or there is a bug. So the question is: How do i implement object authorization with the code example below? For example, I want only the Owner of Stock to be able to POST a Comment or Note on that Stock. This is the book/models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User import uuid class Stock(models.Model): ''' Model representing the stock info. ''' user = models.ForeignKey(User) book_code = models.CharField(max_length=14, null=True, blank=True) def __str__(self): return self.book_code class Note(models.Model): ''' Model representing the stock note. ''' user = models.ForeignKey(User) note = models.TextField(max_length=560) stock = models.ForeignKey(Stock) date_note_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.note class Comment(models.Model): ''' Model representing a Comment for each stock. ''' id = models.UUIDField(primary_key=True, default=uuid.uuid4) stock = models.ForeignKey(Stock, null=True) text = models.TextField() … -
ValidationError - field required in empty form of Formset
I have a formset which is being prefilled using javascript according to what does user have in database. If user has associated 5 objects, 5 forms are shown and prefilled. I've created a JS function which resets formset and user can add new data (old will be deleted). The problem is that Django returns ValidationError (field is required) if some of those prefilled forms are empty. I tried to override clean method but this didn't help. (if value field isn't filled, then form is considered valid). class MyForm(Form): def clean(self): if self.cleaned_data.get('value'): return super(MyForm,self).clean() return self.cleaned_data Do you know what to do? -
Best way to add working code example to django article?
Hi guys I need your help with site blog architecture. I made blog in django where I write about IT. When I write article I want to put working code examples for users. Let's say I write about difference between IEC and SI notation of memory (KB, MB, GB, TB and KiB, MiB, GiB, TiB). I have made AJAX POST request which takes value in Bytes and then converts it to SI and IEC values and then populates fields with converted values. You can see the article and code example in the red at the picture bellow. But this is how I cheated inside the article template. I used the current URL to check if it is the URL which talks about the byte notation then I show the code. Last code line loads the article itself. {% if unos.url == 'pretvorba-i-razlika-kb-mb-gb-u-kib-mib-gib' %} <script type='text/javascript' src='https://code.jquery.com/jquery-1.8.2.js'></script> <script type="text/javascript"> $(document).ready(function() { $("#button").click(function() { var input_string = $("#forminput").val(); $.ajax({ url : "konvertor/", type : "POST", dataType: "json", data : { client_response : input_string, csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function(json) { $('#KiB').html( 'kibiBajti: ' + json.KiB + ' KiB'); $('#KB').html( 'kiloBajti: ' + json.KB + ' KB'); $('#RKB').html( json.RKB); $('#MiB').html( 'mebiBajti: … -
Why I am getting RelatedObjectDoesNotExist when I add the object in the view instead of form?
Getting error from my Model def clean RelatedObjectDoesNotExist during the clean in model def clean(self): model = self.__class__ if self.extra and (self.is_active == True) and model.objects.filter(extra=self.extra, lease__is_active=True).exclude(id=self.id).count() > 0: raise ValidationError('Extra has active lease already, Terminate existing one prior to new assignment '.format(self.extra)) however it clearly does exist since even it is not in the form but I added it in the view what could be the reason? What is my way out if I want to keep the clean validation in model since I use it also in other places? This is my model: class LeaseExtra(CommonInfo): version = IntegerVersionField( ) extra = models.ForeignKey(Extra,on_delete=models.PROTECT) lease = models.ForeignKey(Lease,on_delete=models.PROTECT) is_included = models.BooleanField(default=True) def clean(self): model = self.__class__ if self.extra and (self.is_active == True) and model.objects.filter(extra=self.extra, lease__is_active=True).exclude(id=self.id).count() > 0: raise ValidationError('Extra has active lease already, Terminate existing one prior to new assignment '.format(self.extra)) def save(self, *args, **kwargs): self.full_clean() return super(LeaseExtra, self).save(*args, **kwargs) my view looks like this @login_required def extra_lease_new(request,pk,uri): logger = logging.getLogger(__name__) extra1 = get_object_or_404(Extra, pk=pk) title = 'Add New Lease to Extra' uri = _get_redirect_url(request, uri) if request.method == "POST": form = ExtraLeaseForm(request.POST) if form.is_valid(): extra = form.save(commit=False) extra.extra = extra1 extra.save() messages.add_message(request, messages.SUCCESS, str(extra.id) + "-SUCCESS Object created successfully") return … -
declare variable in if else block in django framework
I am doing a conditional block in loop django template , but unable to find exact answer for this. Please consider my code here, {% for data in app_data %} {% if forloop.counter == 1 %} {% declare_some_variable = 'hello' %} {% else %} {% declare_some_variable = 'bye' %} {% endif %} {{ declare_some_variable }} {{ data.name }} {% endfor %} This is what I want. But it does not work. -
Should I use template tags or JavaScript
I have a website that provides distance and speed data and the user can specify which units they want the data to be displayed in. Their user preferences are stored in a user profile table. Currently the data is stored in meters and meters per second in the database. When it comes to displaying the data to the user is it better to use a template tag to convert each piece of data into the correct units or use a template tag once to return the convertipn factor and then use JavaScript to convert each piece of data. Currently there the template has 20 data points that need converting but that could grow. -
Django CBV - How can I check a user's custom attributes to allow access to a view
I'm having a problem when checking custom attributes of a user to allow access to the view. Lets suppose I just want to allow access to the users that have activated in their userprofile the self_store option. When i use function views is very easy i put this in the beginning of the view and works fine if not request.user.is_authenticated(): return redirect('auth_login') if not request.user.userprofile.self_store: return do_something_here Well like i said is very easy to use and do different things for different options activated or not in my userprofile But i cant find the way to do this in class based views, if i want to allow access to the users that have activated the self_store option in the usersprofile how can i do for example in this updateview class ClientUpdateView(UpdateView): model = Client template_name = "clients/update.html" pk_url_kwarg = 'client_id' fields = [ 'first_name', 'last_name', 'email', 'phone', 'phone_2', 'address', ] I can use logginrequired mixin perfect but i want to check like i said custom users properties that i use in the userprofile. The check that i need to make is something like the PermissionRequired Mixin but for the attributes in the userprofile. -
Django Rest Framework - nested objects not being generated properly
I am trying to implement simple api in Django Rest Framework. I have following models in models.py: class Entry(BaseModel): company_name = models.CharField(max_length=256, null=True, blank=True) first_name = models.CharField(null=True, default=None, max_length=32) last_name = models.CharField(null=True, default=None, max_length=32) code = models.CharField(null=True, default=None, max_length=12) class Meta: db_table = 'entry' class Admin(admin.ModelAdmin): list_display = ('company_name', 'code') list_display_links = ('company_name', ) ordering = ('-created',) class EntryContactData(BaseModel): entry = models.ForeignKey(Entry, related_name='contact') email = models.CharField(max_length=256, null=True, blank=True) website = models.CharField(max_length=64, null=True, blank=True) phone = models.CharField(max_length=64, null=True, blank=True) My API serializers.py: from django.contrib.auth.models import User, Group from rest_framework import serializers from core.models import Entry, EntryContactData class EntryContactSerializer(serializers.ModelSerializer): class Meta: model = EntryContactData fields = ('uuid', 'email', 'website', 'phone') class EntrySerializer(serializers.ModelSerializer): contact = EntryContactSerializer(many=False, read_only=True) class Meta: model = Entry fields = ('uuid', 'company_name', 'first_name', 'last_name', 'contact') And my API views: from core.models import Entry from .serializers import EntrySerializer class EntryViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving users. """ queryset = Entry.objects.all() def retrieve(self, request, pk=None): queryset = Entry.objects.all() entry = get_object_or_404(queryset, code=pk) serializer = EntrySerializer(entry, context={'request': request}) return Response(serializer.data) When I want to retrieve single entry its contact field is empty: { "uuid": "e6818508-a172-44e1-b927-3c087d2f9773", "company_name": "COMPANY NAME", "first_name": "FIRSTNAME", "last_name": "LASTTNAME", "contact": {} } So it doesn't contain … -
Django Template: If Variable doesn't exist do some stuff
I am using the following Django template code which is working perfectly: {% for details in teamsremaining %} <tr> <TD class="col-lg-1 col-md-1 col-sm-1 col-xs-1" ><img src="/static/straightred/images/smalllogo/{{details.teamname}}SmallLogo.svg" alt="" width="22" height="22"/>&nbsp;{{details.teamname}}</TD> </tr> {% endfor %} However, on some occasions there will be NO teams remaining so the for loop will not run. If this is the case I would like to have: <tr> <TD class="col-lg-1 col-md-1 col-sm-1 col-xs-1" >NO TEAMS REMAINING.</TD> </tr> I thought I could just use the {% if NOT teamsremaining } code here {% endif %} but had no joy. Any help would be appreciated. -
Loading content issues in child Layout in Django using jinjer
I am using below two code 1) test.html with below given code {% extends "extend_layout.html" %} <!DOCTYPE html> <title>This is Title</title> <h1>This is the header</h1> {% include 'include_layout.html' %} <h2>This is the header</h2> {% block content %} <p>THis is the part that will be added to the extend section</p> {% endblock %} =================================== Here is the second file 2) extend_layout.html <!DOCTYPE html> <div> {% block content %} {% endblock %} </div> The output that gets printed on browser after I run my project is "THis is the part that will be added to the extend section" I am not able to see other parts like title and header that I places inside test.html. Can anyone please explain where am I going wrong or give me some knowledge regarding the same -
Why won't my link navigate to the page that I want upon clicking it?
In Chrome, I must manually type http://127.0.0.1:8000/music/1/ in order to get to the page that I want. (I want to go to page 1). However, When I try to click the link that I thought would take me to where I want in http://127.0.0.1:8000/music, for example, Red. It takes me to that error page: Here's my views.py: from django.http import HttpResponse from django.shortcuts import loader from .models import Album def index(request): all_albums = Album.objects.all() template = loader.get_template('music/index.html') context = { 'all_albums': all_albums, } return HttpResponse(template.render(context, request)) def detail(request, album_id): return HttpResponse("<h2>Details for album id: " + str(album_id) + "</h2>") Here's my urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name = 'detail'), ] Here's my `index.html {% if all_albums %} <!-- Will be true as long as it has at least 1 album --> <h3>Here are all my albums</h3> <ul> {% for album in all_albums %} <li><a href="/music/id/{{ album.id }}">{{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} -
SelectDateWidget: substitute user's input
Django 1.11 This is how SelectDateWidget looks like: General problem is: when a user inputs a day which does not exist, s/he receives a validation error "Enter a valid date" I want to prevent it and in case of such situation just substitute the user's day with the last day of the month: def ceil_day(year, month, day): __, number_of_days_in_month = calendar.monthrange(year, month) return min(day, number_of_days_in_month) In the code below I have put two breakpoints. class FrameDateForm(ModelForm): def clean_from_date(self): return self.cleaned_data.get("from_date") # Breakpoint 1 def clean(self): return super(FrameDateForm, self).clean() # Breakpoint 2 class Meta: model = FrameDate exclude = [] years = range(1800, datetime.datetime.now().year + 1) widgets = { 'frame': forms.HiddenInput(), 'from_date': forms.SelectDateWidget(years=years), } When I input, say, February, 28, 1981, the program stops at breakpoint 1. When I input February, 31, 1981, the program stops at breakpoint 2. Well, could you help me understand: Why in case of such error the program doesn't stop at breakpoint 1? Should I really use my function in clean method? Or where? -
Django database structure for media library app
I am trying to create a media library app with django. For all the media (document, audio, video, image) I have created a structure as below : #models.py class Media(models.Model): title = models.CharField(unique = True, max_length=200) slug = models.SlugField(editable=False) class Meta: abstract = True class ModelImage(Media): file = models.ImageField(upload_to=get_qualified_path) #ModelDocument, ModelAudio, ModelVideo are extending from Media base too... However, for an issue on the admin site, now I decided to change my structure as: #models.py class Media(models.Model): title = models.CharField(unique = True, max_length=200) excerpt = RichTextField(config_name = 'extralight', blank=True, null=True) description = RichTextField(config_name = 'simple', blank=True, null=True) file = models.FileField(upload_to=get_qualified_path, blank=True, null=True) file_type = models.Charfield() Now I have only one table for four types of file. This way is better on the admin site. I want to ask if my second choice of model declaration has disadvantages compared to first choice. ( speed vs... ) Thank you. -
Django Apache only show It's works page
I just learned Django and was able to create a simple web app. I am trying to deploy Django App in VPS with Debian 7.0. I am using Python 2.7, Apache 2, libapache2-mod-wsgi and Django 1.11.2. All went well until I accessed the domain server and only displayed the "It's works" page. This is 000-default.conf file: <VirtualHost *:80> ServerName serverededenid-to.cloud.revoluz.io ServerAdmin webmaster@serverededenid-to.cloud.revoluz.io Alias /static /var/www/static-root <Directory /var/www/static-root> Require all granted </Directory> Alias /media /var/www/media-root <Directory /var/www/media-root> Require all granted </Directory> <Directory /var/www/venv/src/cfehome> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess cfehome python-path=/var/www/venv/src/:/var/www/venv/lib/python2.7/site-packages WSGIProcessGroup cfehome WSGIScriptAlias / /var/www/venv/src/cfehome/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Any body can help me? -
How can I change media root of photologue in Django
I am trying to deploy a project on Heroku, the build is successful. Here's the build log -----> Python app detected -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 73 static files copied to '/tmp/build_0e164445076c2ad03a67e962b1108c5b/static'. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 54.7M -----> Launching... Released v7 https://odyssy.herokuapp.com/ deployed to Heroku There are no errors in build log but the app is not working. When I run heroku run python manage.py syncdb I face this error mkdir(name, mode) OSError: [Errno 30] Read-only file system: '/media' The app is successfully running locally. This app uses photologue. When I run this locally a folder named "media" is created outside of the app directory, and this is also happening in heroku but heroku doesn't allow creating folders manually in root directory. Is there any way to fix this? Can I change the address of media folder in Photologue? -
Django REST + Angular
Want to use this chain (Angular 2, not AngularJS) but not quite understand how exactly should it work on production. Tutorials and simple logic show 2 variants: 1) Separate application servers, for example apache <--> angular-4-on-top-of-webpack-or-smth <--> django-on-top-of-gunicorn 2) "Folder-style" project separation, like project-folder angular-folder ... django-folder ... (some config-magic to make it work) Does somebody have working boilerplate of such application? (everything I saw was outdated) Can someone show right path where to start? -
AttributeError: module 'app_name.tasks' has no attribute 'celery' Django
I can't get Celery to work on Django. When I run the worker like this: celery worker -A app_name.tasks -l INFO I receive this error: AttributeError: module 'app_name.tasks' has no attribute 'celery' This is celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('app_name', broker='amqp://',backend='amqp://',include=['proj.tasks']) # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() CELERY_RESULT_BACKEND = 'django-db' @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) This is the init file in proj/proj from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] finally this is tasks.py in proj/app_name from __future__ import absolute_import, unicode_literals from celery import Celery, shared_task @shared_task def add(x, y): return x + y This is the structure of my Django project: proj/ proj/__init__.py proj/settings.py proj/celery.py proj/app_name/tasks.py And I'm following this … -
SelectDateWidget: substitute day in case of wrong day
Django 1.11 The problem: if day is absent in a month, the user gets validation error: "Enter a valid date". Before this validation error occurred, I'd like to use this function: def ceil_day(year, month, day): __weekday, number_of_days_in_month = calendar.monthrange(year, month) return min(day, number_of_days_in_month) In other words, I'd like to substitute the date: if a user input a non-existing day, let it be the last day of that very month. Could you help me understand how to do that. class FrameDateForm(ModelForm): class Meta: model = FrameDate exclude = [] years = range(1800, datetime.datetime.now().year + 1) widgets = { 'frame': forms.HiddenInput(), 'from_date': forms.SelectDateWidget(years=years), 'through_date': forms.SelectDateWidget(years=years) } -
Django custom decorator not wrapping
I'm trying to create a custom decorator in Django and apply it to a class based view in the URLs file. This is the decorator in decorators.py. It uses functools. I'm not able to get the wrapper function to execute the second log command. def user_isnt_blocked(func): logger.info("user_not_blocked call " + func.__name__) @wraps(func) def wrapper(self, request, *args, **kwargs): logger.info("user_not_blocked wrapper") return func(self, request, *args, **kwargs) return wrapper Right now, the decorator does nothing as I'm first trying to figure out how to get it to do the wrapping part - i.e. it is not logging the "user_not_blocked wrapper". The initial call is logged - it does print out "user_not_blocked call". The pertinent url pattern for the class-based view is coded as follows: urlpatterns = [ url(r'update-profile/$', user_blocked(views.UpdateProfile.as_view()), name="update-profile"),] The class-based view is as follows: class UpdateProfile(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(UpdateProfile, self).dispatch(request, *args, **kwargs) def get(self, request): return super(UpdateProfile, self).dispatch(request, *args, **kwargs) def post(self, request): ... Any help with what I'm doing wrong would be appreciated. -
SelectDateWidget and usability
Django 1.11 Could you have a look at the picture and the code below. SelectDateWidget seems interesting. But if a user inputs, say, 31st of February, they will get a validation error: "Enter a valid date". This is not user friendly, I would say. This ruins the whole idea of the widget: we should either give them a calendar or not to tell them off for selecting what we ourselves offered them. If we use a calendar, we don't need this SelectDateWidget at all. But I like the widget. I think maybe at the server side we could substitute, for example, 29-31 of February with 28/29 depending the year. That would suit me perfectly. Anyway Could you help me understand how to make SelectDateWidget more user friendly. class FrameDateForm(ModelForm): class Meta: model = FrameDate exclude = [] years = range(1800, 2015) widgets = { 'from_date': forms.SelectDateWidget(years=years), 'through_date': forms.SelectDateWidget(years=years) } -
How to send json serialize data from a form to ajax using django
Currently, I'm sending the data via code in this way and it's working but how can I send the entire form in json? Code : $.ajax({ url : window.location.href, // the endpoint,commonly same url type : "POST", // http method data : { csrfmiddlewaretoken : csrftoken, email : email, password : password, username : username, dob : dob, }, // data sent with the post request I want to send and retrieve everything including csrfmiddlewaretoken using formdata json. I have tried something similar to that : var formData = new FormData($('#my_form'); formData.append('csrfmiddlewaretoken', '{{ csrf_token }}'); $.ajax({ url : window.location.href, // the endpoint,commonly same url type : "POST", // http method data : formData, // data sent with the post request But, this does not work for some reason. How can I get it to work? -
Value of Memcache location on PythonAnyWhere
What LOCATION should I point Memcached to after deployment on pythonanywhere server? For local I am using this setting and things are working fine. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } I need to change 'LOCATION' to replace localhost. Any guidance? -
Why isn't the following Python script installing libraries using pip?
I am trying to automate creating a project in Django with the following script. import os, sys, pip, virtualenv directory = sys.argv[1] if not os.path.exists(directory): os.makedirs(directory) new_dir = os.path.join(os.getcwd(), directory) os.chdir(new_dir) if not os.path.exists('venv'): os.makedirs('venv') venv_dir = os.path.join(os.getcwd(), "venv") virtualenv.create_environment(venv_dir) activate_script = os.path.join(venv_dir, "bin", "activate_this.py") execfile(activate_script, dict(__file__=activate_script)) pip.main(["install", "--prefix", venv_dir, "pytz"]) The last line installs django, but doesn't install pytz. It says that pytz is already installed, but when I activate the venv, start python from within the venv and import pytz, it cannot load it. What am I doing wrong here? -
URL pattern in django with first part as variable
Its is easy to create URL pattern as below url(r'^member/(?P<member_name>[a-z]+)/$', views.get_member, name='get_member'), this will generate the complete url as http://example.com/member/john/ but I want to make urls like http://example.com/john/. What URL pattern should I make for this? If I do url(r'^(?P<member_name>[a-z]+)/$', views.get_member, name='get_member'), it will start matching all other urls in it. -
Django unable delete form with data shown
i have created a delete function for my forms but it can only delete if i did not display out my information. However if i try to display the information out on the delete page, the delete function wouldn't work. i think because when i display the information out, the form isn't valid, hence unable to delete the object. My views.py def servicing_entry_delete(request, serv_entry_id): delete_object = get_object_or_404(serv_entry, id=serv_entry_id) if request.method == 'POST': form = Delete_Flying_form(request.POST, instance=delete_object) if form.is_valid(): # checks CSRF delete_object.delete() return HttpResponseRedirect(reversed('AC2058:servicing_entry')) # wherever to go after deleting else: form = Delete_Flying_form(instance=delete_object) return render(request, 'AC2058/servicing_entry_delete.html', {'form':form}) My forms.py class Delete_Flying_form(forms.ModelForm): class Meta: model = serv_entry fields = ('Servicing_Type', 'Time', 'Date','Ic_Clear_Name','Ic_Clear_Time','Ic_Clear_Date') My deleteconfirmation.html {% extends 'hello/base.html' %} {% block content %} <h1>Delete Servicing Entry</h1> <p>Are you sure you want to delete this Entry: </p> {{ form }} <form action="" method="POST"> {% csrf_token %} <input type="submit" action="" value="Yes, delete this Entry." /> </form> {% endblock %} Without the {{ form }}, i am able to delete the object smoothly but not being able to display any information. However if i try to display, like this is there anyway if i could display this few fields and still delete successfully? My …