Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to combine two or more ModelAdmins in django admin
There are two custom ModelAdmins provided by contrib projects which I'd like to combine on a single model's administrative interface. How do I combine two or more ModelAdmins on a single model such that they both apply to the same administrative interface? My particular scenario: I'm building a gis app using geodjango which keeps track of locations. My data model uses the models.PointField() type provided by geodjango. In order to be able to edit the location in the admin panel I registered my model using the admin.OSMGeoAdmin admin model. admin.site.register(Prospect, admin.OSMGeoAdmin) This now shows me a graphical location picker with a map, which is what I want. However, I want to import and export these objects. Typically I would use the import_export ModelAdmin for this, which looks like this: class ProspectResource(resources.ModelResource): class Meta: model = Prospect class ProspectIEAdmin(ImportExportModelAdmin): resource_class = ProspectResource admin.site.register(Prospect, admin.ProspectIEAdmin) How do I combine these two ModelAdmins on the same model so that I can both set the location using the graphical map tool AND import and export the objects? If I ago ahead and attempt to register them both like so: admin.site.register(Prospect, admin.OSMGeoAdmin) admin.site.register(Prospect, admin.ProspectIEAdmin) I get the following error: AttributeError: module 'django.contrib.gis.admin' has no attribute β¦ -
EmptyPage Error in Django pagination
I am tring to make digg-style pagination in my django application. I used custom templatetags. First and last pages didnt work and I dont understand how to fix that. However other pages work fine. Where I did mistake? First page Error: EmptyPage: That page number is less than 1 File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\paginator.py", line 38, in validate_number raise EmptyPage('That page number is less than 1') django.core.paginator.EmptyPage: That page number is less than 1 Last page Error: EmptyPage That page contains no results File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\paginator.py", line 43, in validate_number raise EmptyPage('That page contains no results') django.core.paginator.EmptyPage: That page contains no results views.py def project_list(request): objects = Project.objects.filter(status='public', membership__user=request.user) paginator = Paginator(objects, 1) page = request.GET.get('page') try: projects = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. projects = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. projects = paginator.page(paginator.num_pages) return render(request, 'project/project_list.html', {'projects': projects, 'paginator': paginator}) pagination.py from django import template register = template.Library() LEADING_PAGE_RANGE_DISPLAYED = TRAILING_PAGE_RANGE_DISPLAYED = 5 LEADING_PAGE_RANGE = TRAILING_PAGE_RANGE = 4 NUM_PAGES_OUTSIDE_RANGE = 2 ADJACENT_PAGES = 2 def custom_paginator(context): paginator = context['paginator'] page_obj = context['projects'] pages = paginator.num_pages page = page_obj.number in_leading_range = in_trailing_range = False β¦ -
Cannot download images from django to android using volley
I am trying to download images from django to android using volley. But I cannot load images in the ListView. I ran the server and tried to load the image, but image is not loading in NetworkImageView. MainActivity.java package com.example.lenovo.myapplication; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG=MainActivity.class.getSimpleName(); private List<FeedData> feedData; private ListView listView; private CustomListProject adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=(ListView)findViewById(R.id.listView); feedData=new ArrayList<FeedData>(); setData(); adapter = new CustomListProject(this,feedData); listView.setAdapter(adapter); } public void setData() { FeedData f1=new FeedData("Sree Parvathy","Palakkad","http://127.0.0.1:8000/photos/a.jpg"); FeedData f2=new FeedData("Prassanna Lakshmi","Palakkad","http://127.0.0.1:8000/photos/b.jpg"); FeedData f3= new FeedData("Top in town","Palakkad","http://127.0.0.1:8000/photos/c.png"); feedData.add(f1); feedData.add(f2); feedData.add(f3); } } FeedData.java package com.example.lenovo.myapplication; public class FeedData { private String title,place, thumbnail; public FeedData() { } public FeedData(String title, String place, String thumbnail) { this.title=title; this.place=place; this.thumbnail=thumbnail; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnailUrl) { this.thumbnail = thumbnailUrl; } public void setPlace(String place) { this.place=place; } public String getPlace() { return place; } } CustomListProject.java package com.example.lenovo.myapplication; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.widget.BaseAdapter; import android.view.View; β¦ -
Add Image for automated correspondence email
I am looking to add a avatar image for noreply email for automated correspondence in Django. How can I do it? -
django-background-tasks migrations on heroku
I am trying to migrate dajngo-background-tasks on my app hosted in heroku. Migrations worked normally locally but when I tried to run: heroku run python manage.py migrate It returned 'No migrations to apply' I've added 'background_task', to INSTALLED_APPS I ran heroku run python manage.py makemigrations background_task And it created the required migrations I even tried running heroku run python manage.py migrate background_task causing "CommandError: App 'background_task' does not have migrations." PS: One thing I noticed is that when running migrate locally I get this text Apply all migrations: admin, background_task, auth, contenttypes, sessions, <my_app> But when I run it on the server I get Apply all migrations: admin, auth, contenttypes, sessions, <my_app> Every form of help will be very much appreciated! -
Print price of the item corresponding to different sizes and if there is no variation in size then print the base price
In my models I have created a new class variation in which I added 3 variations to my first product like small, medium, large. but what I want is to pass the price according to variation and if some product do not have any variation then it must pass the base price saved earlier in the database. Cart App views.py from django.shortcuts import render, HttpResponseRedirect from django.core.urlresolvers import reverse # Create your views here. from products.models import Product from .models import Cart, CartItem def view(request): try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {"cart": cart} else: empty_message = "Your Cart is Empty, please keep shopping." context = {"empty": True, "empty_message": empty_message} template = "cart/view.html" return render(request, template, context) def update_cart(request, id): request.session.set_expiry(120000) try: qty = request.GET.get('qty') update_qty = True except: qty = None update_qty = False try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(id=id) except Product.DoesNotExist: pass except: pass cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product) if created: print "yeah" if update_qty and qty: if int(qty) == 0: cart_item.delete() else: cart_item.quantity = qty cart_item.save() else: pass new_total = 0.00 for item β¦ -
How to access inital data in django rest framework serializer
I would like to auto populate some fields in a Serializer (Not a ModelSerializer) I need a method I can hook into, that gives me both access to the data passed in, and the ability to manipulate which fields are shown dynamically (but I can see how to do that from the example in the docs) Essentially, how can I access and manipulate the data that has been passed into the Serializer at it's initialisation. http://www.django-rest-framework.org/api-guide/serializers/#example -
Haystack SearchQuery API
I already know haystack SearchQuery API but i have case i don't know how to handle it if i need to make filter by this criteria [ filter1 ΩAND (filter2 OR filter3)] This ok because i know know many fields which i need to add for OR but now if i have comma string how i can make the same thing for OR clause This my code sqs = SearchQuerySet().models(UserProfile).filter(content=request.POST.get('q', ''))\ .filter(SQ(user_type=1) | SQ(user_type=2)) and this the for loop for country in request.POST['location'].split(','): sqs = sqs.filter_or(SQ(country_name=country)) How can i made the for loop as this .filter(SQ(user_type=1) | SQ(user_type=2)) -
Django issue during migrations - lazy reference
I currently added this model to my app from mainApp.models import modelPatient class modelBodyParts(models.Model): part_name = models.CharField(max_length=1000, unique=False , default="") modelPatient = models.ForeignKey(modelPatient) result = models.CharField(max_length=3000, unique=False , default="") Now the makemigrations and migrate commands give me the following error >>python manage.py makemigrations >>python ./manage.py migrate ValueError: The field interviewApp.modelInterviewAnswers.patients was declared with a lazy reference to 'mainApp.modelpatients', but app 'mainApp' doesn't provide model 'modelpatients' I am not sure what that means. But I do remember that at one point mainApp.modelpatients existed and then it was changed to mainApp.modelpatient which still exists.How do I resolve this issue and why is this showing up ? Any help would be appreciated. -
post list of device id in a group
The design of my api is { "id": "667c476ca953483493afa265e5d500b0", "name": "Home" } This is the result of GET API. In posting, i want the list of devices to be posted. For example, if user want to post devices to Home group, then the url i have designed is /group/group_token/add(/group/667c476ca953483493afa265e5d500b0/add). The data sending format is { "devices":[<device_id1>, <device_id2>] } i.e { "devices":"[5ac41ba7e6ae4628982b2c81c99343a8], [7nu21ba7e6ae4628982b2c81c99343a8]" } Here is my model, serializer and APIView i have done so far class BaseDevice(PolymorphicModel): name = models.CharField(max_length=250, blank=False, null=False) owner = models.ForeignKey(User, blank=False, null=False) token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) group = models.ForeignKey('DeviceGroup', related_name="groups", null=True, blank=True) class Device(BaseDevice): description = models.TextField(blank=True, null=True) class DeviceGroup(models.Model): token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) name = models.CharField(max_length=250, blank=False, null=False) owner = models.ForeignKey(User, blank=False, null=False) class DeviceGroupSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) class Meta: model = DeviceGroup fields = ['id','name'] class DevicesGroupsAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def get_serializer_class(self): if self.request.user.is_staff: return DeviceGroupSerializer def get_object(self, user, token): try: return BaseDevice.objects.filter(owner=user).get(token=token) except ObjectDoesNotExist: return error.RequestedResourceNotFound().as_response() def get(self, request, format=None): reply = {} try: groups = DeviceGroup.objects.filter(owner=request.user) reply['data'] = DeviceGroupSerializer(groups, many=True).data except: reply['data'] = [] return Response(reply, status.HTTP_200_OK) def post(self, request, token=None, format=None): device_group_instance = DeviceGroup.objects.get(token=token) for device_token in request.data['devices']: device = Device.objects.get(token=device_token, owner=request.user) device.group = device_group_instance device.save() β¦ -
What are recommeded directives for robots.txt in a Django application?
Currently my django project has following structure. ./ ../ app1/ app2/ django_project manage.py media static secret_stuff and my robots.txt looks something like this: User-agent: * Allow: / Sitemap: mysite.com/sitemaps.xml I want to know following things: What are the recommend directives should i add to my robots.txt file, as django documentation is saying nothing on this topic. How do i stop bots from reaching (indexing) contents of secret_stuff and mysite.com/admin/ directory ? Disallow: /secret_stuff (Is that okay ?) Disallow: /admin (Is that okay ?) -
How to implement Endless pagination without getting an Errno 13 Permission Denied error?
I'am trying to implement endless pagination on my django project but i have an issue that i don't know how to solve. When i include page template as follow in the documentation (http://django-el-pagination.readthedocs.io/en/latest/twitter_pagination.html), I have an errno 13 permission denied. I saw on few other post, they told me to change the directory but i don't know exactly how to do it on Windows. And when I change {% include page_template %} by {% include 'portfolio/art_items.html' %} , I don't have anymore the error. But when I click on "more" it load me the new items and put also load me after the items all the index.html page again. Thanks a lot for your help ! Here my code and the error: Traceback : [Errno 13] Permission denied: u'C:\\Users\\Marion\\Desktop\\myportfolioV3\\myportfolio\\myportfolio\\portfolio\\templates' Index.html <div class=endless_page_template" id="container-arts"> {% include page_template %} {% block js %} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{% static 'portfolio/js/el-pagination.js' %}"></script> <script> $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: 20 }); </script> {% endblock %} </div> art_items.html {% load el_pagination_tags %} {% lazy_paginate 3,6 arts %} {% for art in arts %} <div class="col-md-4 "> <div class="ot-portfolio-item"> <figure class="effect-bubba"> <img src="{{ art.image.url }}" class="img-responsive" /> <figcaption> <h2>{{ art.title }}</h2> <p>{{ art.art_date }}</p> <a href="#" data-toggle="modal" data-target="#Modal-{{ β¦ -
Django Group Permitions-like Field
I would like to know how what is the name of the field and how to use it in django admin groups permitions as i attach in the image below. It looks like a ManytoManyField but it is a lot more user freindly. Thanks in advance. -
Python class/singleton interaction with Django and gunicorn
Implemented a singleton using Method 1 from this question: def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass This works locally when I'm running it locally, but when I deploy it with gunicorn and django-crontabs it appears as if the singleton doesn't hold up and multiple instances of the class are instantiated. I'm wondering if each gunicorn worker spawns a separate instance of the class. In short, I'm asking about the interactions with Python and Django when running a web application with gunicorn. -
Django pagination of filtered results using AJAX
I've been trying to figure this out for days and was unable to find any useful information online. What I am trying to do is paginate objects from my model after filtering them using a drop down menu and supplying the data to python via AJAX. I know where the problem is but I am not sure how to solve it. I have two templates, first one is: entry_index.html: {% extends 'main/base.html' %} <form action="" method="get" accept-charset="utf-8"> <select class="selectpicker" name="times" onchange="FilterCategories()" id="times"> <option value="1">last 24 hours</option> <option value="30">past month</option> <option value="365">past year</option> <option value="10000">all time</option> </select> </form> <ul id="all-games" class="list-unstyled"> {% include page_template %} </ul> The template that is being included in the above template is entry_index_page.html: {% if objects %} {% for object in objects %} do something {% endfor %} <div class="pagination"> <span class="step-links"> {% if objects.has_previous %} <a href="?page={{ objects.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ objects.number }} of {{ objects.paginator.num_pages }}. </span> {% if objects.has_next %} <a href="?page={{ objects.next_page_number }}">next</a> {% endif %} </span> </div> urls.py: url(r'^$', views.entry_index, name='index') views.py: def entry_index( request, template='entry_index.html', page_template='entry_index_page.html'): date_from = timezone.now() - timezone.timedelta(days=1) obj_list=Object.objects.filter(submitted__gte = date_from).order_by('-votes') message=[] context = { 'objects': obj_list, 'page_template': page_template} if request.is_ajax(): template β¦ -
Django get_full_name not working in html
Im trying to get the full name of my user to be displayed in html and I am using {{ instance.user.get_full_name }}. When I use {{ instance.post_author }} it displays the users username, but get_full_name displays nothing. This is the view for viewing a post: def post_display(request, post_id=None): instance = get_object_or_404(Post, id = post_id) context = { "title": instance.post_title, "instance": instance, } return render(request, "post_display.html", context) This is my model for Posts: class Post(models.Model): post_title = models.CharField(max_length = 120) post_content = models.TextField() last_updated = models.DateTimeField(auto_now=True, auto_now_add=False) post_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_image = models.FileField(upload_to=upload_location, null=True, blank=True) post_author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) def __unicode__(self): return self.post_title def __str__(self): return self.post_title def get_absolute_url(self): return reverse("posts:post_display", kwargs= {'post_id': self.id}) And this is the Html: <li>Written By: {{ instance.user.get_full_name }}</li> Thanks for any help you can give, Will -
Djamgo 1.10: accessing session data after redirect
I have a custom user class for django because I needed to use email addresses instead of usernames, not sure if that is relevant for the question but I wanted to add that just in case. I am trying to redirect a user to their dashboard after successful login, however, when I attempt to call the redirect via URL, I then seem to lose the ability to access the logged in user data via request.user. How can I redirect the page from login to dashboard and maintain session data for the user between the two views? The django docs for sessions and the authentication system seem to suggest that you can use session anywhere and the data will be available if the login method was called for the user (a reference to the session stored in a cookie maybe?) but when I attempt to make calls to data in the session.user object, there is no data there and if I wanted to do something like, say hi request.user.first_name, there is currently not any data like that available to call. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^create$', views.user_create), url(r'^login', views.user_login), url(r'^dashboard', views.display_dashboard) ] views.py from β¦ -
Django Database for multiple server
At present, I have one server in production which serves the client. Now if the user starts growing I may need more servers to handle requests. Now, I maintain sessions using Django. I am using AWS Server and will be using a load balancer for multiple servers. If a user logs in from server A and next time he tries to access his resource and that request is diverted to another server but on that particular server session id wouldn't be present. I am thinking of maintaining a dedicated server for Database. Will that be okay? Should I consider something else? -
Django filtering on foreign key
Hi and thanks for reading. Below is the relevant piece of my Data Model. I want to pull all the threads for a given section in my forum. but I'm struggling to get this to work. Here's the data model: class ForumSections(models.Model): heading = models.CharField(max_length=200) icon = models.CharField(max_length=50) hits = models.IntegerField(default=0) def __str__(self): return "Section: %s" % (self.heading) class ForumThread(models.Model): heading = models.ForeignKey(ForumSections, on_delete=models.CASCADE) threadTitle = models.CharField(max_length=200) threadStatus = models.BooleanField(default=True) def __str__(self): return "Thread: %s Under Section: %s" % (self.threadTitle, self.heading so I'm thinking I want to do something like: ForumThread.objects.filter(ForumSections__heading=heading) However this returns an error : django.core.exceptions.FieldError: Cannot resolve keyword 'ForumSections' into field Really appreciate your help - I'm stuck here. Thanks! Tommy -
Most pythonic way of checking if a form submiited has data
I'm currently learning Django however I'm torn on how to structure the equivalent of add method using it. I'm creating a URL shortener and I'm between the following methods to implement in creating the shortened URL: def shorten(request): if request.method == 'POST': http_url = request.POST.get("http_url","") if http_url: # test if not blank short_id = get_short_code() new_url = Urls(http_url=http_url, short_id=short_id) new_url.save() return HttpResponseRedirect(reverse('url_shortener:index')) else: error_message = "You didn't provide a valid url" return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message }) return render(request, 'url_shortener/shorten.html') vs. def shorten(request): http_url = request.POST["http_url"] if http_url: short_id = get_short_code() new_url = Urls(http_url=http_url, short_id=short_id) new_url.save() return HttpResponseRedirect(reverse('url_shortener:index')) else: error_message = "You didn't provide a valid url" return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message }) return render(request, 'url_shortener/shorten.html') Specifically, I want to know the best practice on the following: Is it best practice to explicity test if method is post or http_url = request.POST["http_url"] is enough Is http_url = request.POST.get("http_url","") recommended to be used or this is just suppressing the error? If (2) is not recommended, how can I make the http_url required and throw an error? I also tried the following but the except block is not triggered when I submit a blank form def shorten(request): if β¦ -
how to build a system for django in sublime text 3
How to build a new system , works like python3 shell (when we enter python 3 manage.py shell) in sublime text 3. -
Django does not find static files which are not tied to specific apps
I want to put the static files in the folder outside any apps. This is the file structure. mysite |---assets |---css |---js |---images |---companyinfo |---views.py |---models.py |---templates |---index.html |---recruit.html |--- .... |---mysite |---urls.py |---settings.py |--- .... |---manage.py |--- .... settings.py looks like the following. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/assets/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets"), ]` urls.py under mysite folder looks like the following. I did not define a urls.py under companyinfo folder. from companyinfo import views as civiews urlpatterns = [ url(r'^$', civiews.index, name='index'), url(r'^recruit/$', civiews.recruit, name='recruit'), ] views.py is just two functions that render the html pages. The urls for the static files are the same in the two html pages. The problem is the index page loads well with all the css and js files, but the recruit page does not find those files. What might the problem be? I'm using Django1.10. Thanks in advance! -
click jquery call not working on button click
I am trying to write a simple django template as follows: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" /> <script> $("#submitQuery").click(function() { alert("Hola!!"); }); </script> </head> <body> <label for="geo_location"> Enter location here: </label> <input id="geo_location" type="text" name="geo_location" required /> <button id="submitQuery">Find out</button> <div id="test"></div> </body> </html> However, clicking the button doesn't do anything. Where am I wrong here? -
Django Models and Permission Restrictions
Models: Company Product We have a parent company (owner of all) who can create any Company and any Product, as sub-Company or sub-Product. Now, what I'd like to accomplish, is limiting which Company can CRUD other Companies and Products alike. Here's are the scenarios: Company and Sub-Companies (sub-contractors): Master (creates) -> Company βAβ Master (creates) -> Company βBβ (creates) -> Company βCβ Master (creates) -> Company βDβ (creates) -> Company βFβ (creates) -> Company βGβ Company and Product Assignment: Master (Add Product) -> Show all products Master (assign products to top levels) -> Company βAβ, Company βBβ and Company βDβ Sub-Company Product Assignment (management): Company βBβ (assign products only to sub-level) -> Company βCβ Company βDβ (assign products only to sub-level) -> Company βFβ Company βFβ (assign products only to sub-level) -> Company βGβ However, if Company D removes a product from a sub-level, this will also remove from all sub-level products recursively. -
Is there a canonical way to mix standard django sitemaps with Wagtail sitemaps?
Pretty straightforward - I want to use the django sitemap framework and set up my static and custom pages, and I want to make sure that any pages added in wagtail are also indexed.