Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comment form in django didn't save the new comments
I have a little problem. I'v create a new form for comments the articles on website. When I add the new comment from django admin everythink works ok, but when I try to add the new comment directly from detail page nothings happen and I'am redirecting to the page with list of articles. here are my files models.py: class Komentarz(models.Model): post = models.ForeignKey(Wpisy, related_name="komentarze", verbose_name="Komentarze do artykułu", on_delete=models.CASCADE) name = models.CharField(max_length=80, verbose_name="Imię") email = models.EmailField(verbose_name="Email") content = models.TextField(verbose_name="Treść komentarza") created_date = models.DateTimeField(verbose_name="Utworzono", auto_now_add=True) active = models.BooleanField(verbose_name="Aktywny?", default=True) class Meta: ordering = ('created_date',) verbose_name="Komentarz" verbose_name_plural="Komentarze" def __str__(self): return 'Komentarz dodany przez {} dla strony {}'.format(self.name, self.post) vies.py with the function of details from django.shortcuts import render, get_object_or_404 from .models import Wpisy, Komentarz from .forms import KomentarzeForma .... def detale_bajki(request, slug, ): detale_bajki = get_object_or_404(Wpisy, slug=slug) komentarze = detale_bajki.komentarze.filter(active=True) if request.method == 'POST': formularz_komentarza = KomentarzeForma(data=request.POST) if formularz_komentarza.is_valid(): nowy_komentarz = formularz_komentarza.save(commit=False) nowy_komentarz.detale_bajki = detale_bajki nowy_komentarz.save() else: formularz_komentarza = KomentarzeForma() return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki, 'komentarze': komentarze, 'formularz_komentarza': formularz_komentarza}) forms.py from .models import Komentarz from django import forms class KomentarzeForma(forms.ModelForm): class Meta: model = Komentarz fields = ('name', 'email', 'content') and detail.html ... {% with komentarze.count as total_komentarze %} <h2> {{ total_komentarze }} … -
Django server crashes when accessing webcam with opencv
so I found out that everything works fine when I remove cv2.imshow("Face",img) from the code but when it is used the server crashes due to some reason, the code runs perfectly when run as a plain script excluding django code. Can anyone tell me why is this happening and the possible solution? thanks from django.shortcuts import render, redirect import cv2 import numpy as np from settings import BASE_DIR def index(request): return render(request, 'index.html') def create_dataset(request): userId = request.POST['userId'] faceDetect = cv2.CascadeClassifier(BASE_DIR+'/ml/haarcascade_frontalface_default.xml') cam = cv2.VideoCapture(0) id = userId sampleNum = 0 while(True): ret, img = cam.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceDetect.detectMultiScale(gray, 1.3, 5) for(x,y,w,h) in faces: sampleNum = sampleNum+1 cv2.imwrite(BASE_DIR+'/ml/dataset/user.'+str(id)+'.'+str(sampleNum)+'.jpg', gray[y:y+h,x:x+w]) cv2.rectangle(img,(x,y),(x+w,y+h), (0,255,0), 2) cv2.waitKey(500) cv2.imshow("Face",img) cv2.waitKey(1) if(sampleNum>35): break cam.release() cv2.destroyAllWindows() return redirect('/') -
User registration using extra fields by extending AbstractUser
I asked something similar before, but people don't seem to understand what I ask or maybe I just don't understand, but I'm really trying to find a solution here. So I have a student model which extends AbstractUser like: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password') class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('phone', 'student_ID', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) photo = models.ImageField(upload_to='students_images') phone = models.CharField(max_length=15, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_student(sender, instance, created, **kwargs): if created: Student.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_student(sender, instance, **kwargs): instance.profile.save() And the expected output is this: I just don't know how the view is supposed to look like. I figured something in the past, but nothing would have been saved. I want that student will not be able to register unless he fills up all those fields: username, email, phone, student_ID etc. But also, I want that the fields of Student to be editable in database after the user is created by the form submission. I'm new to this, but I really need to … -
How to get pk of an instance of a django model before saving the instance
I am trying to upload an image using models.ImageField(upload_to=upload_location) def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s"%(instance.id,filename) but its giving "GET /media/None/image_qacfEsv.jpg HTTP/1.1" I have tried using slug field it worked fine but neither id nor pk is working I want to use the obj ID to name the folder for image but its giving none here are my files def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s"%(instance.id,filename) class Post(models.Model): draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False,auto_now_add=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) slug = models.SlugField(unique=True) title = models.CharField(max_length=120) image = models.ImageField(upload_to=upload_location, null=True,blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) -
Django dont show block tags properly
im using 2 apps. blog and contact. i included 2 block tags in my index.html. but i can only get one working at the same time. when im on my blog it wont show the contact one, when im on my contact it wont show the blog block. My Project: https://github.com/bibschxz/bibsch_project -
Reset a value in a model for all users each year - Django.
I am developing a Django application that tracks an employees holiday. I am not to sure how I would go about resetting the holiday each year at a specific date. Are there any good known solutions/libraries for how to do this? class User(models.Model): avatar = models.ImageField( default='images/avatars/profile.png', upload_to=user_directory_path) name = models.CharField(max_length=100) title = models.CharField(max_length=200, default="Employee") email = models.EmailField(max_length=254) present = models.BooleanField(default=False) code = models.CharField(max_length=4, unique=True) date_created = models.DateTimeField(auto_now_add=True) date_clocked = models.DateTimeField(default=timezone.now) total_holiday = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) holiday_remaining = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) My model is shown above I need to reset the remaining_holiday field on a admin user defined day each year. -
returning record count in django restful api
I have a very complex API that accepts different filter fields via POST request. the result is a list of items from the database. The total result set can be thousands of items if the user does not filter good. The API will be returning only 30 items but I want to add the total amount of items that satisfied the search conditions. I know that I can add a custom field in the Serializer class to return the count but I don't know how to access the queryset to query for the count(). I am sure there is a simple solution for this which I am missing Thanks Eyal -
Pass related object's field in Django ModelForm
I have a Django model class that extends the django.contrib.auth.models.User: class MyModel(models.Model): user = models.OneToOneField(User, models.CASCADE, unique=True) bio = models.TextField() date_of_birth = models.DateField() and out of this model I'm making a ModelForm: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['bio', 'date_of_birth'] How can I tell the MyModelForm to take in the User's fields such as username, first_name, last_name? Example in the class Meta fields I can add ['bio', 'date_of_birth', 'user'] but that will just provide me with the dropdown to select to whom shall the MyModel in the MyModelForm be related to. Doing ['bio', 'date_of_birth', 'user.first_name'] throws an exception django.core.exceptions.FieldError: Unknown field(s) (user.first_name) specified for MyModel -
Django views receiving FormData() object without keys
Here what i am basically trying is to stringify an array and append it to form data object and pass it to a view through ajax. The strange part is values are sent to the views but without keys. Here is my ajax formData = new FormData() var instrument = [136519172, 136485892] formData = new FormData() formData.append('instrument', JSON.stringify(instrument)) $.ajax({ type: 'POST', url: 'place_orders', cache:!1, processData:!1, data: formData, success:function(data){ }, error:function(){ } }); Here is my view def placeOrders(request): if request.is_ajax(): instrument = request.POST.get('instrument') return HttpResponse(instrument) The response i get is None This is the Formdata sent(took from headers of Network tab) ------WebKitFormBoundaryNPW2Q1atgClRKOyY Content-Disposition: form-data; name:"instrument" [136519172,136485892] ------WebKitFormBoundaryNPW2Q1atgClRKOyY-- -
Django - saving form to the built in database SQLite
This is my first time using django and I am very simply trying to save text to the database. I have created the table inputs in the database. I am getting the following error; Error - Page not found (404) My code is as follows; Models.py from django.db import models class Input(models.Model): waist = models.IntegerField(default=0) height = models.IntegerField(default=0) def __unicode__(self): return "{0} {1} {2}".format( self, self.waist, self.height) forms.py class InputForm(forms.ModelForm): class Meta: model = Input fields ={ 'waist', 'height' } views.py def InputView(request): if request.POST: form = InputForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('account/input') else: form = InputForm() args = {'form' : form} return render(request,'accounts/input.html', args) urls.py url(r'^input/$',views.InputView, name='view_input') input.html {% extends 'base.html' %} {% block head %} <title> Edit Profile </title> {% endblock %} {% block body %} <div class="container"> <h1> Enter Body Details </h1> <br> <br> <form action="account/input" method="post"> {% csrf_token %} <ul> {{form.as_ul}} </ul> <input type="Submit" name="submit" value="submit"/> </form> </div> {% endblock %} If any one can help it would be greatly appreciated. -
Class based view and call function to script
I'm learning django and I'm facing a problem I can't figure how to debug. I have a lobby_detail.html template that shows a button like this: <button type="button" href="{% url 'sign'%}" class="btn btn-primary btn-lg btn-block">Sign this Document</button> The template is a Detail view modelview: class LobbyDetailView(generic.DetailView): model = Lobby I would like the button to execute some code that requires both user connected and current lobby instances How can I use the button thanks to class based view? Thanks in advance. -
Django Q object AND operation not working
I have a listview of people with a filter. The filter has the following code: if textquery: qs = qs.filter() qs = qs.filter(Q(name__icontains=textquery) | Q(surname__icontains=textquery) | Q(surname__icontains=textquery) & Q(name__icontains=textquery) ) return qs People can have both a first and a last name, and searching for those works as expected. However, when I input both the first AND the lastname, the program does not return any results (even though I thought that the '&' operation in the end should include both variables). In summary: this is currently the result of my queries: Person: 'John Doe' Query: 'John' Result: 'John Doe' Person: 'John Doe' Query: 'Doe' Result: 'John Doe' Person 'John Doe' Query: 'Johh Doe' Result: '' Does anyone know what I am doing wrong, and why matches for both the NAME and SURNAME do not return any results? -
Django - multiple databases - how to define the router?
I would like to connect my application to 3 different databases. To do this, I've changed the following code in the settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'local_db', 'USER': 'root', 'PASSWORD': 'password1', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, 'firstExternalDb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'firstExternalDb', 'USER': 'userName', 'PASSWORD': 'password1', 'HOST': 'firstExternalDb.node.com', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, 'secondExternalDb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'secondExternalDb', 'USER': 'userName', 'PASSWORD': 'password1', 'HOST': 'secondExternalDb.node.com', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, } And I want to have a possibility to specify for which database I will create a datatable. For example all django tables like 'auth_group' , 'django_admin_log' I want to save in localhost. Was trying to create a router going through this tutorial https://docs.djangoproject.com/pl/1.11/topics/db/multi-db/#topics-db-multi-db-routing But I do not understand this. Could you answer my questions: Should I create new router for each application ? how to define that all django tables should be used by default database ? -
How to display twitter feeds based on users in django & tweepy?
I want to show twitter data based on twitter username in my template (Tweepy) but I don't know how to send data from my models into my views. models.py: <pre> from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL # Create your models here. class Feed(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) feed = models.CharField(max_length=211, blank=True, null=True) twitter = models.CharField(max_length=211, blank=True, null=True) # this is the twitter user name which the user can enter. def __str__(self): return self.feed </pre> views.py: <pre> from django.shortcuts import render from django.views.generic import TemplateView from .tweet import * from .models import Feed def feed(request): api = tweepyapi(request) username = Feed.objects.filter(owner=request.user) user = api.get_user(twitter) # I want this portion to be dynamic. findfriends = user.friends() return render(request, 'feeds/feeds.html', { 'user': user, 'findfriends': findfriends }) </pre> -
Is there anyway to delete object from queryset that already chosen in django?
Example: query = Test.objects.all() I want to delete the specific one. But before deletion I want to do some function like so. for q in query: if q.name == something: newq = q.relate_set.all() query.remove(q) # this remove not work -
Export User model into different app
I have a project with one app, where user, their posts and other models are located. Now I want to separate User model and put it into different app, called users. How should I do this correctly? User model looks like this: class ExternalUser(AbstractUser): class Meta: permissions = ( ('can_do_this', 'Permission1'), ('can_do_that', 'Permission2'), ..., ) I've done django-admin startapp users and copy-pasted user's model code into created app models.py. Then I tried makemigrations and it failed, showing: SystemCheckError: System check identified some issues: ERRORS: photogal.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'ExternalUser.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'ExternalUser.groups'. photogal.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'ExternalUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'ExternalUser.user_permissions'. users.ExternalUser.groups: (fields.E304) Reverse accessor for 'ExternalUser.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'ExternalUser.groups' or 'User.groups'. users.ExternalUser.user_permissions: (fields.E304) Reverse accessor for 'ExternalUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'ExternalUser.user_permissions' or 'User.user_permissions'. Adding related_name='+' to the old user model resulterd in: ERRORS: <class 'django.contrib.auth.admin.UserAdmin'>: … -
Django - app in subfolder
I've created new django app in a subdirectory using the command: python manage.py startapp appName subFolder/appName but if I try to add this app to INSTALLED_APPS at the end of the list I see the following error: ImportError: No module named appName Does anyone know what I am doing wrong ? -
Django - delete record view based on the same method as django admin?
id like a are you sure page like the one in django admin that enables users to delete records if they have perms. currently my view and templates are per the below (the template is modified from the admin template in the Django install) the view I think ive got half right, I just need to send the model_count and deleted_objects, but im not sure how to obtain them in my view? {% extends "home/sbadmin_base.html" %} {% load extras %} {% load static %} {% block content %} {% if perms_lacking %} <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would result in deleting related objects, but your account doesn't have permission to delete the following types of objects:{% endblocktrans %}</p> <ul> {% for obj in perms_lacking %} <li>{{ obj }}</li> {% endfor %} </ul> {% elif protected %} <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would require deleting the following protected related objects:{% endblocktrans %}</p> <ul> {% for obj in protected %} <li>{{ obj }}</li> {% endfor %} </ul> {% else %} <p>{% blocktrans with escaped_object=object %}Are you sure you want to delete the {{ object_name }} "{{ escaped_object }}"? … -
Django makemigrations permission denied for relation django_migrations
I have Python 2.7.14, Django 1.11 and PostgreSQL 9.4.15, and cannot run python manage.py makemigrations with it. It says: django.db.utils.ProgrammingError: permission denied for relation django_migrations But python manage.py migrate works just fine. Sudo's mode is not what I need. With sudo it has another mistakes -- it cannot import settings, but everything is fine with settings, because other developers don't meet this problem. What could be the issue? -
Django: make model field and foreign key unique together
I have the following model: class Locale (models.Model): """ Locale model """ locale_id = models.AutoField(primary_key=True) locale_name = models.CharField(max_length=800) magister = models.ForeignKey(Magister, on_delete=models.CASCADE) def get_name(self): return self.locale_name In the database, there must be exactly one locale-magister pair. To create each locale item, an administrator has to upload the locales. This is done via a bulk upload: try: lcl=Locale(locale_name = data_dict["locale_name"], magister = data_dict["magister "]) # lcl.full_clean() locales_list.append(lcl) rows+=1 if rows==INSERTNUMBER: try: Locale.objects.bulk_create(locales_list) locales_uploaded+=rows except IntegrityError as e: print("Error: locale bulk_create "+repr(e)) locales_list=[] rows=0 I tried using lcl.full_clean() in my bulk upload but I get a UNIQUE constraint failed: zones_locale.locale_name error and only about 1/2 of all locales upload successfully. I also tried using: def validate_unique(self, exclude=None): lcl = Locale.objects.filter(locale_id=self.locale_id) if lcl.filter(magister=self.magister).exists(): raise ValidationError("item already exists") But the same error occurs. I also tried using: class Meta: unique_together = (("locale_name", "magister"),) This did not work either. From what I can tell, the problem is that there exist locales with the same name that belong to different magisters. How can I allow locales with the same name to be uploaded while also enforcing the uniqueness of any given locale-magister pair? -
Why does this URL work in Django? It is not in urls.py
I've never worked with Django before. I'm taking over a Django project that was started by another programmer, who is now long gone. There is some magic happening in the code that I do not understand. For instance, in this file: urls.py I see this: from django.conf.urls import url, include from django.contrib import admin from django.core.urlresolvers import reverse_lazy from django.views.generic.base import RedirectView from django.conf import settings from core import views as core_views from sugarlab.search.views import validate_collections, create_document, delete_interest, rename_interest, add_url, my_interests from sugarlab.search.views import content, score, terms from django.contrib.auth.views import logout as django_logout from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ url(r'^admin/logout/$', django_logout, {'next_page': '/'}), url(r'^admin/', admin.site.urls), url(r'^accounts/logout/$', django_logout, {'next_page': '/'}), url(r'^accounts/', include('allauth.urls')), url(r'^unsecured/$', core_views.home), The confusing part is these two lines: from django.conf import settings url(r'^accounts/', include('allauth.urls')), "allauths" is some configuration set inside of this file: settings/common.py The data looks like this: 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.auth', 'django.contrib.sites', # Social/3rd party Authentication apps 'allauth.socialaccount.providers.linkedin_oauth2', 'captcha' Somehow this is a URL that actually works: /accounts/signup/ This file is completely blank: settings/__init__.py So I've two questions: how does "import settings" manage to magically import allauths? how does /accounts/signup/ map to an actual view? I don't see anything in urls.py, nor in settings, … -
DJANGO - Add field to default auth.User model - simpliest way
Looking for a simpliest way to add one field to Django's User model. I have two types of users with different fields - Company and Customer so I decided to create two types of UserProfiles. CompanyProfile and CustomerProfile. Every user has either CompanyProfile or CustomerProfile. To be able to filter and deciding which type is it, I want to add type field to User model. What would you suggest? Now I have UserProfile in the middle which seems to be overkill and it makes filtering, lookups and many other things less straightforward. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USERPROFILE_TYPE_CHOICES) company_profile = models.OneToOneField('CompanyProfile', null=True, blank=True, on_delete=models.CASCADE, related_name='userprofile') customer_profile = models.OneToOneField('CustomerProfile', null=True, blank=True, on_delete=models.CASCADE, related_name='userprofile') I'm considering to create my custom User model. class User(AbstractBaseUser): type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USER_TYPE_CHOICES) USERNAME_FIELD = 'username' but Django say's that there is no such field like username and I would like to avoid writing whole User model and all it's fields manually. EDIT I know that I could filter based on customerprofile__isnull=False so practically, I don't need type field at all but it doesn't look to be the best way. -
Django ModelForm: Display readonly boolean field as ModelAdmin().readonly_fields does
When in the admin class, a boolean field becomes read-only: class MyAdmin(admin.ModelAdmin): readonly_fields = ('a_boolean_field', ) it gets a great appearance using icons as described in this answer. If this boolean field is defined in a forms.ModelForm: class MyForm(forms.ModelForm): a_boolean_field = forms.BooleanField(disabled=True) How can I present it in the admin interface as if I had set it in the readonly_fields of the admin.ModelAdmin()? -
Django raw query "Schema does not exists"
I'm using django 1.7, and I wish to make us a Count with a conditional. This is possible in django 1.8 onwards, but I'm unable to upgrade. As such, I'm trying to write a raw query as detailed in this question.. Regretfully, I haven't yet managed. My query: a = Photo.objects.raw( 'select "photos_photo"."id" , ' 'COUNT(' 'DISTINCT ' 'CASE ' 'WHEN "point_substanceexistslabel"."substance"."name" = "fabric" then 1 else null end) as c ' 'FROM "photos_photo" ' 'LEFT OUTER JOIN "points_substanceexistslabel" ' 'on ("photos_photo"."id" = "points_substanceexistslabel"."photo_id")' ' GROUP BY "photos_photo"."id"' ) Running the query and trying to print a result raised the following error: ProgrammingError: schema "point_substanceexistslabel" does not exist -
How to get a list of many to many relation to the same model
I want to move the list of related messages with a given model to the variable in the view - this is the "related" field. At the moment I'm getting all the objects that are badly displayed on the site. Please any hint, thanks a lot. Model: class News(models.Model): title = models.CharField(max_length=500) subtitle = models.CharField(max_length=1000, blank=True) text = models.TextField() link_title = models.CharField(max_length=500) date = models.DateField(null=True) related = models.ManyToManyField('self', symmetrical=False, blank=True) class Meta: verbose_name_plural = 'news' ordering = ['-date'] View: class NewsDetailView(DetailView): model = models.News context_object_name = 'news_item' def get_context_data(self, **kwargs): context = super(NewsDetailView, self).get_context_data(**kwargs) context['related_news'] = models.News.objects.values_list('related', flat=True) return context