Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Swagger Custom Auth Headers in "Try it Out" section
I was wondering if it was possible to add custom auth headers for each "Try It Out" section of the docs produced by django-rest-swagger? I have setup custom token authentication for my REST API and just need a custom header specified for each request produced by the "Try it out!" button. -
_wrapped_view() takes at least 1 argument (0 given) when cash view in django
Error in first line of: @cache_page(3600) def get_big_items_html(): .... return 'some html string' Here is my settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } -
Switch between two objects' values - Django
I have this model: class Person(models.Model) id = IntegerField() place_in_line = IntegerField() I want to avoid race conditions in this code: @transaction.atomic def switch(person1, person2) place1 = person1.place_in_line place2 = person2.place_in_line person1.place_in_line = place2 person2.place_in_line = place1 person1.save() person2.save() I have tried using F or Case expressions, but they all refer to themselves and not to other arbitrary field... thanks. -
Elastic beanstalk django deployment wsgi error repeatedly
I am trying to deploy a simple django application on elastic beanstalk and getting an internal server error. When I check the logs, I see the following error [Sun Dec 04 10:24:24.854440 2016] [:warn] [pid 4022] mod_wsgi: Compiled for Python/2.7.10. [Sun Dec 04 10:24:24.854445 2016] [:warn] [pid 4022] mod_wsgi: Runtime using Python/2.7.12. [Sun Dec 04 10:24:24.856303 2016] [mpm_prefork:notice] [pid 4022] AH00163: Apache/2.4.23 (Amazon) mod_wsgi/3.5 Python/2.7.12 configured -- resuming normal operations [Sun Dec 04 10:24:24.856316 2016] [core:notice] [pid 4022] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Sun Dec 04 10:24:27.609892 2016] [:error] [pid 4027] [remote 127.0.0.1:27067] mod_wsgi (pid=4027): Target WSGI script '/opt/python/current/app/twittrends/twittrends/wsgi.py' cannot be loaded as Python module. [Sun Dec 04 10:24:27.609919 2016] [:error] [pid 4027] [remote 127.0.0.1:27067] mod_wsgi (pid=4027): Exception occurred processing WSGI script '/opt/python/current/app/twittrends/twittrends/wsgi.py'. [Sun Dec 04 10:24:27.609948 2016] [:error] [pid 4027] [remote 127.0.0.1:27067] Traceback (most recent call last): [Sun Dec 04 10:24:27.609963 2016] [:error] [pid 4027] [remote 127.0.0.1:27067] File "/opt/python/current/app/twittrends/twittrends/wsgi.py", line 16, in <module> [Sun Dec 04 10:24:27.610012 2016] [:error] [pid 4027] [remote 127.0.0.1:27067] application = get_wsgi_application() [Sun Dec 04 10:24:27.610022 2016] [:error] [pid 4027] [remote 127.0.0.1:27067] File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application This is my django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: twittrends/wsgi.py I can't figure out the problem. It does … -
Get changes done to model instance in a single revision
Using: Django 1.10 django-reversion 2.0.8 djangorestframework 3.4.6 Hi, I read that django-reversion stores only changes done to model instance. However, when I lookup versions for a given model instance I see that the field serialized_data in revisions.model.Version has all the fields of the model stored in it. Is it because I use serializers.ModelSerializer to make partial updates to the model instance and save the data using serializers.ModelSerializer.save() ? How can I remedy this so I can quickly check what changes were done to my instance. This is related to my other question about displaying a changelog history for a given model instance: Show change log history for model instance using django-reversion -
Django query ManyToMany field with thorugh
I have tables like this: class Ingredient(models.Model): name = models.CharField(max_length=20, blank=False, null=False) class IngredientHistory(models.Model): ingredient = models.ForeignKey(Ingredient, blank=False, null=False) product = models.ForeignKey('Product', blank=False, null=False) date = models.DateField(auto_now_add=True) quantity = models.PositiveIntegerField(blank=False, default=1) class Product(models.Model): ingredients = models.ManyToManyField(Ingredient, through=IngredientHistory, through_fields=('product', 'ingredient'), related_name='products') In IngredientHistory I have a history of quantity of ingredients in a product, I want to make a query that gets me the last ingredients of each product, it means if in IngredientHistory I have 6 rows which just point to Ingredient with ids [1, 2] my result must be the quantity of ingredients [1, 2] for the product. This is a simple and naive solution for queries that I want: p = Product.objects.get(pk=1) q = p.ingredients.all().values('id').annotate(max_date='ingredienthistory__date') for i in q: ingredient = p.ingredients.all().filter(id=i.id, ingredienthistory__date=i.second) # do something with ingredient I am looking for a one-line command that gets me all ingredient of a product as above. I am using django-1.10 and postgresql-1.9. -
Show change log history for model instance using django-reversion
Using: django 1.10 reversion 2.0.8. My question is how to show a nice list of changes done to given model instance. By that I mean that the user can quickly see a list of all the changes (new values for fields) in all revisions. He doesn't need o see all the fields only the new values of the changed ones. So I found that a good tool for storing changes is django-reversion. However, I cannot find a solution for my problem which as I mentioned is to show a nice change-log history for a given model instance. I found solution that can compare two revisions django-reversion-compare, but that is not what I am looking for. Maybe there is a better tool for that ? -
Python manage.py runserver returns nothing and ./manage.py runserver returns an error
I was working with Django today. When I ran python manage.py runserver it returns nothing and when I ran ./manage.py runserver I get the following error. ./manage.py: line 7: syntax error near unexpected token "DJANGO_SETTINGS_MODULE",' ./manage.py: line 7: ` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "instaPG.settings")' I looked for similar issues but didn't find any. Thanks in advance. -
Jquery slider django
I would like to use a django value in this script. The slider is working, but the slider is not showing in my html file when I put this: change: function( event, ui ) { $('#id_QA1').value(ui.value); } I want to store the answer from the form field 'QA1', retrieved by a rangeslider, in my database. Any help is appreciated! form: slider.html <div class="slider"> <span class="amount" > </span> <span id="amount" type="text" value="{{ form.QA1 }}"></span> <div class="slider-range"></div> Jquery: <script> $(document).ready(function() { $(".slider").each(function() { $this = $(this); $(".slider-range", $this).slider({ range: "min", min: 0, max: 100, values: [30], slide: function( event, ui ) { $(this).parent().find(".amount").html( + ui.values[ 0 ]); } change: function( event, ui ) { $('#id_QA1').value(ui.value); } }); $(".amount").html( + $(".slider-range").slider("values", 0 )); }); }); </script> -
Django Tables2 duplicated results
Django tables2 seems to be showing duplicated results for the top row and the last row. E.g. Database records shows: ID|Name|User 1|test1|1 2|test2|1 However table shown on the website is: ID|Name|User 2|test2|1 1|test1|1 2|test2|1 Not sure why this is happening. Could you please help? views.py class ReportsView(ListView): model = Reports template_name = 'reports.html' def get_context_data(self, **kwargs): context = super(ReportsView, self).get_context_data(**kwargs) login_user = self.request.user context['reports_table'] = ReportsTable(Reports.objects.filter(user=login_user)) return context models.py class Reports(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=30) description = models.CharField(max_length=50) def __str__(self): return self.name def get_absolute_url(self): return reverse('edit_report', kwargs={'pk': self.pk}) tables.py class ReportsTable(tables.Table): class Meta: model = Reports attrs = {'class': 'table table-bordered'} reports.html {% load render_table from django_tables2 %} {% render_table reports_table %} -
django aggregate and filter
I'm going to convert this sql to django commands: SELECT core.id, core.title, core.age_id, core.cat_id, max(date) AS max_date FROM core WHERE core.state = 'ABC' GROUP BY cat_id, age_id I tried this, but not works correctly: Core.objects.values('id', 'title', 'age_id', 'cat_id').filter(state='ABC').annotate( max_date=Max('date')).aggregate(Count('age_id', 'cat_id')) -
ForeignKeyAutocompleteAdmin
Given these two models: class Product(Model): upc = CharField(max_length=96, unique=True) ... class Meta: app_label = 'scrapers' class Order(Model): ... product = ForeignKey('scrapers.Product', related_name='orders', on_delete=models.CASCADE) objects = OrderManager() class Meta: app_label = 'scrapers' And this admin.py: class OrderAdmin(ForeignKeyAutocompleteAdmin): related_search_fields = { 'product': ('upc',) } fields = ('product', 'client', 'completed', 'expires', 'amount', 'filled') admin.site.register(Order, OrderAdmin) Having done collectstatic and declared django_extensions and my app in INSTALLED_APPS. Why am I getting this: [04/Dec/2016 05:54:28] "GET /admin/scrapers/product/foreignkey_autocomplete/?search_fields=upc&app_label=scrapers&model_name=product&q=045496 HTTP/1.1" 302 0 Not Found: /admin/scrapers/product/foreignkey_autocomplete/change/ [04/Dec/2016 05:54:28] "GET /admin/scrapers/product/foreignkey_autocomplete/change/ HTTP/1.1" 404 1875 On input to the input field (box to the left not pk input to the right)? The Product table has millions of rows and the default admin configuration doesn't handle this well so I tried the extensions package solution. I don't see anything in the docs addressing url configuration (I assume this is done when registering with the admin). How can I get this to work? -
how does the registration POST data in django?
I am staring to learn python and django. Currently trying django 1.9 I know the it has build in user model which I can just migrate and use. I also used the simple login it provided which only needs user name and password. The thing is, I tried finding example on how to create the registration I couldn't find much. I found a few which just tells us to insert template and use the build in form in view.py which would output asking user to enter username, password and password confirm. I have no idea where to find how django is passing POST into sqlite and do modifications to inputs passed to the backend. Can someone give me a leading clue or if there's a well documented link? Thanks in advance -
Cannot install Django
I tried to install Django on my laptop but Window PowerShell doesn't recognize the version. I installed python 3.5.2 on my laptop. PS C:\Users\Work> python --version python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + python --version + ~~~~~~ + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
I am trying to send email via Django but the request is not getting processed
The following is the view I wrote, no errors occur but no mail is getting sent to the receiver_email address. def register_user(request): username = request.POST['username'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] receiver_email = request.POST['email'] passwd = generate_passwd() user = User.objects.create_user(username=username,password=passwd,email=email,first_name=first_name,last_name=last_name) res = send_mail("password",passwd,"theanirbanacharya@gmail.com",receiver_email) return HttpResponseRedirect(reverse('polls:login',args=())) What I am doing is generating a random password that I wish to mail to the user ( to the receiver_email ). But when I hit the "register" button nothing happens, the request is not getting processed. -
Request goes to the wrong function in Django
The following is the URL pattern specified in my code. from . import views from django.conf.urls import url urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<uuid>[\w\-]+)/$', views.detail, name='detail'), url(r'^layout/$', views.layout, name='layout'), ] I have three functions specified as def detail(request,uuid) def index(request) def layout(request): However, whenever I type the 'layout' keyword, I get the following error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Aditya Ranganath\PycharmProjects\untitled\untitled1\polls\views.py" in detail 38. path = Attribute[0]['Path'] Exception Type: IndexError at /polls/layout/ Exception Value: list index out of range Which essentially means the request is sent to the wrong function. After debugging it, I have realized that the function goes into the detail function. Kindly let me know why this is happening. Thanks! -
Django - Validation Errors are not showing up - Using forms with ListView
I'm making a website that shows events using a ListView and each event has a sign up form. The form works as long as it passes through the clean_fullname in forms.py without a ValidationError, but when there are validation errors, they don't show up on the form. As long as I put something into the field and submit, it always brings me to the success page, but the form isn't saved to the database if the clean_fullname isn't passed without validation error. I've tried using {{ form.as_p }} rather than only the field and that didn't work either. I'm thinking that it's because I'm using a ListView. forms.py: from django import forms from .models import SignUps, Hours, Events import datetime class SignUpForm(forms.ModelForm): fullname = forms.CharField(label="Full name", widget=forms.TextInput(attrs={'placeholder': 'Full name', 'class': 'form-control'})) class Meta: model = SignUps fields = ['eventname','fullname','ip'] def clean_fullname(self): fullname = self.cleaned_data.get('fullname').title() eventname = self.cleaned_data.get('eventname') try: name = Hours.objects.get(fullname=fullname) except Hours.DoesNotExist: raise forms.ValidationError("Please enter a valid Key Club member's full name as displayed in the hours page.") try: name = SignUps.objects.get(fullname=fullname) except SignUps.DoesNotExist: try: numOfSignUps = SignUps.objects.filter(eventname=eventname).count() except SignUps.DoesNotExist: numOfSignUps = 0 try: event = Events.objects.get(name=eventname) except Events.DoesNotExist: raise forms.ValidationError("Something went wrong. This event does not exist.") try: … -
Running django in a virtualenv with python 3 on OSX
I created a python3 virtual environment but when I'm in my virtualenv and I type: python -V I get: Python 2.7.12 If I want to run my server with command: python manage.py runserver It gives me error: File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: 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? But when I run: python3 manage.py runserver It works perfectly!?! Why does it still want to run python 2 if it's a python 3 environment ? -
Django NoReverMatch at /
I read the book 'Django By Example' and run the examples in chaper7. But the results call "NoReverMatch at /" NoReverseMatch at / Reverse for 'product_detail' with arguments '(5, u'ironman')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<id>[\\d+])/(?P<slug>[-\\w+])/$'] This is the models.py class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) This is the urls.py urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), url(r'^(?P<id>\d+)/(?P<slug>[-\w+])/$', views.product_detail, name='product_detail'), ] This is the views.py def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) return render(request, 'shop/product/detail.html', {'product': product}) And this is … -
Django - passing flatpage.title variable as part of an include
I'm using Django flatpages and trying to pass the title of a flatpage as part of an html include. {% block navbar %} {% include 'navbar.html' with active='{{flatpage.title}}' %} {% endblock %} This is so I can highlight the whereabouts in the navigation bar. <ul class="nav navbar-nav"> <li class="{% if active == 'home' %}active{% endif %}"><a href="{% url 'home' %}">Home</a></li> etc. </ul> It doesn't appear to render correctly. Whereas if I replace {{flatpage.title}} with a hard-coded value ie. 'home' it works just fine. {% block navbar %} {% include 'navbar.html' with active='home' %} {% endblock %} Am I not able to do this? I'm not clear on a way to debug Django templates to check for these values... The way I'm currently checking that the variable is passing the right value is simply to reference {{flatpages.title}} elsewhere, separately in the html - which appears to render the correct 'home' value I'd expect. <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="{% if active == 'home' %}active{% endif %}"><a href="{% url 'home' %}">Home</a></li> {{flatpage.title}} etc. </ul> </div> -
Django Web Application Design Guidance
I am looking for some advice before I start on a new project. I am creating a Web Application using Django 1.10. I have experience with Django and creating general "content-based" websites with it. However, since this project is going to be a web-based application, I plan on doing more "complex" things than just rendering HTML templates and doing some basic CRUD operations. When I say "complex" things, the most specific example I can give at this point is to leverage more asynchronous requests so my web-application can remain responsive to the user and provide that "real-time" experience that comes with an application that might be installed on their local machine or whatever. Plus, since this is a web-application and not just a website, the project is definitely going to be more data-driven which could potentially mean requesting large amounts of data that would be best served in say a paginated manner, etc. So, my though was this.....Since I am familiar with Django and have read such good things about the Django REST Framework, I could create a RESTful API to perform all of my CRUD operations and basically interface with my web application's core database. At that point, I … -
Local variable referenced before assignment Django
I'm fairly new to Django and am currently getting an error when trying to get data from my database for the first time. My app is called restaurants and I have model with this name as well. Whenever I try and load the /restaurants/ page I am getting the error that the local variable has been referenced before assignment. The 4th line is being referenced in the error. from django.http import HttpResponse from .models import restaurants def index(request): all_sites = restaurants.objects.all() html = '' for restaurants in all_sites: url = '/restaurants/' + str(restaurants.id) + '/' html += '<a href="' + url +'">' + restaurants.site_title + '</a><br>' return HttpResponse(html) def detail(request, site_id): return HttpResponse("<h2>This is a detailed view for site ID:" + str(site_id) + "</h2>") -
AttributeError in django-shopify-sync
I'm getting an AttributeError when running a command with the django-shopify-sync package for the first time: After the initially setting up the package, I'm trying to run: products = Product.objects.sync_all(query="Foo bar",session=sess) The raised error is: in sync_one defaults.update({'session': shopify_resource.session.model}) AttributeError: 'Session' object has no attribute 'model' The error flows back to base.py. The applicable section of code in base.py: # Synchronise instance. try: instance, created = self.update_or_create(id=shopify_resource.id, defaults=defaults) except (utils.IntegrityError, Session.DoesNotExist): # This means that there needs to be the session in the defaults if isinstance(shopify_resource.session, ShopifySession): defaults.update({'session': shopify_resource.session.model}) else: defaults.update({'session': shopify_resource.session}) instance, created = self.update_or_create( id=shopify_resource.id, defaults=defaults, ) I'm not yet familiar enough with the shopify resource package to understand what may be the problem. I can't tell if it is something I may have set up wrong or it it is something poorly handled in the package itself. -
jsGrid loadData not being called
So I am really struggling getting jsGrid up and running with my Django site, specifically using a controller to load the data in the table from an ajax request. It wasn't working, so I set up this very basic configuration just to see what was going on with my loadData function in my controller. Using the below configuration, the only thing that gets printed in the console is "In Script." so it's obviously not calling loadData within the controller. Please, what am I missing here? It has to be something silly. <script> console.log("In Script.") $("#demos-js-grid").jsGrid({ onDataLoading: function(args) { console.log("On Data loading.") }, width: "100%", height: "100%", inserting: true, editing: true, sorting: true, autoLoad: true, controller: { loadData: function(filter) { console.log("loadData being called.."); } }, fields: [ { name: "Client Status", type: "text", width: 50 }, { name: "Bee Status", type: "text", width: 50 }, { name: "Store Status", type: "text", width: 50 }, { name: "Region", type: "text", width: 100 }, { name: "Chain", type: "text", width: 100 }, { name: "Store", type: "text", width: 150 }, ] }); </script> -
Saving to UserProfile model doesn't stick
I'm using Django with Django_Rest_Framework and whenever I try to make a change to the UserProfile associated with a User, it doesn't persist to the database. Here are my applicable models (using Django's User model): class UserProfile(models.Model): STUDENT = 'S' INSTRUCTOR = 'I' ADMIN = 'A' ROLE_CHOICES = ( (STUDENT, 'Student'), (INSTRUCTOR, 'Instructor'), (ADMIN, 'Admin'), ) user = models.OneToOneField(User) role = models.CharField(max_length=1, choices=ROLE_CHOICES, default=STUDENT) class Meta: db_table = 'UserProfile' def create_user_profile(sender, instance, created, **kwargs): """ Create a user profile with a role of `instructor` if the email address is example.com or ex.com. Otherwise set the role to `student`. """ if created: role = UserProfile.STUDENT domain = instance.username.split('@')[-1] if domain in ("example.com", "ex.com"): role = UserProfile.INSTRUCTOR UserProfile.objects.create(user=instance, role=role) # Every time a user is created, the above method runs. post_save.connect(create_user_profile, sender=User) Here is my UserSerializer: from rest_framework import serializers from rest_auth.serializers import UserDetailsSerializer from rest_auth.registration.serializers import RegisterSerializer class UserSerializer(UserDetailsSerializer): role = serializers.CharField(source="userprofile.role") class Meta: model = User fields = UserDetailsSerializer.Meta.fields + ('role',) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) role = profile_data.get('role') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data and role: profile.role = role profile.save() # Note: I've checked that both …