Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
a view with 2 treeviews and drag and drop from one to another
I want to create a form with 2 treeviews (each treeview is based on a table of my database with recursive data). And I want to be able to create a drag and drop form one treeview to the other in odrer to link data between the data tables. I tried django-treenode but i can t understand to use it for doing my view. -
Constrain Django model by field value
Consider the following Django model: class Account(models.Model): ACCOUNT_CHOICES = [ ('m', 'Main',), ('s','Secondary') ] user = models.ForeignKey(User) level = models.CharField(max_length=1, choices=ACCOUNT_CHOICES) How can I enforce a database constraint of a maximum of one 'Main' account per user, while still allowing any number of 'Secondary' accounts per user? In a sense, I want unique_together for user and level, but only when the value of level is m. I know that I can manually check on saving, but I would prefer the database to check automatically and raise an IntegrityError when appropriate. -
creating custom profiles for selected user types
1.I have multiple type of users in my project. i have created a single signup page. in the signup page i have option to select the type of user.based on the selection a related profile should be created and the type of user should be logged into their particular profile page..for example..if the type of user selected is student then after signup a student_profile should be created and student should be logged into that.. similar for professional and other user types.I have used django auth user model to create signup.. 2. I have many custom profile forms for each user types and no idea how to integrate it..model is below: what Please don't suggest me this link cz i don't wanna go with this approach since they use a signup for each user type but i have only one signup for every user type.. https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html user registration in forms.py: class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).exists(): raise forms.ValidationError(u'Email addresses … -
Add individual users to Project in Django
I am building a basic project management app using Django, where a Project can have any number of users. How can I create a form to add users one at a time? The default behavior of Django provides multi-select fields for many to many relationships. class Project(models.Model): project_number = models.IntegerField() name = models.CharField(max_length=100) design_manager = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_design_manager', null=True, blank=True) permit = models.CharField(max_length=100, blank=True, default='') is_active = models.BooleanField(default=True) users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='project_users') I want a dynamic field that allows you to add one user at a time. -
Create Extended User Object with Django Rest Auth
I'm using django-rest-auth with django-rest-framework. I have the default API endpoints already generated. They appear like so: api-endpoints: { login: { create(password, [username], [email]) } logout: { list() create() } registration: { verify-email: { create(key) } create(username, password1, password2, [email]) } user: { read() update(username, [first_name], [last_name]) partial_update([username], [first_name], [last_name]) } } Now, I want to use a custom model called UserProfile, which extends the default user via a OneToOneField as shown below: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) custom_field1 = models.CharField(...) custom_field2... ... The docs state I should create a custom registration serializer. I did some searching around and figured I could try this code as that custom serializer (with cf as an abbreviation for custom_field for this example): class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): user_dict = super().get_cleaned_data() user_dict["c1"] = self.validated_data.get("cf1", '') user_dict["cf2"] = self.validated_data.get("cf2", '') return user_dict However, this does not create an Account object, when a user registers. My two questions are thus: How can I create an Account object on registration? (Is this the appropriate design decision anyway?) (Possibly related to 1) How can I properly create a custom registration serializer? -
probleme de creation des evenements
importation des bibliothques from django.db import models from django.contrib import admin from django.utils.translation import ugettext_lazy as _ code de la classe calendrier class Calendar(models.Model): name = models.CharField(_('name'), max_length=50) slug = models.SlugField(_('slug'), unique=True) def __unicode__(self): return u'%s' % self.name class Meta: verbose_name = _('calendar') ordering = ['name'] creer un evenement class Event(models.Model): title = models.CharField(_('title'), max_length=100) start = models.DateTimeField(_('start')) end = models.DateTimeField(_('start')) calendar = models.ForeignKey("Calendar", on_delete=models.CASCADE) def __unicode__(self): return u'%s' % self.title class Meta: verbose_name = _('event') ordering = ['start', 'end'] creer un calendier class CalendarAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} admin.site.register(Calendar, CalendarAdmin) class EventAdmin(admin.ModelAdmin): list_display = ('title', 'start', 'end') search_fields = ['title'] date_hierarchy = 'start' svp aidez moi suis vraiment bloqué car les views et les templete meme la ne marchent pas -
trying to access a ManyToManyField from db query but returning None
Im tring to access a ManyToManyFireld property after model query but get back None. This is what the model looks like. class Role(models.Model): ROLES = Choices('user', 'staff', 'admin') user = AutoOneToOneField( 'account.User', related_name='_role', primary_key=True, on_delete=models.CASCADE ) role = models.CharField(max_length=10, choices=ROLES, default=ROLES.user) locations = models.ManyToManyField('location.Location', related_name='_role', blank=True) def __str__(self): return '<Role: user={0} ({1})>'.format(self.user_id, self.role) When i call locations on the Role lookup i get back location.Location.None and this is what the query lookup looks like. user_role = Role.objects.get(pk='123249882323') role_locations = user_role.locations print(role_locations) => location.Location.None I want role_locations to return all the locations associated with the Role -
Generating a page dynamically in Django
I'm tyring to generate a page dynamically in Django but i can't find a way to do this. In my DB, i have a table containing some items, this table is "dynamic"; so i will keep adding and removing items from this table. Now, this is what i would like to do: For each of these times, there should be generated a page containing some data about those items. I created a standard view and a standard template like this: views.py def home(request): return render(request, "main/home.html") home.html {% extends "main/header.html" %} {% block content %} { Here should be data about the X item } {% endblock %} I would like to create something like this: When a page is opened, the user is redirected to a page looking like this: site.com/home/item1 or site.com/home/item2, so instead of the line { Here should be data about the X item }, there should be data about the corresponding item. Can someone give me some help? -
Looking for format for KeywordsField.save_form_data
I have a Mezzanine Project and am trying to update the keywords on a blog entry. I am having difficulty getting the format write to call KeywordsField.save_form_data this invokes a js that will update the keywords on a blog post. See below: class PubForm(forms.ModelForm): class Meta: model = BlogPost fields = ['keywords'] def UpdatePub(request, slug): blog_post = BlogPost.objects.get(id=slug) if request.method == 'POST': form = PubForm(request.POST) if form.is_valid(): publish_date = datetime.datetime.now() blog_post.status = CONTENT_STATUS_PUBLISHED publish_date=publish_date tags=form.cleaned_data['keywords'] blog_post.save() KeywordsField.save_form_data(user,blog_post,tags) return HttpResponseRedirect('/write/') else: form = PubForm(instance=blog_post) return render(request, 'blog_my_pub.html', {'form' : form}) It complains that the field user has no attribute 'name'. I have seen this called with (self,instance,data) as the three parameters. I have no idea what self is. Thanks for any input. -
Django Form not recognising model Attribute
Django doesn't seem to recognise the model object in my custom user form. This is the error: -
Incorrect type. Expected pk value, received str
I am trying to use APIVIew to UPDATE and PATCH. Here are my models: class Moment(models.Model): name = models.CharField(max_length=200, blank=False) start = models.CharField(max_length=50,null=True, blank=True) end = models.CharField(max_length=50, null=True, blank=True) outcomes = models.TextField(blank=True) actionPlan = models.TextField(blank=True) forumLead = models.ForeignKey("ForumLead", related_name='forumlead', on_delete= models.CASCADE) platform = models.ForeignKey("Platform", related_name='platform', on_delete= models.CASCADE) kam = models.ForeignKey("KAM", related_name='kam', on_delete= models.CASCADE) typeOfMoment = models.ForeignKey("TypeOfMoment", related_name='typeofmoment', on_delete= models.CASCADE) bigEvent = models.ForeignKey("BigEvent", related_name='bigevent', on_delete= models.CASCADE) campaign = models.ForeignKey("Campaign", related_name='campaign', on_delete= models.CASCADE) def __str__(self): return "{}".format(self.name) class ForumLead(models.Model): name = ... class Platform(models.Model): name = ... class TypeOfMoment(models.Model): name = ... class BigEvent(models.Model): name = ... class Campaign(models.Model): name = ... class KAM(models.Model): name = ... My Serializer: class MomentSerializer(serializers.ModelSerializer): """Serializer for the Moment Objects""" class Meta: model = Moment fields = '__all__' But I am having a Incorrect type. Expected pk value, received str error I have tried to follow the example here a link, but sincerely I am not understanding how to apply it to my case. Any help will be welcomed. -
Passing the error value to the JS code in template. Django
I have purchased one of the Bootstrap templates. I am trying to pass a value from a view or forms.py to my template <div class="input-group"> <textarea class="form-control" rows="4" name="text" placeholder="Hi there, I would like to ..." aria-label="Hi there, I would like to ..." required data-msg="Please enter a reason." data-error-class="u-has-error" data-success-class="u-has-success"></textarea> </div> Exactly this value data-msg="Please enter a reason." How can I do this? pass the value to the JS code or is it possible? how to change the content of the message which will be displayed by the JS code. Any help will be appreciated. -
Angular + Django Api application deployment using Nginx
I have a web application developed using Angular6 + Django rest framework and hosted in aws. Angular application is deployed to my webserver which is public (ip:3.xx.xx.xx) and Django Api is deployed to my appserver which is private(ip:10.xx.xx.xx) I'm using nginx to reverse proxy to the appserver from web server. From the angular application i'm forming the endpoints to call the api functions. Angular Url: http://3.xx.xx.xx:8083/signup Api endpoint :http://10.xx.xx.xx:8081/api/customer/company_registration/ But I'm getting below error when i try to access the api from browser. POST http://10.xx.xx.xx:8081/api/customer/company_registration/ net::ERR_CONNECTION_TIMED_OUT ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message: "Http failure response for (unknown url): 0 Unknown Error" name: "HttpErrorResponse" ok: false status: 0 statusText: "Unknown Error" url: null __proto__: HttpResponseBase This is nginx config i tried: server { listen 8083; server_name 3.xx.xx.xx; client_max_body_size 20m; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { root /usr/share/nginx/html/; index index.html; } } server { listen 8081; server_name 10.xx.xx.xx; client_max_body_size 20m; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # Handles proxying to Django API location /api/ { #rewrite ^/api(.*) $1 break; add_header 'Access-Control-Allow-Origin' "$http_origin" always; … -
Django-Filer Canonical URLS not working properly (Page not Found)
I am using Django-Filer in my admin on a Django web project which is hosted in PythonAnywhere. I have gone through the installation instructions but I am having trouble accessing the canonical urls the Filer makes for each file. It seems I am being directed to an extended url that Filer.urls is not recognizing (the non-canonical part starts at /filer-public/; this is a directory that is being created and storing my files on the separate PythonAnywhere file directory). Is there an error in my urls syntax? An error in my views.canonical? I am unsure of why plugging in the exact canonical url redirects me to this extended version of the url. Python: 3.7 Django: 2.2 Canonical URL: /filer/sharing/1560887480/39/ ERROR / DEBUGGING SCREEN Page not found (404) Request Method: GET Request URL: http://www.mywebsite.com/filer/sharing/1560887480/39/filer_public/36/ea/36ea58a8-f59c-41ad-9d1f-00a976603eb1/big1.jpg Using the URLconf defined in mywebsitesite.urls, Django tried these URL patterns, in this order: admin/ ^filer/ sharing/(?P<uploaded_at>[0-9]+)/(?P<file_id>[0-9]+)/$ [name='canonical'] The current path, filer/sharing/1560887480/39/filer_public/36/ea/36ea58a8-f59c-41ad-9d1f-00a976603eb1/big1.jpg, didn't match any of these. APP URLS: /mywebsite/.virtualenvs/env/lib/python3.7/site-packages/filer/urls.py # -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf.urls import url from . import settings as filer_settings from . import views urlpatterns = [ url( filer_settings.FILER_CANONICAL_URL + r'(?P<uploaded_at>[0-9]+)/(?P<file_id>[0-9]+)/$', # flake8: noqa views.canonical, name='canonical' ), ] APP … -
How to Reference Variable From Different View (Django)
I would like to use a variable outside of the function in which it is defined. I have only ever passed data to different templates and have not had to reference that data afterwards so I am unsure as to how I should proceed. Any help would be greatly appreciated, I am still new to Django/Python. Thanks! views.py def new_opportunity_company_id(request): company = request.GET.get('selected_company') company_obj = cwObj.get_company(company) company_id = company_obj[0]['id'] return company_id def new_opportunity_location(request): for company_id in new_opportunity_company_id(request): locations = cwObj.get_sites(company_id) context = {'locations': locations} return render(request, 'website/new_opportunity_location.html', context) -
Annotating a queryset with objects from a different "filter" queryset
If you're filtering a queryset using values from a different queryset, what is the best way to annotate the "filter" value onto the original queryset? For example, below I have a simGrants QS that I'm filtering using the simKeys QS. When a match is found, I'd like to append the matching simKeys cosine score to the simGrants object. The database is fairly large so I'm looking to find the most computationally efficient way to do this. Simkeys =similarity_matrix.objects.filter(y_axis__in=profiles).filter(cosine_score__gt=0) simGrants = Grant.objects.filter(indexKey__in=simKeys) -
Django: Creating an intermediate form with radio buttons that redirects the user
I have a Django project in which the user registers (this is the default user registration in use) and after registration I want them to be able to select an option - W or WP (radio buttons). Depending on the button they select, they would be re-directed to an appropriate profile page. (e.g profile-W or profile-WP) The "more info" intermediate page looks like this (html) more-info page showing two radio button options I would like some guidance on the best way to achieve this. Am I correct in thinking the first two steps would be to 1) Create a form for the more-info page 2) Create a view that would re-direct users to a profile. So far, I have this forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile """ Step 1- Create a More Info form class MoreInfoForm(): choice = forms.ChoiceField(required=True, widget=forms.RadioSelect( attrs={'class': 'Radio'}), choices=(('option1','I am a W'),('option2','I am a WP'),)) """ views.py """ STEP 2 - Create another view def moreinforequest(request): if request.method =='POST': form = UserMoreInfoForm(request.POST) #create a form that has the data that was in request.POST if form.is_valid(): #is the form valid (has something been ticked?) form.save()#this just … -
Django and Nginx (Digital Ocean)
I am finishing my first project in Django and in deployment I'm facing a problem. when I enter the site, I get the Nginx default page. I followed all the steps in the tutorial, read it again, so I don't know what I am missing. Here are the codes: Gunicorn Service Nginx Configuration Path -
It doesn't get the information right
The index.html doesn't show any error but doesn't show the information that it should. When using tags there is no problem but when trying to get the information from the website, it simply doesn't show it. <div class="box"> <article class="media"> <div class="media-left"> <figure class="image is-50x50"> <img src="http://openweathermap.org/img/w/{{ weather.icon }}.png" alt="Image"> </figure> </div> <div class="media-content"> <div class="content"> <p> <span class="title">{{ weather.city }}</span> <br> <span class="subtitle">{{ weather.temperature }}°F </span> <br> {{ weather.description }} </p> </div> </div> </article> There are no errors, just the images not showing up -
deployment django project to cpanel v3
i got cpanel from company but it's not python anywhere or digitalocean and i can't write right settings.py file i need a documentation to upload it and file manager in this cpanel it's not look like another cpanels i can't find python behind file manager , actually someone uplaod his project on it but i can't upload it.. if someone can't understand , please contact me on facebook : https://www.facebook.com/a7med7amed69 -
Django template pass array to input field
I have a hidden input field in my django template where I'm passing as value an array. <form method="post" action="{% url 'flights:flight-selection' %}">{% csrf_token %} <input type="hidden" id="fa_f_ids" name="fa_f_ids" value="{{ value.fa_f_ids }}"> <button type="submit" class="btn btn-light">Select</button> </form> When I submit this form via post request I want to get the value of fa_f_ids as an array but I am getting a string instead when I'd like to get an array. request.POST.get("fa_flight_id") #=> <QueryDict: {'csrfmiddlewaretoken': ['UoYqbTUlNxTEJW5AUEfgsgsLuG63dUsvX88DkwGLUJfbnwJdvcfsFhi75yie5uMX'], 'fa_f_ids': ["['AMX401-1560750900-schedule-0000', 'AMX19-1560782100-schedule-0001']"]}> -
Django Admin: Save formset for TubularInline
I have a tubularInline field in django admin main model is Model1 and the tubularinline model is Model2, say. so admin looks like class Model1Admin(admin.ModelAdmin): model = Model1 inlines = [Model2Inline] def save_formset(self, request, form, formset, change): # whatever I do here, nothing gets saved class Model2Inilne (admin.TabularInilne): model = Model2 I've seen many of the posts about save_formset and nothing works for me. I've tried what Django doc suggests https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset and it doesn't work. Nothing gets saved. I've tried something like In Django, how do I know the currently logged-in user? It doesn't work. Nothing gets saved. I'ev tried Django InlineModelAdmin - set inline field from request on save (set user field automatically) (save_formset vs save_model) which is essentially the same as the doc, nothing gets saved. -
why can't I fetch multiple images django views?(I haven't used django forms)
I am making one website in which I want to upload and fetch multiple images with simple HTML form <div class="row"> <div class="input-field col s12"> <div class="file-field input-field"> <div class="btn #4e342e brown darken-3"> <span>Upload Images</span> <input type="file" name="images" multiple required> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text" placeholder="please Upload all photos at a time"> </div> </div> </div> </div> -
Django Admin: How to list only filtered values based on another field selected in dropdown?
I'm creating a django admin interface where I have two dropdown lists: user and inventories The inventories list can be quite long and I want to filter by the user selected. The entry will be saved in a model class UserInventories(Model): user = ForeignKey('auth.user') inventory = ForeignKey('inventory.inventories') I made up all the variables and names, so don't worry about syntax Is there a way to modify the queryset based on the user selected? -
Unable to add user through django admin page
I have been using django-admin page to add user to my application. Recently when I tried to add a new user I started getting TypeError. The exact error is :- Exception Type: TypeError at /admin/auth/user/add/ Exception Value: 'float' object is not subscriptable Request information Since I have not changed anything in the code, I am not sure why I am getting this error now. That is why I am at a loss as what to try to solve the issue. I am attaching the traceback here:- File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/options.py" in wrapper 552. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in bound_func 63. return …