Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DetailView can't resolve slug for views
I have wrote models,views and urls like this models.py class PreventionField(models.Model): name = models.SlugField(max_length=200) verbose_name = models.CharField(max_length=200) views.py class PreventionFieldDetailView(DetailView): model = PreventionField template_name = 'prevention-fields-details.html' template_name = "prevention-field-details.html" def get_object(self, **kwargs): return PreventionField.objects.get(slug=self.kwargs['slug']) urls.py urlpatterns = [ url(r'^$', Frontpage.as_view(), name='frontpage'), path('fields/<slug>/',PreventionFieldDetailView.as_view(),name='fields')] And what I want is to generate slug urls based on entries in PreventionField model that I can switch between subpages in my website like http://mywebsite.com/fields/neuro where neuro slugfield from model,but this return error FieldError at /fields/neuro/ Cannot resolve keyword 'slug' into field. Choices are: id, name , verbose_name and ok,so I have to switch from 'slug' into 'name' because this is my SlugField in model PreventionField,right? Well, when I change views.py code to return PreventionField.objects.get(slug=self.kwargs['name']) then got following error: KeyError at /fields/neuro/ 'name' and now I've lost it. I don't understand why DetailView works this way and how I should change it to obtain slug url. PS I should mention that I didin't have problems when I was using pk instead of slug. -
Unsafe redirect to URL
i'm create a class views on django, but get this error: Unsafe redirect to URL with protocol 'products' this is my code on the views: class CreateProduct(CreateView): model = Product form_class = ProductForm template_name = "administrador/create_product.html" success_url = "products:admin_productos" this is my urls: url(r'^create_product$', CreateProduct.as_view(), name="create_product"), i dont know why get this error..please some one idea..!! thanks..!! -
Django 2.1 - DeleteView - only owner can delete or redirect
I'm doing an exercise that consists of a small newspaper, I want to allow only to the Article creator to delete it, otherwise, redirect to the 'home' page. But, that's not working, I'm only being able to raise Http404. views.py: class ArticleDeleteView(LoginRequiredMixin, DeleteView): model = Article template_name = 'article_delete.html' success_url = reverse_lazy('article_list') def get_object(self, queryset=None): """ Hook to ensure object is owned by request.user """ obj = super(ArticleDeleteView, self).get_object() if not obj.author == self.request.user: print(redirect('home')) raise Http404 return obj I tried to: return redirect('home') Instead of "raise Http404" but Django throws this error: 'HttpResponseRedirect' object has no attribute 'delete' What's the way to solve this behavior and why it's this happening? Thanks for your help!! -
Iterating over the value of a form in Django
I have a form, that accepts a number. On submission of the form, this number is redirected to another html page from the django views.py. Here, how do I iterate over the number that I have received? When I try with the below, it says 'int' object is not iterable {% for i in N %} <p>{{i}}</p> {% endfor %} Note: N here is the number received from the form. -
Is there a reason why Django won't accept a blank field?
I am working on a project where I originally intended some fields to be required that are now optional. However, the newer fields will still throw an error if they are left blank. From my models.py: class PlanOfAction(models.Model): PoA_1 = models.CharField(max_length=255, blank=True, default="") q1_why = models.CharField(max_length=255, blank=True, default="") PoA_2 = models.CharField(max_length=255, blank=True, default="yeah") q2_why = models.CharField(max_length=255, blank=True, default="") PoA_3 = models.CharField(max_length=255, blank=True, default="") q3_why = models.CharField(max_length=255, blank=True, default="") long_term_goal = models.CharField(max_length=255, blank=True, default="") long_term_date = models.CharField(max_length=255, blank=True, default="") long_term_actions_1 = models.CharField(max_length=255, blank=True, default="") long_term_actions_2 = models.CharField(max_length=255, blank=True, default="") long_term_actions_3 = models.CharField(max_length=255, blank=True, default="") short_term_1 = models.CharField(max_length=255, blank=True, default="") short_term_1_date = models.CharField(max_length=255, blank=True, default="") short_term_actions_1_1 = models.CharField(max_length=255, blank=True, default="") short_term_actions_1_2 = models.CharField(max_length=255, blank=True, default="") short_term_actions_1_3 = models.CharField(max_length=255, blank=True, default="") short_term_2 = models.CharField(max_length=255, blank=True, default="") short_term_2_date = models.CharField(max_length=255, blank=True, default="") short_term_actions_2_1 = models.CharField(max_length=255, blank=True, default="") short_term_actions_2_2 = models.CharField(max_length=255, blank=True, default="") short_term_actions_2_3 = models.CharField(max_length=255, blank=True, default="") short_term_3 = models.CharField(max_length=255, blank=True, default="") short_term_3_date = models.CharField(max_length=255, blank=True, default="") short_term_actions_3_1 = models.CharField(max_length=255, blank=True, default="") short_term_actions_3_2 = models.CharField(max_length=255, blank=True, default="") short_term_actions_3_3 = models.CharField(max_length=255, blank=True, default="") created_by = models.ForeignKey(User, related_name="user_poa") objects = PlanManager() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) And where it is writing to the database in models.py new_plan = PlanOfAction.objects.create( PoA_1 = … -
Redirecting a form to another form dynamically
I'm a beginner in Django. So I do sincerely apologize in advance if my question is dummy. That being said, I've been trying to search for the answer on the Internet for days with no success so far. In a nutshell, I have a form made of a single MultipleChoiceField. When the user connects for the 1st time on the webpage with this form, he can check the boxes which are appropiate and then hit a Submit button. So far, I manage to do it. Where I get stuck is on how to redirect the user to another form (in total there will be 10 forms, until he reaches a "complete" webpage). Using redirect, I know how to redirect the user to a static webpage, but I could not figure out how to redirect him to a dynamic webpage (ie based on the variables values within my view). Below are the scripts I wrote to give you a better idea of what I'm trying to achieve: [views.py] def my_form(request, id): form = MyForm(request.POST or None, form_id=id) if form.is_valid(): # DO SOME CLEAN-UP... form.id += 1 id += 1 return render(request, 'my_form.html', {'form': form, 'id': id}) [urls.py] urlpatterns = [ ... … -
Start mezzanine project with custom database
I'm trying to start up a mezzanine project with my own database, however when i create the database and migrate after starting a new project, the database remains empty. This is what I do: 1) In PGADMIN 4, I create a new database with the name 'mydatabase' and the user 'myuser' and password 'mypassword' 2) I start a new mezzanine project with: mezzanine-project testproject 3) I change my database in settings.py to: DATABASES = { "default": { # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "mydatabase", # Not used with sqlite3. "USER": "myuser", # Not used with sqlite3. "PASSWORD": "mypassword", # Set to empty string for localhost. Not used with sqlite3. "HOST": "localhost", # Set to empty string for default. Not used with sqlite3. "PORT": "5432", } } 4) Finally, I run: python manage.py migrate Everything runs fine - but the database I created in PGADMIN 4 remains empty (no new tables), even after refreshing and restarting. So, where does this database get created?? I'm specifying the database as a postgres database, and I don't have any other instances of postgres on the computer? How do I … -
argument of type 'ManyToManyDescriptor' is not iterable
I have mode: class Subscribe(models.Model): class Meta: verbose_name_plural = 'sunscribes' id=models.AutoField(primary_key=True) name=models.CharField(max_length=30,null=False); owner=models.ForeignKey(User,related_name='owner', null=False, blank=True, on_delete=models.PROTECT) subscription = models.ManyToManyField(User,null=True,related_name='subscription') I need to select all Subscribe items where this user is in the list subscration My attempt: avtor=post.author # user item subscribe=Subscribe.objects.get(avtor in Subscribe.subscription ) # get list Error: argument of type 'ManyToManyDescriptor' is not iterable Post is instance of Article: class Article(models.Model): id = models.AutoField(primary_key=True) ... author = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT) -
Django model field dependent on another model field
I have general question. Let’s say I have a model field that is the sum of two other fields in a different model. I’m having a hard time to implement this. Let’s take the following example model1 field1 field2 model2 field3 (dependent on field1 and field2) in model1 If I do it as part of specific page in my webapp. It means that if field1 or field2 has changed but the person didn’t visit the page that sum up the value and update it in field3 then field3 will carry incorrect value. The only way to takle such a problem that I managed to identify is to never create field3. everytime a sum(or any other operation that had dependency on other fields) take a place is to be done in a variable inside the view.py This means that value to be calculated everytime it is needed. This way I won’t get myself in a position where I forget to recalculate the value of field3. My question is this the best way to do it? Is there a way that whenever a depedent field change such as field1 that automatically change field3 without the need to visit a specific page? I … -
Can't open file 'manage.py': [Errno 2] No such file or directory
My Procfile contains web: gunicorn chn_parking.settings Why I am getting this error? Can't open file 'manage.py': [Errno 2] No such file or directory I am trying to deploy an app on Heroku. All was fine... -
Cannot access server on PythonAnywhere with Ionic app
I am developing a mobile app in which I show my gym's schedule. I use bs4 for scraping data from the website and Django for the rest of the backend. I've deployed my app to PythonAnywhere. Everything is awesome when I just visit my_username.pythonanywhere.com/schedule. I get the JSON that I wanted to receive. I also tried to do it with Postman, and I get the same result. Moreover, when I call ionic serve and visit my localhost, I see the ionic page and all the information received from the server as it should be. However, when I test everything on my device, the data is not displayed at all. The access log gives me the code 404 928. The error log is the following: Not Found: /, and I understand that Django searches for the page on "/" which is not there. But I don't send any request to my_username.pythonanywhere.com/ ! Instead, I send requests to my_username.pythonanywhere.com/schedule, so Django shouldn't bother about the non-existence of the page that I don't ask for. I would understand if after ionic serve my browser didn't display data and got the same error. But it does display the data! And the mobile app does … -
Django-tables2 and Django-filters: Filtering list of dicts
I have a table, that I made from 3 different models. And I want to filter them. But the problem is - all examples, that i've found - was about queryset and have only one model. dict = [{'name': Model1.objects.get(id=1), 'adress': Model2.objects.get(id=Model1.objects.get(id=1))},{'name': Model1.objects.get(id=2),},....] filter=FilterSet(queryset=???) The point is - data from another models I got from Model1. But I can't build table on this model, because it don't have foreign keys to other 2 models. Other words Model1(models.Model): field1 = models.Charfield() field2 = models.Charfield() Model2(models.Model) field3 = models.Charfield() field4 = models.ForeignKey(Model1) ... Any suggestions? Because I don't think that making another model is a good solution. -
django model not creating postgresql table
I have added a simple model to my reporter app in my django project class Municipalities(models.Model): namelsad = models.CharField(max_length=100) geom = gismodels.MultiPolygonField(srid=4326) when I python3 manage.py makemigrations reporter it says no changes detected in reporter then when I python3 manage.py migrate reporter Operations to perform: Apply all migrations: reporter Running migrations: No migrations to apply. but there is no postgresql database table of reporter_municipalities reporter is included in installed apps -
Why django_admin_log table is empty in Django Rest Framework
I am developing a web application where I'm using Django 2.0.8 and Django Rest Framework to build a RESTful API. I have build some endpoint for basic CRUD operations. The problem is now I am trying to view log to my admin Dashboard. (Custom Admin Panel). But when I browsed my Database (PostgreSQL), I found that I have django_admin_log table but it is totally empty. But I created some object with those endpoints. Doesn't Django keep logs of user's activities by default? Or am I missing something? PS: I was authenticated while creating those objects django_admin_log table -
Can I extend django admin to one of the good looking bootstrap admin templates?
I am trying to use django as the platform for a website development. I was using wordpress so far. I liked its CMS and admin system. Can I make a function rich admin backend with django that has; pages, menus, categories, tags, posts, images etc. as the wordpress. In order to make it look good, is it possible to use boostrap or similar dashboard templates? How much of difficulty are you expecting for this project? Looking forward for your opinions Thanks -
Upload image to S3 via Django Admin with Non-model field
I'm trying to use Django admin to upload an image to S3, but not save the file path to disk. To do this, I'm creating the ImageField by modifying the admin form however it seems that I'm losing the upload magic that Django does behind the scenes because I'm not using the model version of ImageField. So basically, this all saves correctly except the image doesn't get uploaded. My form looks like this: ref: shops.admin.py: from django import forms from django.contrib import admin from shops.models import Shop class ShopForm(forms.ModelForm): image = forms.ImageField() def save(self, commit=True): image = self.cleaned_data.get('image', None) return super(ImageForm, self).save(commit=commit) class Meta: model = Shop fields = ['name', 'address', 'market', 'pictures', 'image'] class ShopAdmin(admin.ModelAdmin): form = ShopForm fieldsets = ( (None, {'fields': ('name', 'address', 'market', 'pictures', 'image')}), ) admin.site.register(Shop, ShopAdmin) My model looks like this: class Shop(models.Model): class Meta: managed = False db_table = 'shop' #verbose_name = "shop" _id = models.ObjectIdField() name = models.CharField(max_length=150) address = models.CharField(max_length=150) market = models.ForeignKey( Market, on_delete=models.CASCADE, db_column='main_market' ) pictures = models.CharField(max_length=500, blank=True, null=True) The reason why I'm doing it like this is I need to store the url from the image field in the pictures field which is an array of urls. … -
Beginners: Dynamic filtering of foreign key field in Django CreateView form
Models: class Instructional_Cycle(models.Model): date_started = models.DateField() date_finished = models.DateField() standard_tested = models.OneToOneField(Standard, on_delete=models.CASCADE) class Standard(models.Model): subject = models.CharField(max_length=14, choices=subjects) grade_level = models.IntegerField(choices=gradeLevels) descriptor = models.CharField(max_length=15) description = models.TextField() essential_status = models.BooleanField(default=False) View: class CycleCreateView(CreateView): model = Instructional_Cycle template_name = 'cycle_new.html' fields = '__all__' success_url = reverse_lazy('student_progress:cycles') Template: <!-- student_progress/cycle_new.html --> {% extends 'base.html' %} {% block content %} <h1>Add a new instructional cycle:</h1> <form action="{% url 'student_progress:cycle_new' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button name="submit">add cycle</button> </form> {% endblock content %} The problem I'm having with this form is that the dropdown to select Instructional_Cycle.standard_tested has literally 1000 records from Standard. There's no way that the user can scroll through all of those and find the one record they want. What I need is some way to click a link and filter the dropdown list by subject or grade_level and/or a search box, similar to what's achieved on the admin side by creating a custom admin model in admin.py like so: class StandardAdmin(admin.ModelAdmin): list_display = ('descriptor', 'description', 'essential_status') list_filter = ('subject', 'grade_level', 'essential_status') search_fields = ('descriptor',) inlines = [MilestoneInLine] def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) try: search_term_as_int = int(search_term) except ValueError: pass else: … -
ImportError: cannot import name 'HttpResponce' from 'django.http' [on hold]
So, I'm trying to create a web, and I use django. My code is next: from django.http import HttpResponce def index(request): return HttpResponce('Hello World!!!') I don't understand why it workes in another projects and doesn't work now. -
how to loop through django queryset data and set the values in an array not a dictionnary
I Have to loop through data of the query set in django and put the data into an array without specifying the model name. My Django view, : it is giving me error "Permission' object is not iterable" permissions = Permission.objects.all().order_by('perm_label') arrayData = [] for type in permissions: for value in type: arrayData.append(value) -
Django: Using Celery & RabbitMQ to save a record
I have recently found an article describing the process of using celery along with RabbitMQ to every single operation that can slow down the entire time of processing a particular request. Without any doubt, such a combination is great and useful whenever there is a need of processing big amounts of data / using some sophisticated algorithms to complete some task, but what is more, I have seen a way of saving a simple record to the database with the usage of this setup. Is there anyone that can explain to me whether such a solution is better than typical approach, that assumes the completion of operations related with the database in first order, and only after that ending the users request? Thanks in an advance -
Apache 403 Forbidden Error- No permission to access server on /
I have browsed all related questions and it seems like everything I try doesn't work. If I visit my server (root) ip address I get forbidden error. But if I visit {my_ip_address}/static, that does work. I have a projectfolder located at /root/myproject and my static files located in /var/www/static.What I'm trying to achieve is to deploy my django application for production, so static files can be served through apache. In /etc/apache2/apache2.conf I have tried: <Directory /> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /root/myproject/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> In /etc/apache2/sites-available/myproject.conf I have tried: <VirtualHost *:80> ServerAdmin admin@myproject.com ServerName {placeholder for ip address} DocumentRoot /root/myproject Alias /static /var/www/static <Directory /var/www/static> Require all granted </Directory> WSGIDaemonProcess {placeholder for ip address} processes=2 threads=15 display-name=%{GROUP} python-home=/root/myproject/env/lib/python3.5 WSGIProcessGroup {placeholder for ip address} WSGIScriptAlias / /root/myproject/app/app/wsgi.py <Directory /> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /root/myproject/app/app> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /root/myproject> Require all granted </Directory> </VirtualHost> I have tried the following commands to give permission: chgrp -R www-data /root/myproject chmod -R 2750 /root/myproject And obviously, reloaded apache with the command: … -
Get all values from Django QuerySet plus additional fields from a related model
I was wondering if there is a shortcut to getting all fields from a Django model and only defining additional fields that are retrieved through a join (or multiple joins). Consider models like the following: class A(models.Model): text = models.CharField(max_length=10, blank=True) class B(models.Model): a = models.ForeignKey(A, null=True, on_delete=models.CASCADE) y = models.PositiveIntegerField(null=True) Now I can use the values() function like this: B.objects.values('y', 'a__text') to get tuples containing the specified values from the B model and the actual field from the A model. If I only use B.objects.values() I only get tuples containing fields from the B model (i.e. y and the foreign key id a). Let's assume a scenario where B and A have many fields and I am interested in all of those belonging to B but only in a single field from A. Manually specifying all the field names in the values() call would be possible, but tedious and error-prone. So is there a way to specify that I want all local fields but only a (few) specific joined field(s)? Note: I'm currently using Django 1.11 but if a solution only works with a more recent version I am interested in that too. -
How to make Django Rest API fore nested comments?
I want to make a nested comment model for an android app and I am using Django Rest framework. I have defined two models Post and Comment as follow: class Post(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey('CustomUser',on_delete=models.CASCADE, related_name="author") created_at = models.DateTimeField(auto_now=True, editable=False) tag = models.ForeignKey('Tag', on_delete=models.CASCADE, blank=True, null=True) class Comment(models.Model): p_post = models.ForeignKey('Post', on_delete=models.CASCADE) description = models.TextField() author = models.ForeignKey('CustomUser', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True, editable=False) p_comment_id = models.ForeignKey('self', blank=True) is_anon = models.BooleanField(default=False) What I am having problem is if I want to get the list of comments on app, so, how should I deal with it? I have following points in my head: I can not return the complete list of comments, as it will be a very long list So, how do I chose to restrict to return top 5 comments along with their top 5 child comments. -
Flutter, complex SQLite DBs with many tables, is this best practice?
Flutter newbie here afraid. I have a small Django app (python) that I am porting over to a standalone Flutter app with no web back-end. I directly exported the SQL (DDL; about 300 lines worth) that specifies my SQL tables used in my Django app and use that in my flutter app (see below). I end up with ~8 tables and I can query these by just copy/pasting the Django SQL queries Django creates for me via it's ORM. My question: is it best practice to have complex tables in mobile app development? I worry SQLite is not best suited for such complexity. But I feel it saves me time to reuse this already generated model structure and range of SQL queries. Many thanks, Andy. initDb() async { // Get a location using path_provider var databasesPath = await getDatabasesPath(); String path = join(databasesPath, "gear_log.db"); await deleteDatabase(path); var theDb = await openDatabase(path, version: 1, onCreate: (Database db, int version) async { String sql = await rootBundle.loadString('assets/db/schema.txt'); for(var s in sql.split(";")) { //seems to be a max # characters for db.execute if(s.length > 5) { // catching any hidden characters at end of schema await db.execute(s + ';'); } } // When … -
Django query using result of Count annotation from another query
I've been struggling with this one for days now. I have a database table that has time stamps and stock transaction information including company trading symbol and value transacted. Each timestamp represents a single day. Here is the data model: class OwnershipDocument(models.Model): transactionTimeStamp = models.IntegerField(null=True, blank=True) issuerTradingSymbol = models.CharField(max_length=50, null=True, blank=True) valueTransacted = models.FloatField(null=True, blank=True) I want to make a django query that will select only those stock transactions where there are more than one transaction for a company for a time stamp. I've come up with a query to get the transaction counts for each time stamp: query = OwnershipDocument.objects.filter(issuerTradingSymbol__iexact='ED') query1 = query.values( 'transactionTimeStamp' ).annotate(count = Count('transactionTimeStamp')).order_by('transactionTimeStamp') I think that I need to use query1 with a subquery somehow but I'm not sure how to do this. I have accomplished what I want using raw SQL: query = OwnershipDocument.objects.raw(''' SELECT * FROM insider_app_ownershipdocument WHERE "valueTransacted" > 1 AND ("issuerTradingSymbol", "transactionTimeStamp") IN ( SELECT "issuerTradingSymbol", "transactionTimeStamp" FROM insider_app_ownershipdocument GROUP BY "issuerTradingSymbol", "transactionTimeStamp" HAVING COUNT (*) > 5) order by "transactionTimeStamp" DESC, "issuerTradingSymbol" ''') But I need to chain this to a previous django query object which apparently I can't do using raw SQL. So how do I convert this raw …