Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Rendering Model Choices in template when not using Forms or ModelForms
I created a model and one of the fields has choices. I created a select form in my template and the choices are not been displayed. I'm not using Forms or ModelForms for a few reasons. But my understanding is that I should be able to make this work using CHOICES in the model, building a form in the template and save the information using the object manager. How can I get the choices to populate the form? Models.py class NewRating(models.Model): EXCELLENT = 'EX' GOOD = 'GD' FAIR = 'FR' BAD = 'BD' RATING_CHOICES = ( (EXCELLENT, 'Excellent'), (GOOD, 'Good'), (FAIR, 'Fair'), (BAD, 'Bad') ) function = models.ForeignKey(Function, related_name='frating') timeline = models.ForeignKey(Timeline, related_name='trating') rating = models.CharField(max_length=25,choices=RATING_CHOICES) Views.py def f_page(request, Function_id): assignments = Function.objects.get(id=Function_id) time = Timeline.objects.all() ratings = NewRating.objects.all() context = { 'assignments': assignments, 'time' : time, 'ratings' : ratings, } return render (request, 'project/pager.html', context) HTML <div id=for_rat> {% for rated in time %} <form action= "/project/rated" method='POST'> {% csrf_token %} {{rated.segment}} <input type="hidden" name="year" value="{{rated.year}}"> <input type="hidden" name="month" value= "{{assignments.id}}"> <select name="ratings"> <option value="">Choose From List</option> {% for rating in ratings %} <option value="{{rating.choices}}">{{rating.choices}}</option> {% endfor %} </select> {% endfor %} <input type="submit" value="Save"> </form> </div> Using {% … -
How to make a UserOwnerMixin - django
I have dashboard for registered users but I need to make sure that dashboard must be accessed by their owner only here is my urls.py #urls.py url(r'^dashboard/(?P<username>[-\w]{5,30})/$',views.DashboardView.as_view(),name= 'user_dashboard'), I need a mixin that make sure username in url = authenticated user if not then it automatically redirect to authenticated user dashboard. Thanks in advance for help and giving me time. -
Custom Django session management with external authentication
I have a question regarding authentication. Let's say i have a Django app where i only want users from an another user-database API to login. Is it possible to use Django's session authentication, but without having to create them as a user in Django's user backend? I'm using Django's rest framwork. Auth flow: Post a request to another user-database API with username and password. Status code 200 if user exists. Use Django's (if posssible) session authentication to manage this new session, so the user doesn't have to login on every refresh, but not be logged in permanently either. Be able to logout, too I know about the different kinds of auth for django-rest-framwork but they all seem to wanna have a user created in their backend. Using django 1.11.3 djangorestframework 3.7.7 -
RuntimeError: Can't resolve dependencies Django Groups with Users
Now I had a problem RuntimeError: Can't resolve dependencies while running tests and after long debugging We found that a forigen key relationship is the problem Yet we need this relation in our app The models like that: class UserAccount(AbstractUser): arabic_name = models.CharField(max_length=128, default='', blank=True) django.contrib.auth.models import Group Group.add_to_class('owner', models.ForeignKey('users.UserAccount', blank=True, null=True, related_name='groups_created' )) As I need to define an owner to the groups as I have my specific hierarchy system for users so no one can see others groups So what Can I do? -
Django + Jquery AJAX form.serialize
I am posting form data using post method through Jquery AJAX. All data is successfuly posted to server except one hidden text field in form and its value is not getting post. Please help me. Thank you. Below is a piece of code. // Below line prints its value successfully console.log($("#daily_reading_detail_id").val()); $.ajax({ type: "POST", url: "/report/update-payment-report/", data:$('#update_payment_report_form').serialize() + '&add_mr_counter='+add_mr_counter+'&add_bd_counter='+add_bd_counter, success: function(response) { if (response.success == 'true'){ toastr.success("Updated successfully"); get_payment_values(); $('#update_payment_report_modal').modal('hide'); $('#update_payment_report_form').trigger("reset"); for (i=0,j=0; i<add_mr_counter || j<add_bd_counter; i++,j++){ $('#mr_row_'+i).remove(); $('#bd_row_'+j).remove(); } add_mr_counter = 0; add_bd_counter = 0; } }); -
Change title of object django admin 'Select %object% to change'
How to change the header of model object, i mean no verbose_name, i need to completely change this string to custom. example -
Django: Return matching and non-matching records
I am trying to implement an OUTER JOIN functionality with existing Django features/commands. I have this model: class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') # single quotes (') because User table is defined down the code. clinic = models.ForeignKey(Clinic, related_name='clinicsF') and class User(AbstractUser): clinics = models.ManyToManyField(Clinic, through='ClinicDoctor', related_name='doctors') I need to get list of all doctors along with their associated clinics. I am able to get the list if they have clinics associated with them. But I am not able to get those doctors who have no clinics linked to them. I tried this: doctorsQuerySet = ClinicDoctor.objects.filter(doctor__groups__name='Doctor').distinct() It doesn't work as it does sort of INNER JOIN This query will give me all the doctors. But I don't know who to proceed to fetch all doctors irrespective clinic associations. doctorsQuerySet = User.objects.filter(groups__name='Doctor').order_by('full_name') I have to show clinics along with doctors, if they have any. It seems to be functionality similar to OUTER JOIN. How do we do it in Django? Thank you. -
Django translation don't change language
Hello i have next situation: In settings.py: LANGUAGE_CODE = 'ru-ru' LOCALE_PATHS = ( os.path.join(BASE_DIR, "locale"), ) LANGUAGES = [ ('en', 'English'), ('ru', 'Russian'), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True In urls.py i have: url(r'^i18n/', include('django.conf.urls.i18n')), #url(r'^jsi18n/$', javascript_catalog, js_info_dict, name='javascript-catalog'), url(r'^admin_tools/', include('admin_tools.urls')), Language change form: <form id="lang-bar" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input class="button" type="submit" value="{% trans 'Change' %}" /> </form> I have created locale and translated and compile it, but when i click change the language isn't change. It other project where LANGUAGE_CODE = 'en-us' this code work great -
Django staticfiles not found
Help me please! I feel like bad wizard, my kind of magic ...doesn't work... Python 2.7.13 , django.VERSION (1, 8, 0, 'final', 0) &: INSTALLED_APPS = ( [...] 'django.contrib.staticfiles', &: STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( ('static', os.path.join(os.path.dirname(BASE_DIR), 'static')), ('node_modules', os.path.join(os.path.dirname(BASE_DIR), 'node_modules')), ) &: $ python manage.py findstatic rarrow.png --verbosity 2 No matching file found for 'rarrow.png'. Looking in the following locations: /home/user/Pulpit/geoHP/static <-- here IS this file !!!!!!! for sure! /home/user/Pulpit/geoHP/node_modules /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static /usr/lib/python2.7/dist-packages/django_tables2/static /usr/local/lib/python2.7/dist-packages/djng/static More over, on web content is properly url for files and css and js, but of course doesn't work... The static dir and files privileges are '777'. I have no idea what should I check or do more... somebody helps? -
Submit search query along with another form
I have a Web page where there is a form with filters. On submitting this form a table with the results is displayed. Now I want to add a search field in a second form above the table , which, when submitted, further eliminates the results. How can the search query be submitted along with the filters' values simultaneously and vice versa? Is there a non js way as well? -
Not able to display the Content of Table
models.py has class Question(models.Model): Question_Id = models.AutoField(primary_key=True) Question_Text = models.TextField(max_length=1000) def __str__(self): return self.Question_Text def __int__(self): return self.Question_Id class QuestionChoices(models.Model): Choice_Id = models.AutoField(primary_key=True) Question_Choices_Question_Id = models.ForeignKey("Question", on_delete=models.CASCADE) Choice = models.TextField(max_length=500) Is_Right_Choice = models.BooleanField(default=False) views.py file has the below def QuestionDisplay(request): retrieved_questions_id = Question.objects.values("Question_Id") retrieved_questions = Question.objects.filter(Question_Id = retrieved_questions_id) display_content = {retrieved_questions_id: retrieved_questions} return render(request, 'cgkapp/Question_page.html', context=display_content) templates folder questions.html has {% block body_block %} <table> <thead> <th>Questions</th> </thead> {% for quest in display_content %} <tr> <td>{{quest.Question_Text}</td> </tr> {% endfor %} </table> {% endblock %} The page displays the Questions as the Table header but not the actual questions from the models. What could be the reason? -
Glitch in dynamically generated formset using JQuery
I have a form created with dynamic child forms create using this plugin - https://github.com/elo80ka/django-dynamic-formset. Everything works fine. It's just that when a validation error comes up the button to generate new form line dynamically gets repeated. Ideally, this button should only be present once at the end. Please look at the image below. Can someone advise how to fix this issue? Relevant codes: forms.py class POHeaderForm(forms.ModelForm): class Meta: model = POHeaderModel fields = '__all__' def __init__(self, *args, **kwargs): super(POHeaderForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'} class POBodyForm(forms.ModelForm): item_number = forms.ModelChoiceField(queryset=InventoryModel.objects.all(), required=False) class Meta: model = POBodyModel fields = '__all__' def __init__(self, *args, **kwargs): super(POBodyForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'} self.empty_permitted = False def clean(self): item = self.cleaned_data.get('item_number') description = self.cleaned_data.get('description') if item is None and description is None: raise forms.ValidationError("Please fill either item number or description") POFormSet = forms.inlineformset_factory(POHeaderModel, POBodyModel,form=POBodyForm, extra=1) Models.py alphanumeric = RegexValidator(r'^[0-9a-zA-Z .-]*$', 'No special characters are allowed.') # Create your models here. class POHeaderModel(models.Model): date = models.DateTimeField(blank=False, default=timezone.now) reference = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True) supplier = models.ForeignKey(SuppliersModel, on_delete=models.PROTECT) note = models.CharField(validators=[alphanumeric], max_length=300, blank=True, null=True) total = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(0)]) class POBodyModel(models.Model): PO = models.ForeignKey(POHeaderModel, … -
Django : How to add/remove/update translation phrases (in po files) in django admin area?
How can we manage translation phrases stored in local\fa\LC_MESSAGES\django.po files by Django Admin area ? I am looking for a package which able to update and compile django translation files like updating models in django Admin area I am using Django 1.10 -
How to restrict foreign key objects for autocomplete search results in django ModelAdmin.autocomplete_fields?
Following this answer, I was able to filter foreign keys choices to select: But when I mark spm as autocomplete_field:autocomplete_fields = ['spm'], the spm field becomes from select field to autocomplete search field: But the foreign key choices are not restricted as configured in "formfield_for_foreignkey" any more. Even when I am attaching the widget inside formfield_for_foreignkey method, spm autocomplete options are getting restricted: @admin.register(CustomModel) class CustomModelAdmin(admin.ModelAdmin): #autocomplete_fields = ['spm'] search_fields = ['name'] def get_form(self, request, obj=None, **kwargs): request.current_object = obj return super(CustomModelAdmin, self).get_form(request, obj, **kwargs) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'spm': instance = request.current_object if instance.brand and instance.memory_size: filtered_qs=StandardProductWithMemorySize.objects.filter( product__brand=instance.brand, memory_size=instance.memory_size ) kwargs['queryset'] = filtered_qs db = kwargs.get('using') kwargs['widget'] = AutocompleteSelect(db_field.remote_field, self.admin_site) return super( CustomModelAdmin, self ).formfield_for_foreignkey(db_field, request, **kwargs) -
getting values of QuerySet in django
how can I get value of course_code in this QuerySet ? <QuerySet [{'course_code': 11}]> -
The field polls.UserProfile.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'
So I've been using the website: https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username To build a section of my project, but I keep getting the error ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field calendarium.Event.created_by was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field calendarium.Occurrence.created_by was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.Clipboard.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.File.owner was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.Folder.owner was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.FolderPermission.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field polls.UserProfile.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. My App name is called polls, I've made sure that 'polls' is installed in my settings and AUTH_USER_MODEL = 'polls.User' To tell Django that this is the model I want to use. My models.py looks … -
django only allowing super user for authentication
I am getting problem with django authentication, Only superuser is able to authenticate. Here is my Model #models.py class UserManager(BaseUserManager): def create_user(self, username, email, password): if not email: raise ValueError('Users must have an email address') elif not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuse.................. class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name='username', max_length=30, unique=True, ) phonenumber = PhoneNumberField(verbose_name="phonenumber",max_length=13, null=True,unique=True) name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' ............. In my setting I added this. #settings.py AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.MyPhonenumberBackend', ) This is my backend #backends.py from django.contrib.auth import get_user_model class MyPhonenumberBackend(object): def authenticate(self, username=None, password=None): my_user_model = get_user_model() try: user = my_user_model.objects.get(phonenumber=username) if user.check_password(password): return user except my_user_model.DoesNotExist: return None except: return None def get_user(self, user_id): my_user_model = get_user_model() try: return my_user_model.objects.get(pk=user_id) except my_user_model.DoesNotExist: return None My views #views.py def seller_login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('home')) else: return HttpReponse('Account is not active') else: print('Someone tries to login and failed') print('username: {} and password {}'.format(username,password)) return … -
How to use pdfsizeopt in Django python
I am using pdfsizeopt to reduce pdf sizes. it is working fine when I run it in windows CMD but not working Django Python code. Flow : I am uploading a file and then trying to resize it code is following def sizeofpdfs(request,uploaded_file_name): try: fs = FileSystemStorage() uploaded_file_url = fs.url(uploaded_file_name) new_filename = fs.url(uploaded_file_name.split(".")[0]+"_new.pdf") command = "pdfsizeopt "+ uploaded_file_url +" smallsize.pdf" p = subprocess.call(command, shell=True) if p==0: return new_filename except subprocess.CalledProcessError as e: print('CalledProcessError', e) File get uploaded when it try to resize it throws the following error. It is a path error. Can someone suggest me the correct way to use it. -
Django: Can I use objects.filter() for generic foreignkey?
symbol.py class Symbol(BaseModel): name = models.CharField(max_length=30,) class Meta: abstract = True class StockSymbol(Symbol): market = models.CharField(max_length=10,) my_daily_price = GenericRelation(MyDailyPrice) daily_price.py class DailyPrice(BaseModel): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: abstract = True class MyDailyPrice(DailyPrice): open = models.DecimalField( max_digits=15, decimal_places=2, ) What I want to do is, symbol = StockSymbol.objects.first() MyDailyPrice.objects.filter(content_object=symbol) But it occured errors: FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. StockSymbol already has GenericRelation. What's wrong with it? Or do I have to override ojbect manager? -
How do I remove default whitespace in template?
I'd like to list a series of items separated by commas. But if an item after the first doesnt exist, I don't want the comma or item to appear. So I've implemented this: <em>{{object.item1|default_if_none:""}}</em> {% if object.item2 %} <em>, {{object.item2|default_if_none:""}},</em> {% endif %} <em>{{object.item3|default_if_none:""}}</em> If object.item2 exists, it'll put a whitespace after item1--before the comma. When it displays, it'll look something like: "I_am_item_one , I_am_item_two, Item_three" What's the best way to fix this? -
How to make django register users with emails instead of username
I am trying to make a website that registers users with first name, last name, email, and password. I have tried writing this form and using it in the views from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegisterationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'password1', 'password2', ) def save(self, commit=True): user = super(RegisterationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user and using it in the views from django.shortcuts import render, redirect from Users.forms import RegisterationForm from django.contrib.auth import authenticate, login def home(request): return render(request, 'Users/index.html') def map_page(request): return render(request, 'Users/map_page.html') def register (request): if request.method == 'POST': form = RegisterationForm(request.POST) if form.is_valid(): form.save() return redirect('/LoginPage/') else: form = RegisterationForm() args = {'form': form} return render(request, 'Users/index.html', args) However when I do it this way and I fill it in I get an error of UNIQUE constraint failed: auth_user.username I was wondering if there is a way to not use a username and have them signup and login with password and email. I have tried making a backend and included it in the settings and that did not work. … -
Creating Single-Page Application in Python
So I have an application that is written in Python and I want to create a single-page application that allows others to use it. One possible solution is to use Django but I don't want to keep persistent databases on the server. The application is small enough for it to work in-browser on the client's side but the only SPA frameworks I can see seem to use Javascript client-side which would be a problem for me. Is there any way to create an app that meets these requirements? -
Nested serialization Django Rest Framework
Hello guys i'm back again i have a little trouble about my problem. I want to create Account in my Django Project. I extend user model using OneToOneField. here is my mode.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=15, unique=True, null=False, blank=False) birth_date = models.DateField() address = models.TextField() district = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district') created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_at', ] def __str__(self): return self.user.username and here is my serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='account.id', read_only=True) phone_number = serializers.CharField(source='account.phone_number') birth_date = serializers.DateField(source='account.birth_date') address = serializers.CharField(source='account.address') class Meta: model = User fields = ( 'id', 'first_name', 'last_name', 'username', 'email', 'password', 'phone_number', 'birth_date', 'address' ) def update_or_create_account(self, user, account_data): Account.objects.update_or_create(user=user, defaults=account_data) def create(self, validated_data): account_data = validated_data.pop('account', None) user = super(UserSerializer, self).create(validated_data) self.update_or_create_account(user, account_data) return user def update(self, instance, validated_data): account_data = validated_data.pop('account', None) self.update_or_create_account(instance, account_data) user = super(UserSerializer, self).update(instance, validated_data) return user class AccountSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) created_at = serializers.DateTimeField(read_only=True) class Meta: model = Account fields = ( 'user', 'district', 'created_at' ) and here for views.py class AccountList(APIView): def get(self, format=None): account = Account.objects.all() serializer = AccountSerializer(account, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = AccountSerializer(data=request.data) if User.objects.filter(email=request.data['user']['email']).exists(): return Response(data={'email': 'Email already taken, use another email'}, status=status.HTTP_400_BAD_REQUEST) … -
how to construct this Django ORM queryset query?
I'm trying to determine how to construct a query. I have two models from an external database that I"m trying to import into a different schema. The source data has two tables: - Group (basically, a musical band.) - Membership (a list of those in the band through time) In the Memberships, I have fields representing the person and band, with create dates and update dates, as well as other relevant data. Here's the problem: the Membership rows don't have any field that represents which is the canonical record, and they mix and match persons and dates and other data. What I'm doing currently is taking all the Memberships for a given band, running distinct on them for the combination of band and person and using those results to query the Memberships again for the latest instance of each particular combination. While this works, as you might imagine is is unspeakably slow and I know there must be a better way. So I'm looking for how to use some of the advanced django query expressions (Window? Over, F-expressions?) to get this done as much as possible on the database. Here is the code that is getting me the records I … -
creating models inctances from button click
I am new to django and I build an online restaurant website as a task . I have a problem in getting orders into data base . here are the codes models.py from django.db import models from django.contrib import admin from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User) phone = models.IntegerField() address = models.CharField(max_length=500) def create_profile(sender , **kwargs): if kwargs['created'] : user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile , sender=User) class Category(models.Model): category_title = models.CharField(max_length=100 , unique=True) def __str__(self): return self.category_title class Order (models.Model): time = models.DateTimeField(auto_now_add=True) total = models.IntegerField() created_by = models.ForeignKey(User, related_name='orders') class Item (models.Model): name = models.CharField(max_length=100 ,unique=True) details = models.CharField(max_length=1000) price = models.IntegerField() item_logo = models.FileField() category = models.ForeignKey(Category, related_name="items" ,on_delete= models.CASCADE) order = models.ForeignKey(Order, related_name="orderItems", null=True, blank=True) def __str__(self): return self.name class ItemInline(admin.TabularInline): model = Item class CategoryAdmin(admin.ModelAdmin): inlines = [ ItemInline, ] views.py from django.http import Http404 from .models import Category, Item , Order from django.shortcuts import render, redirect from django.core.urlresolvers import reverse_lazy from django.contrib.auth import authenticate , login from django.views import generic from django.views.generic import View from .forms import UsrForm class IndexView(generic.ListView) : template_name = 'res/base.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() def detail(request, category_name): try: category = Category.objects.get(category_title = …