Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show and Edit M2M filelds in both Admin Panel Models (django-select2)
I have some problem with ModelSelect2MultipleWidget when I set him for custom field. models.py class Product(GenerateUniuqSlugMixin, BaseAbstractModel): name = models.CharField( verbose_name='Имя', max_length=255 ) slug = models.SlugField( verbose_name='Url', max_length=100 ) description = models.TextField( verbose_name='Описание', blank=True ) price = models.ManyToManyField( 'Price', verbose_name='Цена', blank=True, related_name='products' ) class Price(BaseAbstractModel): code = models.CharField( verbose_name='Уникальный Код', max_length=100, unique=True, db_index=True ) price = models.DecimalField( verbose_name='Цена', max_digits=16, decimal_places=2 ) creation_date = models.DateField( verbose_name='Дата добавления', auto_now_add=True ) update_date = models.DateField( verbose_name='Дата обновления', auto_now=True ) I want have opportunity for searching and connecting products from Price Admin Panel. And I added for forms next code: class PriceAdminForm(forms.ModelForm): products = forms.ModelMultipleChoiceField( queryset=Product.objects.all(), widget=ModelSelect2MultipleWidget( model=Product, queryset=Product.objects.all(), search_fields=['name__icontains'], attrs={'data-placeholder': 'Поиск в товарах', 'data-width': '50em'} ), required=False ) class Meta: model = Price fields = ( 'code', 'name', 'price', 'products', ) But it's not working and I don't know why, where my mistake? If I remove ModelSelect2MultipleWidget from widget attr I see default choice field, but he don't remeber my save choice he just show all queryset. It will be great if I can see input field which offer ModelSelect2MultipleWidget. Thank's. My environment: Django==2.0.2 django-select2==6.0.1 -
Django: Include template with variables rendered from views.py into another template
I have a template plot.html inside app plot: <div> {{ plot|safe }} </div> some other divs here The plot variable is calculated from views.py inside app plot: class RenderView(TemplateView): def __init__(self): self.template_name = "plot.html" def get_context_data(self, **kwargs): context = super(RenderView, self).get_context_data(**kwargs) context['plot'] = PlotView().make_plot() return context Now I want to include this template with the generated plot and other divs into another template from another app, another.html: {% include "plot.html" %} of course this does not generate the plot and other info from the views.py file. I've been reading about template tags (https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/), but I'm unsure what goes into poll_extras.py there or if tags is the right solution. -
automatically changing model field in Django
Consider a Blog model as below: class Blog(models.Model): text = ... stage = ... # ChoiceField Blog.stage describes the current stage the blog is in which can take many values like edit, content verification, tag etc. Transition from one stage to another is based on a condition. In content verification stage, a user verifies the content of the model and corresponding entries are recorded in the following model. class ContentVerificationModel(models.Model): user = ... #verifier blog = ... # blog being verified do_you_verify_blog_content = ... # BooleanField To move from content_verification_stage to next stage, say, edit stage, following conditions must be satisfied: Blog must be verified by some minimum number of people (Say, 10) Percentage of people who voted for the blog must be greater than some minimum value (say, 60 i.e. 6 out 10 entries for a blog must have do_you_verify_blog_content value as True) How do I manipulate my code so that a model field can be changed automatically when some conditions are met? -
Prevent/allow a hyperlink click conditionally through Ajax in Django
I'm trying to implement a hyperlink on a page which when clicked, will submit through ajax first, run a couple checks determining whether or not the user has the authority to visit the hyperlink-page, and then either allow them to go through or prevent the hyperlink's default action(and raise errors). I've set up the code, and the ajax request will go through, but will not be handled server-side. Here is the template code: <a class='btn btn-primary pairing-CTA-btn' href="{% url 'profile:request' object.user %}">Send {{object.user | upper}} a Request</a> The js: $(document).ready(function(){ var $myButton = $('.pairing-CTA-btn') $myButton.click(function(event){ var $buttonData = $(this).serialize() var $endpoint = $myButton.attr('data-url') || window.location.href // or set your own url $.ajax({ method: "GET", url: $endpoint, data: $buttonData, success: handleSuccess, error: handleError, }) }) function handleSuccess(data, textStatus, jqXHR){ // No need to do anything here. Allow link click. console.log(data) console.log(textStatus) console.log(jqXHR) } function handleError(jqXHR, textStatus, errorThrown){ // on error, prevent default, bring up errors event.preventDefault() // $('.pairing-CTA-btn-errors').text("YOU SHALL NOT CLICK BUTTON"); // $('.pairing-CTA-btn-errors').show(); console.log(jqXHR) console.log(textStatus) console.log(errorThrown) } }) The View where this link exists: class ProfileDetailView(AjaxRequestButtonMixin, DetailView): template_name = 'user_profile/profile_detail.html' And the ajax mixin referenced above: class AjaxRequestButtonMixin(object): def button_allowed(self): print("AJAX") # response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): # PERMISSION-TO-CLICK-LINK … -
Run Angular App, Django Backend and MySql on separate servers
We are trying to build a system with Angular as frontend, Django as backend and MySql as database. We want all three to run on separate servers (standalone angular app and django back end). Have gone through various blogs/docs/questions-answers on internet but have not found similar setup. Our question basically is if we develop separate angular app and django back end the How Angular App will communicate with Django Backend (how routing would be done? or simply by using DRF rest services?) and How Django would communicate to MySql. If someone could point to few examples? -
Django Form submissions - from source code
Hello I'm using the plugin FORMS in Dajngo. In admin panel I have access to Form submissions. I need get access to Form submissions from the source code, like: fs = FormSubmissions.objects.all() I can't find information how can I do it. Thank you for help. -
How to dynamically assign values to a Django model from a dictionary? [duplicate]
This question already has an answer here: How do you programmatically set an attribute? 3 answers I have following attributes for a Django model: charfields = [ 'title','author','rating' ] for f in charfields: locals()[f] = models.CharField(max_length=30, blank=True) I want to assign the values from item in the following function: def process_item(self, item, spider): post = Post() for f in post.charfields: setattr(post, str(f), str(item[f])) print(post.author) #this works print(post) #this prints none .. post.save() -
Django many-to-many serialization
I want to create a model (Source) with many-to-many relation to the another model (Tag) and create a Source objects without duplicating Tag instance in database. Here is my models: class Tag(models.Model): name = models.CharField(max_length=50, null=False, default='source') def __unicode__(self): return self.name class Source(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) language = models.CharField(max_length=50) color = models.CharField(max_length=50, default='white') isFile = models.BooleanField(default=False) link = models.TextField(default='') file = models.FileField(upload_to='uploads/', null=True) tags = models.ManyToManyField('Tag') class Meta: ordering = ('title',) Here is my serializers: class TagSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = ('name',) class SourceSerializers(serializers.ModelSerializer): tags = TagSerializers(many=True) class Meta: model = Source fields = ('title', 'author', 'language', 'color', 'isFile', 'link', 'file', 'tags') def create(self, validated_data): tags_data = validated_data.pop('tags') source = Source.objects.create(**validated_data) for tag in tags_data: t = Tag.objects.create() t.name = tag.get("name") t.save() source.tags.add(t) source.save() return source But when I try to create Source object via http request - the object is created, but without any references to Tags. After some researching I found that validated_data in create(self, validated_data) doesn't contains "tags" field, also I found that validate function of TagSerializer not invoked at any time. What I'am doing wrong? -
Django REST FrameWork JWT does not allow to provide data or decode itself
I have these endpoints: urlpatterns += [ path('api-token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), path('api-token-refresh/', refresh_jwt_token), path('api/', include(router.urls)), ] For example I have a User on backend, and let's say hey wants to login to the system. In login page he must provide his username and password, and login page will use "obtain_jwt_token" endpoint, which will automatically check if that user exists or not. If not, backend will return error message, if that User exists and username & password is correct than backend will return a Token, generated by JWT, and that token will live for let's say 1 hour. But the problem is that backend will not return additional data, it will return only Token itself, but not id of that user or something. And that is the problem. Am I understanding something wrong ? All I want is for backend to return not on the Token, but also id of that user. Or to decode the Token, and get id of User from it. -
Django: show OTP verification dialogue right after submitting form in a modal
First website. I am using Django. I am stuck with implementing this functionality. I right now am able to show a signup form in a modal dialogue and also I can save the details to backend. Now I want to add OTP step to the signup process. What I don't know is how do I move to OTP modal for phone number verification without losing user detail form in the modal. After user enters the correct code how do I save the details that were filled up in previous(signup) modal? So it is two steps: 1. Show Signup Modal. 2. Show OTP verification Modal. How to go to step 2 without losing data entered in step 1. Can anyone please give me an example or idea how it is done? Thank you. -
When a django project deploy on Nginx use uwsgi
I deploy my django project on the Nginx server use uwsgi, and it can access the static files,but when I input my domain on the browser,there is '400 Bad Request' -
Django 2 tables one view
I try to make a simple illustration of my question click to view I have a task to make a quiz. I try to solve a problem : Taking items in cycle by "Metrix" model there I get Questions for Quiz It is no way to get data from "User_metrix" model while using {% for item in metrix_list %} cycle by "Metrix" model. My models: from django.db import models from django.conf import settings class Metrix(models.Model): title = models.CharField(max_length=256, verbose_name='Question') metrix_category = models.ForeignKey( 'category', related_name='Question_category', on_delete=models.CASCADE, verbose_name='Category', ) is_published = models.BooleanField(default=False) def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=256, verbose_name='Question_category') is_published = models.BooleanField(default=False) def __str__(self): return self.title class User_metrix(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_metrix", verbose_name='User') metrix = models.ForeignKey('Metrix', on_delete=models.CASCADE, verbose_name='Question') value = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Value') My view: from django.shortcuts import render from django.contrib.auth.decorators import login_required from metrix.models import Metrix, User_metrix @login_required def metrix_view(request, pk=None): metrix_category = { 'pk': 4 } #Get questions by category metrix_list = Metrix.objects.filter(is_published=True, metrix_category__pk=pk) context = { 'metrix_list': metrix_list } return render(request, 'metrix/metrix.html', context) Template: I list the questions in template, by cycle "metrix_list" How to save answers to values and if answers exists return values to template? <!--cycle for metrix--> {% for item in … -
Extend Django Admin UserCreationForm with OneToOneField
I'm trying to extend the django admin UserCreationForm to include a field from another table related on a OneToOneField. This is my related table: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) supervisor = models.ForeignKey( User, related_name='supervisor', on_delete=models.DO_NOTHING, blank = True, null = True ) And my admin form: from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from django import forms class EmailRequiredMixin(object): def __init__(self, *args, **kwargs): super(EmailRequiredMixin, self).__init__(*args, **kwargs) # make user email field required self.fields['email'].required = True class MyUserCreationForm(EmailRequiredMixin, UserCreationForm): supervisor = forms.Select() class Meta: model = User fields = ['username',] def save(self, commit=True): if not commit: raise NotImplementedError("Can't create User and UserProfile without database save") user = super(MyUserCreationForm, self).save(commit=True) profile = Profile(user=user, supervisor=self.cleaned_data['supervisor']) profile.save() return user, profile class EmailRequiredUserAdmin(UserAdmin): inlines = [ProfileInline, ] list_display = ['username', 'email', 'first_name', 'last_name', 'is_staff', 'get_supervisor', 'get_is_supervisor', 'get_is_project_manager'] form = MyUserChangeForm add_form = MyUserCreationForm add_fieldsets = ((None, {'fields': ('username', 'email', 'password1', 'password2'), 'classes': ('wide',)}),) def get_supervisor(self, instance): return instance.profile.supervisor get_supervisor.short_description = 'Supervisor' def get_is_supervisor(self, instance): return instance.profile.is_supervisor() get_is_supervisor.short_description = 'Is Supervisor' def get_is_project_manager(self, instance): return instance.profile.is_project_manager() get_is_project_manager.short_description = 'Is Project Manager' def get_inline_instances(self, request, obj=None): if not obj: return list() return super(EmailRequiredUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, EmailRequiredUserAdmin) … -
How to write primary key in django 2.0.2
the below code is working only for index page but it's not working for my DetailView. Please help me to fix (Using Django 2.0.2) The below is my class for view: from django.views import generic from .models import Album class IndexView(generic.ListView): template_name = "newboston/index.html" context_object_name = "all_album" def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'newboston/detail.html' The below is my urls.py under my application. from . import views from django.urls import path urlpatterns = [ path('', views.IndexView.as_view(), name='home'), path('<slug:slug>/', views.DetailView.as_view(), name='detail'), ] -
Django Debug Toolbar: Log section cleared every time a page is loaded
I'm experimenting with Django Debug Toolbar, everything works fine except I can't see "historic" Log Entries in the log Panel. Here's an esample of the Dhango views file, used for testing purposes from django.shortcuts import render #logging import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # Create your views here. def home(request): logger.debug('Home view called') return render(request, 'main/home.html') def news(request): logger.debug('News view called') logger.debug('News view called 2nd time') return render(request, 'main/news.html', {'content': "That's some kind of news"}) If I call the home page, in the log file I can see just: Home view called Then If I call the news page, in the log file I can see just: News view called News view called 2nd time Every time I call 'Home' or 'News' the Log is cleared Is there a way to instruct Django Toolbar to keep/show previous entries? Am I missing something? Thank you -
In django, how to disable the use of EmailValidator?
Base on AbstractBaseUser, I create my own profile. In the profile class, I define, def nonfunc(self): pass email = models.EmailField( verbose_name='email address', max_length=255, unique=True, primary_key=True, validators = [nonfunc,nonfunc], ) I do not want to use the email validation from django and I disable html5 validation. <form method="post" novalidate> But when I entered a invalid email and then submit the form, It returned Enter a valid email address. How to exactly disable the django default email validation? -
How do I display my views output variable in my template in Django?
I have my Django views.py function : def dsctbl2(request): dynamodb=boto3.client('dynamodb', region_name='us-west-2') response = dynamodb.scan( TableName='User-Account') filtered = response['Items'] length = len(filtered) a = [] for k in range(length): accnum = filtered[k]['AccountNum']['S'] uid = filtered[k]['UserId']['S'] f = {} f = dict(AccountNum=accnum,UserId=uid) a.append(f) return (a) The above function filters the UserId and Accountnumber items from a dynamodb table. I need to display the "UserId" and "AccountNum" in my html template in a table's row. Here's my html snippet : <div class="mytable"> <table style="width:96%" class="table table-responsive"> <thead id="head" class="mdb-color lighten-4"> <tr> <th></th> <th class="th-lg">User ID</th> <th class="th-lg">Account Number</th> </tr> </thead> <tbody> {% for r in rows %} <tr> <th scope="row"></th> <td>{{r.AccountNum}}</td> <td>{{r.UserId}}</td> </tr> {% endfor %} </tbody> </table> </div> I've included block content and endblock tags in my html code . What am I doing wrong here ? I'm a beginner in Django. Thanks in advance -
Extra form on ModelFormSet
For my Django project, I am rendering the model formset election_formset = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet) in my template: <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} <div class='card'> <div class='card-body w-75 mx-auto'> <div class='row'> <div class='col-6 text-center'> <p>Name<br>{{form.Name}}</p> </div> <div class='col-6 text-center'> <p>Videos<br>{{form.FlipGrid}}</p> </div> </div> <div class='row'> <div class='col-12 text-center'> <p>Description<br>{{form.Description}}</p> </div> </div> <div class='row'> <div class='col-6 text-center'> <p>Allow registration: {{form.CandidateReg}}</p> </div> <div class='col-6 text-center'> <p>Allow voting: {{form.VotingOpen}}</p> </div> </div> </div> </div> {% endfor %} </form> When the formset renders, an extra, blank form is shown at the end of the forms. I only want forms to show that are instances of existing records. Why is there an extra blank formset and how can I prevent it? -
Error: 'QuerySet' object has no attribute, even if the attribute exist
I have the following code: company = Company.objects.filter(account=self.account).only('slug') if company: return redirect(reverse_lazy('company:detail_a', kwargs={'slug': company.slug})) I get the error: 'QuerySet' object has no attribute 'slug' The slug attribute definitely exist(checked in model/database). I tried to access it like in a template. So I tried with other attributes, 'name', because appears when I print the QuerySet. So I think the QuerySet is not evaluated or something like that, but I don't know how to force to do it. -
Django admin: how to predefine field values?
I use Django 1.11.10 and python 3.6; I have Category model that has name and parent. Parent field links to itself. But when I create new Category model, I want choose parent from already created categories that have no parents. So how to predefine this list? class Version(models.Model): name = models.CharField(max_length=50, unique=True) parent = models.ForeignKey('self', null=True, blank=True) ------ class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ['name', 'parent'] class CategoryAdmin(admin.ModelAdmin): form = CategoryForm admin.site.register(Category, CategoryAdmin) -
Mailgun Email sender isn't what its supposed to be
So ive just set up django emails with mailgun, and sent the first email. This is the config I have in Django: EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') EMAIL_HOST = config('EMAIL_HOST', default='') EMAIL_PORT = config('EMAIL_PORT', default=587, cast=int) EMAIL_HOST_USER = 'postmaster@mg.smartsurvey.xyz' EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='') EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool) DEFAULT_FROM_EMAIL = 'SmartSurvey <noreply@smartsurvey.xyz>' This is the view that sends the email: current_site = get_current_site(request) subject = 'Activate your SmartSurvey account' message = render_to_string('email/email_activation.html', { 'name': user.get_full_name(), 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) And I want the sender to be SmartSurvey <noreply@smartsurvey.xyz>, however it currently sends like: noreply=smartsurvey.xyz@mg.smartsurvey.xyz on behalf of SmartSurvey <noreply@smartsurvey.xyz> How can I go about fixing this? -
Djagno many to many relationship. How to get all rows which primary key doesn't exist on another table?
I've 3 models A, B and C. they are as follows: class A(models.Model): name=models.TextFeild() class B(models.Model): name=models.TextFeild() class C(models.Model): a=models.models.ForeignKey(A, on_delete=models.CASCADE, related_name='as') b=models.models.ForeignKey(B, on_delete=models.CASCADE, related_name='bs') I want to get all B's which exist in C with A.name = 'jhon' I've tried taken_tests = C.objects.filter(a.name='jhon') queryset = B.objects.filter().exclude(pk__in=taken_tests) But this gives me all B's. -
Django Rest Docker with MySQL create a superuser
I have dockerized my existing Django Rest project which uses MySQL database. My dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt And my docker-compose.yml file: version: '3' services: web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code depends_on: - db ports: - "8000:8000" db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: libraries MYSQL_USER: root MYSQL_PASSWORD: root My commands docker-compose buildand docker-compose up are successful and output of later is: D:\Development\personal_projects\library_backend>docker-compose up Starting librarybackend_db_1 ... done Starting librarybackend_web_1 ... done Attaching to librarybackend_db_1, librarybackend_web_1 db_1 | 2018-02-13T10:11:48.044358Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). db_1 | 2018-02-13T10:11:48.045250Z 0 [Note] mysqld (mysqld 5.7.20) starting as process 1 ... db_1 | 2018-02-13T10:11:48.047697Z 0 [Note] InnoDB: PUNCH HOLE support available db_1 | 2018-02-13T10:11:48.047857Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins db_1 | 2018-02-13T10:11:48.048076Z 0 [Note] InnoDB: Uses event mutexes db_1 | 2018-02-13T10:11:48.048193Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier db_1 | 2018-02-13T10:11:48.048297Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 db_1 | 2018-02-13T10:11:48.048639Z 0 [Note] InnoDB: Using … -
django postgres LIKE query syntax error at or near "%"
In django, to query JSONB, I do: cursor.execute("""\ SELECT * FROM "somemodel_some_model" WHERE UPPER(("somemodel_some_model"."data" #>> array[0,'fieldX'])::text[]) LIKE UPPER(% %s %) """,[my_string]) .. and I get: IndexError: list index out of range To investigate this, I drop to SQL and do the following: SELECT * FROM "somemodel_some_model" WHERE UPPER(("somemodel_some_model"."data" #>> array[0, 'fieldX'])::text[]) LIKE UPPER(%my_search_string%) ..but, I get: django.db.utils.ProgrammingError: syntax error at or near "%" So, the question is, do I need to escape %? Seems odd -
Django admin: how iterate over form attributes in ModelAdmin
I use Django 1.11.10 and python 3.6; I need to iterate form values in admin. How to do that? class ServerForm(forms.ModelForm): class Meta: model = Server def clean(self): setattr(self, 'field1', 'value1') setattr(self, 'field2', 'value2') class ServerAdmin(admin.ModelAdmin): form = ServerForm def save_model(self, request, obj, form, change): # this works # but how to iterate form? obj.field1 = form.field1 obj.field2 = form.field2 # AttributeError: 'ServerForm' object has no attribute 'items' for key, value in form.items(): setattr(obj, key, value) super(ServerAdmin, self).save_model(request, obj, form, change)