Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User-Created Fields in Django Models
I'm creating a contact form which would allow users to create custom fields. I'm trying to pass request or a group object into the model.py. I would need this line contact_custom_char1 = ContactCustomCharField.objects.filter(group=group)[0] but don't know how to get the group or request there. How should I go about this? What is a way of letting users customize form fields? Let me know if I'm not being clear enough. class ContactCustomCharField(models.Model): editable = models.BooleanField(default=False) name = models.CharField(max_length=50, null=True) group = models.ForeignKey(Group, editable=False, blank=True, null=True, on_delete=models.SET_NULL) try: contact_custom_char1 = ContactCustomCharField.objects.get(pk=1) except: contact_custom_charl = ContactCustomCharField.objects.create(editable=False, name='None', group=group) try: contact_custom_char2 = ContactCustomCharField.objects.get(pk=2) except: contact_custom_char2 = ContactCustomCharField.objects.create(editable=False, name='None', group=group) try: contact_custom_char3 = ContactCustomCharField.objects.get(pk=3) except: contact_custom_char3 = ContactCustomCharField.objects.create(editable=False, name='None', group=group) class Contact(models.Model): company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) title = models.CharField(max_length=50, blank=True) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) owner_group = models.ForeignKey(Group, editable=False, blank=True, null=True, on_delete=models.SET_NULL) custom_char1 = models.CharField(max_length=50, blank=True, null=True, editable=contact_custom_char1.editable, verbose_name=contact_custom_char1.name) custom_char2 = models.CharField(max_length=50, blank=True, null=True, editable=contact_custom_char2.editable, verbose_name=contact_custom_char2.name) custom_char3 = models.CharField(max_length=50, blank=True, null=True, editable=contact_custom_char3.editable, verbose_name=contact_custom_char3.name) -
Unable to log in with provided credentials - drf django
I have made a custom User Model and using that. Now, I want token auth in my app, so I generated a token for every user in my database. But that does not work for users other than superuser. This is the custom user, class User(AbstractBaseUser, PermissionsMixin): mobile = models.CharField(max_length=15,unique=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30,blank=True) date_joined = models.DateTimeField(auto_now_add=True) is_on_booking = models.BooleanField(default=False) is_acitve = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) bookings_count = models.IntegerField(default=0) GENDER_TYPES = (('male','m'),('female','f'),('other','o')) gender = models.CharField(max_length=15,choices=GENDER_TYPES,blank=True) objects = MyUserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = ['email','first_name'] This is my custom usermanager, class MyUserManager(BaseUserManager): def _create_user(self, mobile, email, first_name, is_staff, is_superuser, password, **extra_fields): if not mobile: raise ValueError('User must give a mobile Number') email = self.normalize_email(email) user = self.model(mobile=mobile,email=email,first_name=first_name, is_staff=is_staff, is_superuser=is_superuser, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, mobile, password=None, email=None, first_name=None, **extra_fields): return self._create_user(mobile, email, first_name, False, False, password, **extra_fields) def create_superuser(self, mobile, email, first_name, password, **extra_fields): return self._create_user(mobile, email, first_name, True, True, password, **extra_fields) The superuser for which it returns the token was made using the default django User Model. So, I get that the problem is somewhere in my custom model OR custom manager. When I try to get token for user … -
django dynamically update ModelForm's Meta Class widgets
I want to dynamically generate ModelForm's Meta Class widgets according to exercise_type field from Exercise class. How can I get the value? class ExerciseAdminForm(ModelForm): class Meta: model = Exercise fields = '__all__' widgets = { 'starter_code': _make_language_mode(exercise_type=Exercise.exercise_type) } -
Django pagination + filter
have a problem with using pagination and filtering. I'm using filtering django-filter and paginator in CBV(ListView). Everything is working. The paginator wraps the box after filtering, the problem is in the buttons of the paginator in the template. When you press NEXT or PREV the filter is reset. I found a solution: <span><a href="?page={{ page_obj.previous_page_number }} {% for key,value in request.GET.items %} {% ifnotequal key 'page' %}&{{ key }}={{ value }}{% endifnotequal %} {% endfor %}">Previous</a> </span> But this does not solve the problem completely, so I can send a request from my filter: ?item_title=&description=&ordering=&popular=&min_price=&max_price=&category_brands=11&category_brands=13 And since i have two category_brands= in url and this solution don't work becouse I can not have two identical keys. Please help me. -
related_query_name's default / fallback behaviour has changed in Django 1.10
I am updating a project from Django 1.8 to Django 1.11. It's a somewhat mature / complex project with a lot of models and queries. It seems that a backwards incompatible change was made in Django 1.10, namely the default behaviour of ForeignKey.related_query_name. In Django 1.10, related_query_name falls back to the model's default_related_name - in Django 1.8 this was not the case. This change is apparent in the docs: Django 1.9: https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.related_query_name Django 1.10: https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_query_name Almost all of my models have default_related_name defined, yet no ForeignKeys have related_query_name set. This means that essentially all of my database queries that traverse relationships are invalid! Am I doomed to rewrite all my queries, or add related_query_name to everything? Or is there some way to retain the old functionality? -
Use multiple database connections based on user role
In my Django project, I would like to restrict the DB access for users based on their respective roles. For example, a user with admin role will have a DB connection with which he can read and write and a normal user will have a read-only database connection. I already tried the 'DATABASE-ROUTERS'.I am using PostgreSQL. -
How to enable function to render templates based on try, except blocks from within another view in Django?
I am creating an application in Django that would allow my users to order items from my site based on information already stored in the database. Not all my users should be able to order certain items, for this purpose I have written a pipeline with comparison statements and try, except blocks. A small, reproduce-able piece of code looks like this: vendor.py def guest_constraint(request) # Ensure user in request is a house-guest by checking if it has an active token. try: guest = GuestProfile.objects.get(user=request.user.id) except ObjectDoesNotExist: return render(request, 'extGuest/appGuestError/not_hotel_login.html') # Check for Hotel Room Information linked to Guest Token try: room_information = RoomInformation.objects.get(guest_token=guest.token) except ObjectDoesNotExist: return render(request, 'extGuest/appGuestError/constraint_error.html') views.py from .vendor import guest_constraint @login_required def index(request): user = request.user # Grab user defined in request. name = user.get_short_name() # Grab first name of user. return render(request, 'extGuest/appGuestFlow/choose_order_type.html') Challenge: I can successfully import this small script into my view and I can see its content is run except for the return render(request, template) part. To explain myself better, the try/except block successfully catch the exception, however it does not returns the template specified in the block but instead it goes back to the view and renders the template I have in … -
Returning related fields of a model instance
I am creating an app with a rest API that should return values for instances of objects based on the url given. Right now I have the API working using ModelViewSets of my objects for the API. For example I have three objects, user, transactions, and goals. As it stands I can go to /mysite/api/users and return a list of all users I can also go to /mysite/api/users/1 to return just the user with the id '1'. I can do something similar with transactions and goals. What I'm looking to do is go to url /mysite/api/users/1/transaction/1/goal to find the goal associated with the transaction for that user. I've been scouring tutorials and am not sure what the right question is to ask in order to find something useful to learn how to do this. What is the correct way to go about setting up my rest api like this? -
Use the generate_files_directory method to change the FielField upload_to param do not work
I write a generate_files_directory method to generate the upload path: def generate_files_directory(self,filepath): url = "images/%s" % (filepath) return url The model is bellow: class Upload(models.Model): filepath = models.CharField(max_length=64, default="imgs/test/") pic = models.FileField(upload_to=generate_files_directory) upload_date=models.DateTimeField(auto_now_add =True) The form code is bellow: class UploadForm(ModelForm): class Meta: model = Upload fields = ('pic', 'filepath') my views.py: def home(request): if request.method=="POST": img = UploadForm(request.POST, request.FILES) if img.is_valid(): img.save() return HttpResponseRedirect(reverse('imageupload')) else: img=UploadForm() images=Upload.objects.all() return render(request,'home.html',{'form':img,'images':images}) and I write a home.html to upload the files: <div style="padding:40px;margin:40px;border:1px solid #ccc"> <h1>picture</h1> <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="Upload" /> </form> {% for img in images %} {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a> ({{img.upload_date}})<hr /> {% endfor %} </div> But seem it did not upload to the generated path, it still upload to the /images/ directory: all in there: -
Could any body plz help about how I can read this error? I am sure I typed import unittest truly and I am not sure why my code does not work?
When I run my code which is about testing my class code, I get the error below Traceback (most recent call last): File "my_servy_test.py", line 1, in <module> import unittest File "C:\python34\lib\unittest\__init__.py", line 59, in <module> from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf, File "C:\python34\lib\unittest\case.py", line 6, in <module> import logging File "C:\python34\lib\logging\__init__.py", line 28, in <module> from string import Template File "C:\Users\flower\Documents\python_work\string.py", line 2 ^ SyntaxError: unexpected EOF while parsing ------------------ (program exited with code: 1) Press any key to continue . . . -
Making code for user in django
I'm creating database in django app. How can I make auto-generation of 8 character for every new registered user? For example, user creates his login and password and system assign him 8 character number, so I can lately use this number in app to search that user instead of using his login -
I get `AnonymousUser` Error when I access my api using axios, but I have really login the account
I get AnonymousUser Error when I request the api, but I have really login the account: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/luowensheng/Desktop/QIYUN/Project/Qiyun02/用户管理后台/产品管理/user_admin_productmanage_cloudserver/api/views.py", line 153, in dispatch result = super(CloudServerListAPIView2, self).dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/luowensheng/Desktop/QIYUN/Project/Qiyun02/用户管理后台/产品管理/user_admin_productmanage_cloudserver/api/views.py", line 159, in get openstackclouduserid = self.request.user.openstackcloud_userid File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/functional.py", line 239, in inner return func(self._wrapped, *args) AttributeError: 'AnonymousUser' object has no attribute 'openstackcloud_userid' The bellow logs can prove me have login my developing website: [28/Nov/2017 11:40:59] "OPTIONS /rest-auth/login/ HTTP/1.1" 200 0 [28/Nov/2017 11:41:00] "POST /rest-auth/login/ HTTP/1.1" 200 50 [28/Nov/2017 11:41:07] "POST /api/user_productmanage/cloudserver/logincloudaccount/ HTTP/1.1" 200 23 My frontend code is bellow: The structure of my Axios method: import qs from 'qs' import Vue from 'vue' import ApiSetting from './config' import Cookies from 'js-cookie'; const Axios = axios.create( ApiSetting.AxiosConfig ); Axios.interceptors.request.use( config => { // 在发送请求之前做某件事 if ( config.method === "post" || config.method === "put" || config.method === "delete"|| config.method === "get" ) { // 序列化 config.data = qs.stringify(config.data); } // 若是有做鉴权token , 就给头部带上token if (Cookies.get('tokens')!==undefined) { config.headers['Authorization']= 'Token '+Cookies.get('tokens'); } return config; }, error => { //出错 return Promise.reject(error.data.error.message); } ); //拦截器 Axios.interceptors.response.use(function (response) { // 相应成功 return response; }, function … -
MultipleHiddenInput widget doesn't get rendered
My MultipleHiddenInput field which I am using to store some choices for another field based on a selector doesn't seem to work. Please consider my code: class LogSearch(forms.Form): platform = forms.ChoiceField(required=True, choices=platforms, initial='v', help_text='The platform to search on') log_type = forms.MultipleChoiceField(required=True, choices=()) keyword = forms.CharField(required=True) other_log_types = forms.MultipleChoiceField(required=False, widget=forms.MultipleHiddenInput, choices=[(1, '3'), (2, 'b')]) As shown in this form code, I would expect the other_log_types to be rendered as hidden. But it doesn't appear at all in my HTML. I am rendering it properly on the template as all other components appear properly. I'm not sure if I am not using the widget right or not. Thanks -
Use the FilteredSelectMultiple widget without using Django's admin
How can I use the FilteredSelectMultiple widget without having the /admin URLs defined and no superusers? I would like to use it in my own form, but I'm not sure how to include the JS without using the built in superusers. The docs show it's possible but as I said I'm not sure about including the JS. -
my django project unit test volume, It's getting bigger
I'm looking for some solution or cases for big testing file what my django-team have... which mean, there is too much Django unit-test files in our django-project.. django_app/tests/tests_xxx.py <--- almost 20 ~ 30 files on tests dir How do I manage all of django-test, more productive and effective methods -
Normal characters&escape seaquence are gotten in my program
Normal characters&escape seaquence are gotten in my program.I wanna get only escape seaquence,so I really cannot understand why.I wrote codes, import re def get_id(request): id= "100¥a" pattern = re.compile(r'[\\u000-\\u037]', re.UNICODE | re.IGNORECASE) if pattern.findall(id): return HttpResponse('<h1>Escape sequence</h1>') else: return HttpResponse('<h1>OK</h1>') In this case,program go into if statement and it is ok.But when I rewrote id into id= "100",program go into if statement too.I wanna only catch escape seaquence in if statement,my ideal system goes into else statement if id does not have escape sequence.What is wrong in my code?How should I fix this? -
rest-framework "get() missing 1 required positional argument"
I want transmit a GET parameters 'pk' to django rest-framework. ![broser][https://i.stack.imgur.com/5sdPR.png] but in my view.py,I was setting my GET method to receive ‘pk’ parameters. ![views.py][https://i.stack.imgur.com/NCpcI.png] It's urls.py code: ![urls.py][https://i.stack.imgur.com/5RdvC.png] and There is another one question,if I models object use 'objects' method in the pycharm,were throw an exception,such as: ![]https://i.stack.imgur.com/9q0OV.png] but my friend was not happen this exception.He use pycharm 2017.4(macOS) cateloydata = category.objects.all() my pycharm version:pycharm 2017.2 python version 3.6 django version 1.11.7 Thank everyone. and I'm sorry,I need at least 10 reputation to post images.So my question composing is very bad. 感谢! -
Filter Django Form Field Based on ForienKey Relation of previous field
Hello guys please how can i filter the items on a form field based of the foreignkey relation with the previous field . somethings like a locations selector in which if the user selects the next field should be filtered based in it. thanks -
Server side pagination for web services api in django
My project structure is as- webservice api : Django database : Mongodb frontend : angular2 I am trying to implement pagination what I have tried- def get_my_large_records_paginated(request): json_data = json.loads(request.body) page_no = json_data["pageNo"] display_records_count = json_data["displayRecords"] records = [very large list around 10000 dictionary objects] # This is large list contains dynamic data which is processed after querying complex query on mongodb paginated_data = self.paginate(records,page_no,display_records_count) return JsonResponse(paginated_data) def paginate(self,records,page_no,display_record): paginatorObj=Paginator(record_obj,display_record) num_pages = paginatorObj.num_pages try: if page_no <= num_pages and page_no >0 : page = paginatorObj.page(page_no) return page.object_list else: print ("Invalid page number or display record count") except Exception as e: error_logger.error(e) return None I am able to paginate records and response. But every time I request new page it process all 10000 records, query mongodb. So is there any way to avoid processing query operation on every consecutive request and return data directly which is processed for first request. If there is alternative solution also for above approach I would love to try. Thanks in advance. -
Dynamically generate fields+1 for model form
I have a model that is basically just a service report. I want this model to contain multiple punches (clock in\clock out). How do I go about doing that? When I pull up the form, I want to be able to add punches obviously. class ServiceReportModel(models.Model): report_number = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) site = models.ForeignKey(customers_models.SiteModel, on_delete=models.PROTECT) request_number = models.ForeignKey(ServiceRequestModel, on_delete=models.PROTECT, null=True, blank=True, related_name='s_report_number' ) reported_by = models.ForeignKey(main_models.MyUser, related_name='reports') reported_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(main_models.MyUser, blank=True, null=True, related_name='+') updated_date = models.DateTimeField(auto_now=True) equipment = models.ForeignKey(customers_models.EquipmentModel, on_delete=models.PROTECT) report_reason = models.CharField(max_length=255, null=True) time_in = models.DateTimeField(blank=True, null=True) time_out = models.DateTimeField(blank=True, null=True) actions_taken = models.TextField(null=False, blank=False) recommendations = models.TextField(null=True, blank=True) def get_absolute_url(self): return reverse('service-report', kwargs={'pk': self.pk}) def __str__(self): return '%s - %s, %s' % (self.site.company, self.reported_date.strftime('%d %B %Y'), self.equipment.name) class Meta: ordering = ['reported_date'] verbose_name = 'Service Report' verbose_name_plural = 'Service Reports' -
Escape sequence cannot be gotten in if-else statement
Escape sequence cannot be gotten in if-else statement.I wrote codes, import re def get_id(request): id= "100¥a" if re.search(r"[\0-\037]", id): return HttpResponse('<h1>Escape sequence</h1>') else: return HttpResponse('<h1>OK</h1>') In this case,I think program go into if re.search(r"[\0-\037]", id): ,but always it go into else statement.I really cannot understand why.Is the way of getting escape sequence in if statement wrong?How should I fix this? -
Form invalidad in Django - ManyToMany relationship
I'm trying to insert data in my ManyToMany relationship but i don't get it, my form always is invalidad. I get this error when i try to save the form "The view apps.alumno.views.SubirActividad didn't return an HttpResponse object. It returned None instead." Models: class Alumno(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nocontrol = models.CharField(max_length=8) grupo = models.ForeignKey(Grupo, on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.nocontrol) class Actividad(models.Model): nombre = models.CharField(max_length=50) descripcion = models.CharField(max_length=100) asignatura = models.ForeignKey(Asignatura, on_delete=models.CASCADE) alumno = models.ManyToManyField(Alumno, through='ActividadAlumno', through_fields=('actividad', 'alumno'),) def __str__(self): return '{}'.format(self.nombre) class ActividadAlumno(models.Model): actividad = models.ForeignKey(Actividad, on_delete=models.CASCADE) alumno = models.ForeignKey(Alumno, on_delete=models.CASCADE) fecha = models.DateField(auto_now_add=False, auto_now=True) documento = models.FileField(upload_to='asignatura/tarea/') calificacion = models.IntegerField(null=True) Form: class ActividadAlumnoForm(forms.ModelForm): class Meta: model = ActividadAlumno fields = [ 'actividad', 'alumno', 'documento', 'calificacion', ] labels = { 'actividad': 'Fecha de entrega', 'alumno': 'Entregado', 'documento': 'Estado', 'calificacion': 'Calificacion', } widgets = { 'actividad': forms.Select(), 'alumno': forms.Select(), 'documento': forms.ClearableFileInput(), 'calificacion': forms.NumberInput(), } View: def SubirActividad(request, id_actividad): actividad = Actividad.objects.get(id=id_actividad) if request.method=='POST': form = ActividadAlumnoForm(request.POST) if form.is_valid(): form.save() return redirect('alumno:asignatura_detalle', clave=form.instance.asignatura.clave) else: alumno = Alumno.objects.get(user=request.user) form = ActividadAlumnoForm(initial={'actividad': actividad, 'alumno':alumno}) return render(request, 'alumno/actividad_subir.html', {'form':form}) -
Django Unique constraint failed for user field in model
I've been trying to figure out how to save the user's id with in a model through a form, I keep getting UNIQUE constraint failed: vapp_numobject.user_id. Here's my model: class NumObject(models.Model): title= models.CharField(max_length=50) number= models.IntegerField() ident= models.IntegerField(blank=True, null=True) user= models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return self.title def save(self, *args, **kwargs): super(NumObject,self).save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:detail', kwargs={'id': self.id}) my forms.py: class NumForm(forms.ModelForm): class Meta: model = NumObject fields = [ 'title', 'number', ] and my view that saves the form: @login_required def post_createnum(request): form= NumForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('/') context= { 'form': form, } return render(request, 'num_form.html',context) I'd like to be a able to sort a list of the NumObjects by user id, and I'm not sure if there's a better method in Django. Any help is appreciated! -
Proper template setup Django?
I'm a new user of Django. I've seen a couple ways people are setting up their templates. I would like to get some thoughts on the proper way in case one leads to problems down the road. The first layout that I've seen is to use multiple template folders. A main one in the root folder and also one under each app directory that you make. The other way I've seen is to use only one templates folder and just name directories under it which match the name of the apps. Hopefully that makes sense. Any thoughts on the right way to do it would be appreciated. -
Understanding Django Model Design and Forms
So I am trying to create a small, but powerful project that manages customers, employee reports, and customer requests. The system stores customer information like address, rates, distance, etc. I have a feeling I am misunderstanding, or over complicating my model design. As an example here is my customer models.py: from django.db import models from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ ''' The address model is just a generic address container ''' class AddressModel(models.Model): street1 = models.CharField(max_length=255) street2 = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) zipcode = models.IntegerField() country = models.CharField(max_length=50) ''' The phone model is just a generic address container ''' class PhoneModel(models.Model): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed." ) phone_number = models.CharField(_('Phone Number'), validators=[phone_regex], max_length=15, blank=True ) # validators should be a list def __str__(self): return '%s' % (self.phone_number) class Meta: verbose_name = "Phone Number" # verbose_name_plural = "Phone Numbers" class CompanyModel(models.Model): name = models.CharField(_('Company Name'), max_length=255) since = models.DateField(auto_now_add=True) rate = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return '%s' % (self.name) class Meta: ordering = ['name'] verbose_name = 'Company' verbose_name_plural = 'Companies' ''' The site model consists of sites of a company …