Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django inline forms
I have to models, an Article and a Photo. There is a many2many relation between them. I need to design an Admin form that works better for editing them. I batch upload photos and the Photo models are created. Then when I write the articles, I want to be able to edit the Photo models as an inline form. When I set it up as described so far, I get an article edit form, with a selector to click on the name of each photo. I would like to have all unassigned photos shown, with a text box for the cutline on each photo and checkbox. When I put a checkbox and save the article the pictures are associated with that article. I also need to save the updated Photo objects with the text under each photo. Suggestions for how I should go about this? -
NameError at /accounts/register/ name 'Honeyword' is not defined
hye there . how to import my new custom password hasher ? it just give me this error : NameError at /accounts/register/ name 'Honeyword' is not defined hashers.py : class MyHoneywordHasher(PBKDF2PasswordHasher): algorithm = "honeyword_base9_tweak3_pbkdf2_sha256" iterations = 36000 digest = hashlib.sha256 def salt(self): salt = get_random_string() while Honeyword.objects.filter(salt=salt).exists(): salt = get_random_string() return salt -
Create and fill a test database
Django==1.11.6 The problem is: first test runs smoothly, but the second test faces an empty database. StaticLiveServerTestCase is a TestCase subclass. Let's have a look at the documentation about setUpClass: https://docs.python.org/3.6/library/unittest.html#unittest.TestCase.setUpClass Well, nothing is clear. But it seems that database is created in the SetUpClass. And as far as I can understand, the database created once and exists till the last method of the class finishes. Well, I seem to be wrong as the second method faces an empty database. Could you help me organize a test database, and fill it once for all the methods. class GeneralMixin(StaticLiveServerTestCase): """ Load selenium and log in. Afterwards quit webdriver. """ fixtures = ['users.yaml'] def _login(self): .... def setUp(self): self._login() @classmethod def setUpClass(cls): super(GeneralMixin, cls).setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super(GeneralMixin, cls).tearDownClass() class FrameTests(GeneralMixin): @classmethod def setUpClass(cls): super(FrameTests, cls).setUpClass() create_dateranges() create_frames() def test_id_frame_1(self): """ User visits frame 1. And sees that ID 1 is shown in the frame detail page. """ FRAME_ID = "1" self.selenium.\ get('{}{}'.format(self. live_server_url, reverse('frame_detail', kwargs={"pk": FRAME_ID}))) id_element = self.selenium.\ find_element_by_id("object_id") found_id = id_element.text self.assertEqual(found_id, FRAME_ID) def test_id_frame_2(self): """ User visits frame 2. And sees that ID 2 is shown in the frame detail page. """ FRAME_ID β¦ -
Django Boolean Field Won't Update
I have a model which has a latest field to determine if a particular instance is the latest definition. When adding a new row to the db I want to make sure to mark latest as false for the already existing record. latest_version = Segment.objects.filter(segment_name=segment_name, third_party_type=third_party_type).first() if latest_version: latest_version.latest = False latest_version.save() This seems relatively straight forward but the latest field will not update and stays as True. -
Django - access to item in list with a changing index
I used to code in C#. I want to use python to do something like: int start_index = 4; List<int> list = { ... } for(int i = start_index;i < 10;i++){ list[i].dosomething(); } this is how I tried in Django {% with 0 as starting_index %} {% for comment in comments %} <!--set a variable to limit the amount of comment on a page--> {% with forloop.counter as index %} {% if index < 3 %} <div class="comment_body"> <div class="content_block"> <p>{{comments[index]}}</p> </div> </div> {% endif %} {% endwith %} {% endfor %} {% endwith %} This code is obviously not working. Can anybody help me with this problem? Thanks in advance! -
Django extra user registration details not saving to database
I have been trying to extend the django user profile but it won't save the extra details to the database which is a user_type of business, student, tourist and I can't figure out why. Any help would be appreciated. It doesn't save in the DB as null, it is saving as just blank. Using python 3 with the latest version of django. Forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.forms import ModelChoiceField from django.contrib.auth.models import User, Group from .models import UserProfile class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=50, required=False, help_text='Not required.') last_name = forms.CharField(max_length=50, required=False, help_text='Not required.') email = forms.EmailField(max_length=300, required=True, help_text='Please input a valid email address.') user_types = ((1, 'Business'), (2, 'Student'), (3, 'Tourist')) user_type = forms.ChoiceField(choices = user_types) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'user_type', 'password1', 'password2',) models.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from django import forms # Create your models here. ADMIN = 0 BUSINESS = 1 STUDENT = 2 TOURIST = 3 class UserProfile(models.Model): user_choices = ( (0, 'Admin'), (1, 'Business'), (2, 'Student'), (3, 'Tourist'), ) # Link UserProfile to User model user = models.OneToOneField(User, on_delete=models.CASCADE) # Add attributes β¦ -
Django - ModelChoiceField validation
I have a simple form witch ModelChoiceField. This is a part of my view.py file: def premium(request, id): context = {} try: site = Site.objects.get(id=id) except Site.DoesNotExist: raise Http404("Nie ma takiej strony") if request.method == 'POST': premium_form = PremiumForm(request.POST) if premium_form.is_valid(): # group = Group.objects.get(id=request.POST["kod"]) print('OK') else: print('NOT OK') else: premium_form = PremiumForm(site) premium_form.fields['group'].queryset = premium_form.fields['group'].queryset.exclude(group_name=site.group) context['site'] = site context['form'] = premium_form context['category'] = site.category context['subcategory'] = site.subcategory return render(request, 'mainapp/premium.html', context) This is my form: class PremiumForm(forms.Form): def __init__(self, site, *args, **kwargs): super(PremiumForm, self).__init__(*args, **kwargs) self.fields['group'].initial = 2 self.fields['group'].empty_label = None group = forms.ModelChoiceField( queryset=Group.objects.filter(is_active=True), help_text="<div id='group'></div>", label="Some text", required=False) My premium.html file: <form method="post" action="" class="form-horizontal"> {% csrf_token %} {% bootstrap_form form layout='horizontal'%} <br> {% bootstrap_button "Submit" size='large' button_type="submit" button_class="btn-primary btn-main-add" %} </form> When I press "Submit" button I get "NOT OK". I can't resolve this problem. I don't have any idea how to validate forms.ModelChoiceField. Thanks for any help. -
Cant get to data to save from form Django
I am creating a job board site. Right now I can successfully register an Employer but when I try to create a job listing while logged in as an Employer, the data from the form does not save to the database. I have the following models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.http import HttpResponse # Create your models here. class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_employer(sender, instance, created, **kwargs): if created: Employer.objects.create(user=instance) @receiver(post_save, sender=User) def save_employer(sender, instance, **kwargs): instance.employer.save() class Job(models.Model): poster = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=50) establishment_name = models.CharField(max_length = 50) details = models.TextField(max_length = 2000) salary = models.CharField(max_length = 20) address = models.CharField(max_length = 50) state = models.CharField(max_length = 20) zip_code = models.CharField(max_length = 10) def __str__(self): return self.job_title + " - " + self.establishment_name \ + ", " + self.poster.user.first_name + " " +self.poster.user.last_name A user can register as an employer just fine, but I am having problems getting Jobs to save to the database. Once a user registers/logs in as an employer they are redirected to employer_home.html, where an employer can post a job: {% extends β¦ -
How to make a button click update the database and redirect to a view in Django?
I have been struggling with this for a while, any help would be appreciated! Basically, what I want to do is click an HTML button in Django, change a field in the database (of the object with the primary key in question), and redirect back to home. An example for clarity: Currently, I am working in the url: http://127.0.0.1:8000/result/edit/1/. The /1/ is the primary key of the model I want to change. The model is a custom group-model, with a field called "status". Status can be "approved", or "not approved": status = models.CharField(max_length=30, default=Status.not_sent, choices=Status.choices(), null=False) In the url result/edit/1/ I have an "Approve" button. When I click the button I want to change status in the model, and save that in the database. Also, after changing status I would like to redirect back to home. I have written the following method in views to do it: def approve_group(request, pk): group = Group.objects.filter(pk=pk) group.status = Status.approved group.save() return redirect(request, 'home') In the html, I have created the following button: <a href="{% url 'resultregistration:approve_group' %}" /> <button id="approve-btn" />Approve</button> </a> My reasoning is that the button should call this URL, which should again call the function in the view: url(r'^result/approve/(?P<pk>\d+)/$', views.approve_group, β¦ -
Ghostscript/Imagemagick is not working in Django
I am working on a Django/Django REST framework based web application. I am building an API that slice pdf to every page, and convert them to image. Here are some of my code. with Image(filename=os.path.join(tmp_dir, pdffilename)) as img: for i, page in enumerate(img.sequence): file = '%s-%d.jpg' % (imagefilename, i + 1) Image(page).save(filename=file) filelist.append(file) but I am getting this error: DelegateError: FailedToExecuteCommand `'gs' -sstdout=%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 '-sDEVICE=pngalpha' -dTextAlphaBits=4 -dGraphicsAlphaBits=4 '-r72x72' '-sOutputFile=/var/folders/kl/5qf5q4x50xj2rbdp8t2prsbh0000gn/T/magick-26897HyfIoUTUbASw%d' '-f/var/folders/kl/5qf5q4x50xj2rbdp8t2prsbh0000gn/T/magick-26897y4uJPEzsfHCE' '-f/var/folders/kl/5qf5q4x50xj2rbdp8t2prsbh0000gn/T/magick-268970ovMV9WfGDbE'' (1) @ error/pdf.c/InvokePDFDelegate/292 I am using python 2.7.10 / Django 1.9. And, of course, installed Ghostscript(9.2.2) and imagemagick(6.9.9). I am not sure why this is not working. Would you like to help me? Any idea why this isn't working for me? -
DJango CreateView not setting attributes before data is saved to the DB
New to using Django over here. I am trying to create a DJango form that will save data to the database. To do this, I am using CreateView When calling the URL that is to "do the work", I have it set up as follows (so, a parameter is being passed in as well) url(r'^owner/contacts/add/(?P<tenantid>[0-9]+)/$', views.MstrstoreheadcontactCreateView.as_view(), name='owner-contact-add'), Problem: When trying to save data to the DB, I get an error that seems to be due to some fields not being set properly the exact error message I am getting is: The above exception (ORA-02291: integrity constraint (ORAAPPS.SYS_C009216) violated - parent key not found) was the direct cause This is how the Model is defined: class Mstrstoreheadcontact(models.Model): tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True) contactid = models.BigIntegerField(primary_key=True) genderid = models.BigIntegerField(blank=True, null=True) firstname = models.CharField(max_length=20, blank=True, null=True) lastname = models.CharField(max_length=20, blank=True, null=True) officephoneno = models.CharField(max_length=20, blank=True, null=True) cellphoneno = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'MstrStoreHeadContact' it was created using the inspectdb option (used to auto-generate classes for tables that already exist in a database) This is how the CreateView is being defined in views.py class MstrstoreheadcontactCreateView( CreateView ): model = Mstrstoreheadcontact fields = [ 'firstname', 'lastname', 'officephoneno', β¦ -
Django Python How to Compare Encrypt User's Password
I am working a project which is like CMS (Content Management System) for a website. I am developing this system with django python. But I am new to django python. I have my own User model (not django user model) that contains some fields like username, email, password etc. and I create new user from my own admin panel. How can I compare encrypted password with user's password that post on login page. For example first time I create user, the password for 123 saved on db like pbkdf2_sha24123$000asd$... After that I am trying to login with password 123 but I get error that the passwords are not equals. from django.contrib.auth.hashers import make_password from account.models import myUsers password = make_password(request.POST.get('password')) email = request.POST.get('email') if myUsers.password == password and myUsers.email == email: #make login and redirect to panel else: #show error message -
Django passing parameter to CreateView and filling the form with it
I want to make a CreateView with the form already completed with an argument that will be passed to it from another view. There is the initial view with an input field. Like this: <form role="form" action="" method="post"> {% csrf_token %} <div class="col-sm-6"> <div class="form-group"> <div class="form-line"> <label>{{form.cpf.label}}</label><strong style="color:red;"> *</strong> {% if form.cpf.errors %}<label class="error">{% for error in form.cpf.errors %}{{error}}{% endfor %}</label>{% endif %} {{form.cpf}} </div> </div> </div> <button class="btn btn-success foot-btn" type="submit"><i style="vertical-align:middle" class="material-icons">add</i><span style="vertical-align:middle">Verificar</span></button> </form> When the user submits this form he will be redirected to another page. Asking if he wants to insert that value in the DB. Right now I'm trying to redirect like this, trying to pass the POST value as a parameter to the CreateView return redirect(reverse('blacklist:addcpfview', args=(request.POST['cpf'],))) But I can't seem to get this parameter in the CreateView. I know this I'm probably very wrong in the way I'm currently doing, but I'm a beginner with Django and want to know the best way to do this. -
Django: Redirect "name 'request' is not defined"
Here's my View, class ObjLike(RedirectView): def get_redirect_url(self, *args, **kwargs): id = self.kwargs.get('id') obj = get_object_or_404(Data, id=id) user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) So after this view how can I redirect user to the same page? I used "return redirect(request.META['HTTP_REFERER'])" but it gives an error "name 'request' is not defined" I can't use the get absolute URL method, i'm using this view at several places. So, how can I do that? -
Can`t fing static files Django
I have macOS Sierra and modified my old Django-project ( project was created on Linux system, maybe this is called some bugs ) I have folder static and folder landing inside static And when I run the server, I have some next messages: GET /static/landing/img/397x300/03.jpg HTTP/1.1" 404 1691 this is my settings file with variable static - STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), '/Users/milkiweed/Documents/python/django/psy_site/static' -
Django - Filtering user information related to the URL
I have 4 models: Blogger, User, Post and Comment. Here is the blogger model. class Blogger(models.Model): username = models.OneToOneField(User, related_name='bloggers') blogger_bio = models.CharField(max_length=1000) Now, i want to display username and blogger_bio depending to the URL. For eg, is someone is using: /testuser, the template will filter username and blogger_bio of only user named testuser. How to filter this Dynamically? -
Django URL patterns to serve external webpack bundle
I'm writing a django rest framework API (backend) with a react SPA frontend. For the production environment, the front end is served up via nginx at http://example.com/ and the backend is proxied to gunicorn and served from the same domain with a different path - http://example.com/api/ This is all working fine in production, there are no CORS issues as the frontend and backend are both served up under the same domain via nginx. For local development, I want to be able to replicate a similar setup using ./manage.py runserver and have django serve up the frontend from project/frontend/dist (built by npm build seperately). Has anyone got any urlpattern wizardry that will allow this to happen and also let the react-router play nicely? I just can't figure it out and it's starting to drive me nuts... The project structure is something like this if it helps in any explanations. Project | ββ backend β βββ apps β βββ config | | βββ settings.py | | βββ settings_local.py | | βββ urls.py β βββ manage.py β βββ requirements.txt β βββ venv βββ frontend β βββ dist (contains the npm build webpack) β βββ node_modules β βββ package.json β βββ package-lock.json β βββ β¦ -
Django - include a child template cannot find template
I am trying to include a page into another one like this <div id="past_comments"> {% include 'comment_block.html' %} <!--{% for comment in comments %}--> <!--<p>{{comment.content}}</p>--> <!--{% endfor %}--> </div> and the structure of my directory is like: |-post |----comment_block.html |----detail.html |----index.html screenshot of structure in picture However, I get an exception: Exception Type: TemplateDoesNotExist Exception Value: comment_block.html Can any body help me with this? Thanks in advance! -
How to copy files from a directory to a new sub domain
I am developing a basic website builder like wix.com using Django, I have a default template in folder which contains css, html and js files in my Django project, Once the user fills the registration form and submits i want to create a new folder with all the files from template folder. Once the folder is created with template files i will use wild cards to create a sub domain. Kindly help me to achieve this -
django staticfiles collection error
I started a new project in django and created a development and a testing environment with their settings in the same folder as the custom settings.py everything is going well till I created a static file directory and I tried to collect static files but got error. raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. this is my directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media") STATICFILES_DIRS = ( os.path.join(os.path.dirname(BASE_DIR), "static", "static"), ) -
Django ORM - MySQL query count optimization for related models
I have two related models, that looks like below: class Enterprise(models.Model): id = models.AutoField(primary_key=True) subsystem_id = models.IntegerField() name = models.CharField(max_length=255, unique=True) modif_date = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Project(models.Model): id = models.AutoField(primary_key=True) subsystem_id = models.IntegerField() name = models.CharField(max_length=255) modif_date = models.DateTimeField(auto_now=True) enterprise = models.ForeignKey('Enterprise' on_delete = CASCADE) active = models.BooleanField(default=True) In my view, need to get all active Enterprises and list them. I'm doing it this way: enterprise_list = Enterprise.objects.annotate(project_count=Count('project')).filter( Q(active=True) | Q(subsystem_id=-1), project_count__gt=0 ) serializer = EnterpriseSerializer(enterprise_list, many=True) Then, my serializer is displaying project list with some additional query: class EnterpriseSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) name = serializers.CharField(max_length=255, required=False) project_list = serializers.SerializerMethodField() def get_project_list(self, enterprise): project_list = Project.objects.filter(Q(active=True) | Q(subsystem_id=-1), enterprise=enterprise) serializer = ProjectSerializer(project_list, many=True) return serializer.data class Meta: model = Enterprise fields = ('id', 'name', 'project_list') This code is working fine, but it has very serious issue - performance. The first query for Enterprise returns list of ~1500 object. Then, for every object, serializer executes single query to fetch additional data for project which results to ~1500 queries. I've tried prefetch_related and select_related but either I'm doing something wrong or it doesn't work in my case. In the other hand I can get list of project first. This could β¦ -
DJango pagination error, staticfiles
Hi guys (I'm newbie in DJango)! I'm having a problem with DJango. When i go to 127.0.0.1/blog i have an error which looks like this: image Here are some lines from settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',] STATIC_URL = '/static/' Here is head from base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static 'css/blog.css' %}" rel="stylesheet"> </head> -
MultiValueDictKeyError at /accounts/upload_save/
I got an error, MultiValueDictKeyError at /accounts/upload_save/ "'image'" . I am making file upload system.It is that if i select file and put "SEND" button,selected image is sent to model.But now,when i select no image and put "SEND" button,the error happens.I wanna make a system that if i select no image and put "SEND" button,<p>You should select at least one photo</p> message is shown. I wrote in photo.html <div class="container" id="photoform"> {% if form.errors %} <div class="alert alert-danger" role="alert"> <p>You should select at least one photo</p> </div> {% endif %} <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn" style="width: 30%;"> <span class="btn btn-primary btn-lg"> File Select1 <input type="file" name="image"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label class="input-group-btn" style="width: 30%;"> <span class="btn btn-primary btn-lg"> File Select2 <input type="file" name="image2"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> File Select3 <input type="file" name="image3"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> </div> I wrote in views.py @login_required @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = β¦ -
django rest api for advance search
i want to create a api using django rest framework which will do some advance search, say a list of grocery item is saved in database and user want to create a list of grocery and he enters first 2 or 3 letters and then my api will do query to get rest of the item name and will suggest to user I have seen the documentation of drf haystack but not sure whether will it fulfill my requirement. Also it does not support django LTS version 1.11 . Can you please give me some suggestion? is django rest framework itself provide any support to create such a api which will do such advance search which i mentioned above? i just need some suggestion as i am new in django rest framework. -
subprocess not work in django with apache
This probelm confused me many days, i can't figure it out, please help. windows django 1.7.8 + python 2.7.8 requirment: copy file to s3 with aws cli process = subprocess.Popen( r'C:\Program Files\Amazon\AWSCLI\aws.exe s3 cp e:\test\p001.zip s3://bucketsname',stdout=subprocess.PIPE, universal_newlines=True) This code can be successful in A,B,C, and file copied to s3. A. run in directly in python cmd B. run in python manage.py shell C. run in django default http server D. django + apache wsgi The only problem is that D, if i use apache in django, the cmd not work, file not copied. So how to deal with apache in this case? Thank you!