Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Windows IIS Single Sign On
I'm currently working on a Django App that has all reporting dashboards for 11 different divisions. One of the web development requirements of our company is a single sign-on. My app is currently hosted via Windows IIS and I have a database resource where I can grab all active users for our company. However, I have searched the net for tutorials on how to do this in my Django app but with no success. If you could provide me a url or at least an advice on how to do this, I would definitely appreciate it. -
Querying django-polymorphic models with foreign key
Sorry if I don't explain this very well. I have several models (simplified example): class Building(models.ModelAdmin): materials = models.ManyToManyField('Material') class Material(PolymorphicModel): name = models.CharField(max_length=100) class MaterialType(Material): pass class MaterialSubtype(Material): material_type = models.ForeignKey('MaterialType', on_delete=models.CASCADE) The idea is that a building can have multiple materials, either of a 'generic' type such as 'stone' (in which case, it's a MaterialType), or a more specific MaterialSubtype (e.g. 'granite'). This seems to work with the Admin and in views. I currently have three objects in my database: one MaterialType (name=stone), one MaterialSubtype (name=granite, material_type=[the 'stone' MaterialType]) and a Building (material=[the granite MaterialSubtype]). I would like a query to find buildings with matching Materials. So if you search for 'Granite', it should match. If you search for 'Stone', it should also match (by following the MaterialSubtype.material_type foreign key). Is this possible, or is the whole thing crazy? UPDATE: I have it working so that I can match whichever model is directly connected to Building.materials (either the MaterialType or MaterialSubtype), but doing something like Building.objects.filter(materials__material_subtype_name='stone') doesn't work (presumably as potentially not all materials have a material_subtype field to query. -
django adding values to foerignkey field
I have a simple application which requires each employee can have multiple files, so i created two models one is Employee and the other one is Files class Files(models.Model): files = models.FileField(upload_to='files') class Employee(models.Model): name = models.CharField(max_length=200) email = models.EmailField() cv = models.ForeignKey( Files, on_delete=models.CASCADE) when i try to upload a file it gives me an error. Cannot assign "'list-employees.png'": "Employee.cv" must be a "Files" instance. Exception Type: ValueError -
How to code django view to open first loading screen and after few second redirect to another template
How to set django view to open fisrt loading template, set delay to few seconds and next open another template. thanks -
How to fix ‘data-url not working with bootstrap’ error in django?
I was trying to make dependent dropdownlist with the framework django, As a start i did a test whish contains two lists without bootstrap and it does work properly but when i added bootstrap the first list worked but the other didn't show anything. I think the problem when i added bootstrap the data-url from the form whish contains the two lists couldn't pass the url to jquery. Backgrounds for the two cases: background 1 background2mgur.com/clPDz.png code: <!-- without bootstrap loading --> {% load widget_tweaks %} {% block content %} <div class="content-inner"> <!-- Page Header--> <header class="page-header"> <div class="container-fluid"> <h2 class="no-margin-bottom">test dropdown</h2> </div> </header> <!--Les Sections--> <section class="forms"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-close"> <div class="dropdown"> <button type="button" id="closeCard2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="dropdown-toggle"><i class="fa fa-ellipsis-v"></i></button> <div aria-labelledby="closeCard2" class="dropdown-menu dropdown-menu-right has-shadow"><a href="#" class="dropdown-item remove"> <i class="fa fa-times"></i>Close</a> </div> </div> </div> <div class="card-body"> <form class="form-horizontal" id="myForm" method="GET" data-urlcomptes="{% url 'comptes_choices_ajax' %}" > <div class="form-group row"> <label class="col-xl-2 col-sm-3 form-control-label" for="fourniSelect">Fournisseur</label> <div class="col-xl-4 col-sm-9"> {% render_field form.Fournisseur title="Fournisseurs" class="form-control" %} </div> </div> </div> <div class="form-group row"> <label class="col-xl-2 col-sm-3 form-control-label" for="compteSelect">Banque</label> <div class="col-xl-4 col-sm-9"> <select name="" id="compteSelect" class="form-control mb-3"> <option>--------</option> </select> </div> <div class="col-xl-4 col-sm-9 offset-xl-8"> <input type="submit" value="Envoyer" … -
how to fetch reddit api while using django?
I want to fetch the Reddit api and display the same on my website. How can we achieve this with Django? Even a near solution will help -
I want to change the password reset email template, but I cannot find a way to make it work
So I have managed to edit basic text on the sent email, but I also wanted to include a picture and a title. I soon realized that simple html tags didn't work. How can I fix this? <!DOCTYPE html> <html> <head> {% load i18n %}{% autoescape off %} <title>Password Reset @PLANT MONiTOR</title> </head> <body> {% blocktrans %}You're receiving this email because you requested a password reset for your user account @PLANT MONiTOR.{% endblocktrans %} {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% trans "Your username, in case you've forgotten:" %} {{ user.get_username }} {% trans "Thanks for using our monitoring system!" %} {% blocktrans %}The PLANT MONiTOR Team{% endblocktrans %} {% endautoescape %} </body> </html> This is the email I get: <!DOCTYPE html> <html> <head> <title>Password Reset @PLANT MONiTOR</title> </head> <body> You're receiving this email because you requested a password reset for your user account @PLANT MONiTOR. Please go to the following page and choose a new password: http://localhost:8000/password-reset-confirm/MTE/574-90ff952d8b6ffe6ef5c1/ Your username, in case you've forgotten: admin Thanks for using our monitoring system! The PLANT MONiTOR Team … -
Use Django URL pattern matcher as component
I guess it's possible, but i still didn't find any solution. I'm looking for a way to use Django URL pattern matcher for another data processing For example: I have following pattern "MySpecific-(?P<my_parameter>)-(?P<my_second_parameter>)" and following regular string "MySpecific-test-123" so what i want is to extract parameters by pattern form regular string in a dict shape { "my_parameter": "test", "my_second_parameter: "123" } Pseudo code: import matcher from django_matcher_package my_pattern = "MySpecific-(?P<my_parameter>)-(?P<my_second_parameter>)" my_string = "MySpecific-test-123" extracted_values = matcher.match(my_pattern, my_string) -
hqo can i make a correct regex in dajngo?
I need to make regex to make a button witch put me on other website this is my re_path: re_path (r'^detaletournament(?P<turnament_id>[0-9]+)/$',detaletournament) Using the URLconf defined in projekt.urls, Django tried these URL patterns, in this order: admin/ tir login register usertournaments turnament addturnament takepart deletetournament quittournament mytournaments webturnament profile ^detaletournament(?P<turnament_id>[0-9]+)/$ The current path, detaletournament, didn't match any of these. -
how to set password show/hide eye button in Django form
First, I will try to solve this problem using native HTML and jquery, but I want to solve this problem in Django form without any script. I will try this source code = https://itsolutionstuff.com/post/bootstrap-show-hidetoggle-password-input-field-using-bootstrap-show-passwordjs-pluginexample.html My expected output is put this same example in the above link to Django form. -
Error when trying to run a file .py to add data in database
I create 2 files .py in an app of my project. my app si importXLS. when I want to run my app, it does not work . first file goes and parse an excel file. It seems working well second file should add each element of the first one and save it in database This one is not working. this is first file which parse excel file: from openpyxl import load_workbook def is_empty(row): return all(cell.value is None for cell in row) def is_empty_gl(row): return row[0].value is None def has_empty_cells(row): return any(cell.value is None for cell in row) # ----------------Chart of accounts-------------- def parse_coa(): wb = load_workbook(filename='Chartofaccount.xlsx') ws = wb.active coa = [] for row in ws.iter_rows(min_row=2, min_col=2, max_col=5): if is_empty(row): continue elif is_empty_gl(row): print('missing cell value found {}. Please fix and run again'.format(row[1].value)) # exit() else: chartdictionnary = { 'field_account': row[0].value, 'field_account_libaccount': row[1].value, 'field_type': row[2].value, 'field_subtype': row[3].value, } coa.append(chartdictionnary) return coa This is second file which is not working Error is : db.connect() NameError: name 'db' is not defined. But I don t know how to connect to data base (which is a sqlite for dev but should be another one in prod) from read_data import parse_coa db.connect() for coa … -
How can I make Django and React Work together without using Django Rest Framework
I working on a web app which has its back-end made in Django and the front-end is developed in Reactjs. How should I integrate the Django back-end and React front-end without using Django Rest Framework. Also I want to know how to use an HttpResponse generated from Django views function in a react frontend. P.S.: I have not worked with Django rest framework. -
How to link one html page to another using django
I am using django and basic templates in my application. I wanted to refer in my html page to another html page in src tag. How can i achieve this? I am getting page not found error only as it is going to find from my installed_apps directory. Lets example , i have a below structure:- smart_chat - client migrations init_py urls.py views.py models.py forms.py app migrations init_py urls.py views.py models.py forms.py smart_chat settings.py migrations urls.py wsgi.py static css js images templates base.html template.html I wanted to give link in base.html file( src = "template.html").// how can i give this depend on my structure and settings mentioned in settings.py file. In my settings.py file, i have mentioned this:- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] But i still page not found error. How can i achieve this? Thanks in advance! -
Django: Populate a table based on incerted value from other table
I need to set a start date and end date on a table (Week) and based on these values, another table (Day) is automatically populated with the days between those dates. My models are: class Week(models.Model): class Meta: constraints = [models.UniqueConstraint(fields=['sub_unit', 'initial_date', 'last_date'], name='unique_item')] ordering = ['-initial_date'] verbose_name = 'Week' verbose_name_plural = 'Weeks' sub_unit = models.CharField(max_length=255, null=True, blank=True, verbose_name='SubUnit') initial_date = models.DateField(blank=False, null=True, verbose_name='Initial Date') last_date = models.DateField(blank=False, null=True, verbose_name='Last Date') def __str__(self): return '{} - Week from {} to {}'.format(self.sub_unit, self.initial_date, self.last_date) class Day(models.Model): class Meta: constraints = [models.UniqueConstraint(fields=['week', 'day'], name='unique_item')] ordering = ['-day'] verbose_name = 'Day' verbose_name_plural = 'Days' week = models.ForeignKey(Week, related_name='week', on_delete=models.CASCADE) day = models.DateField(blank=False, null=True, verbose_name='day') def __str__(self): return '{}'.format(self.day) Can some one put me in right direction. Thanks! -
How to use template variable for redis key prefix
I need to store template cache using a parameter as prefix. Es. With: {% cache 5 :name:variable1: variable_y variable_z %} I need to store: :1:template.cache:name:<<variable1 value>>:.0ecadd093a225ba502d3f6490e19b4 Actually I obtain: :1:template.cache:name:variable1:.0ecadd093a225ba502d3f6490e19b4 where variable1 is the variable name. There's a way? Thanks -
How to add classes to form fields dynamically created by Django?
I have figured out how to add classes to form fields. I have the following: # models.py class Contact(AddressMixin, PhoneMixin): contact_id = models.AutoField(primary_key=True) name = models.CharField(_('name'), max_length=50, blank=False) company = models.CharField(_('company'), max_length=50, blank=True) photo = models.CharField(_('photo'), max_length=255, blank=True) notes = models.TextField(_('notes'), blank=True) created_on = models.DateField(auto_now_add=True) # forms.py class ContactForm(ModelForm): class Meta: model = Contact fields = ['name', 'company', 'photo', 'notes'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'company': forms.TextInput(attrs={'class': 'form-control'}), 'photo': forms.TextInput(attrs={'class': 'form-control'}), 'notes': forms.Textarea(attrs={'class': 'form-control'}), } The magic is in the class Meta, specifically the widgets field. That is where you can define what class to go on what field. However, for each contact I want to ability to add 1 or more phone numbers so I have the following: # models.py class Phone(models.Model): entity = models.ForeignKey('PhoneMixin', on_delete=models.CASCADE) number = models.CharField(_('number'), max_length=50, blank=True) class PhoneMixin(models.Model): phone_id = models.AutoField(primary_key=True) pass # forms.py class PhoneForm(ModelForm): class Meta: model = Phone exclude = ['entity'] widgets = { 'number': forms.TextInput(attrs={'class': 'form-control'}), } Then I have a formset which I believe is the root of the problem: PhoneFormSet = inlineformset_factory( Contact, Phone, form=PhoneForm, exclude=('entity',), extra=1 ) I may be mistaken but I believe it is the formset that is adding a delete field. This delete … -
Django: searching in related models
Hello I want to create simple search form which will allow to get data from related models. I have 3 models: class Person(models.Model): name = models.CharField() surname = models.CharField() class Phone(models.Model): person = models.ForeignKey(Person,on_delete=models.CASCADE) phone = models.CharField(0 class Email(models.Model): person = models.ForeignKey(Person,on_delete=models.CASCADE) email = models.EmailField() in my home view I have: def home(request): people= Person.objects.all() query - request.GET.get("q") if query: people = Person.objects.filter(name__icontains=query)|Person.objects.filter(surname__icontains=query) return render(request,'app/home.html',{'users': people}) And it works fine, but I would like to search throug emails and phones too (person can have fews email and phone). If in my query I use another OR (|), I got error I cant combine 2 models in one query. I also wanto to try with chain: people= above query emails = Email.objects.filter(email__icontains=query) context = chain(people,emails) Unfortunately, this solution doesnt work too. How can I solve this? -
How to save data from form field in Model with One to One reltionship with a Model inheriting from AbstractUser
I have a field called org model called ScrummyUser with a one to one field with a model called User which inherits from AbstractUser model, how do I save data from the form field into the scrummyuser model This is the Organization Model class Organization(models.Model): organization = models.CharField(max_length=255, null=True) def __str__(self): return self.organization This is the ScrummyUser model class ScrummyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='scrummy_profile') role= models.CharField(max_length=100, choices=role, blank=True, null=True, default='DEV') org = models.ForeignKey(Organization, max_length=255, on_delete=models.CASCADE, default=1) This is the ScrummySignup form class ScrummySignUpForm(UserCreationForm): role = forms.ChoiceField(choices=role, required=False) org = forms.ModelChoiceField( queryset=Organization.objects.all(), widget=forms.Select ) class Meta(UserCreationForm.Meta): model = User fields = ['first_name', 'last_name','username' ,'email'] @transaction.atomic def save(self): user = super().save(commit=False) user.is_user = True user.save() scrummy = ScrummyUser.objects.create(user=user, role=role) return user It throws me this errormessage scrummy = ScrummyUser.objects.create(user=user, role=role, org=org) NameError: name 'org' is not defined which is obvious but I am looking for another approach to save the data -
Django test with APIRequestFactory : how to pass "flat" parameter to a view
Django 2.2 I am writing tests for API using APIRequestFactory. The code that hits /some_endpoint and /some_endpoint/<item_id> already works, and so does the test that tests /some_endpoint. However the test to test /some_endpoint/<item_id> does not work because I can not find a working way to pass that <item_id> value to the view code. Please not it's not /some_endpoint/<some_keyword>=<item_id> , it's "flat" in my case i.e. there's no keyword. The problem is <item_id> does not make it into the view code (it's always None in the classview in get_queryset method) I tried to pass it as **kwargs, it does not arrive either. But that probably would not work anyway without keyword. I tried to switch to use of Client instead of APIRequestFactory, same result. But I would rather get it working with APIRequestFactory unless it does not work this way in general. Below is the code. test.py def test_getByLongId(self) : factory = APIRequestFactory() item = Item.active.get(id=1) print(item.longid) #it prints correct longid here request = factory.get("/product/%s" % item.longid) view = ItemList.as_view() force_authenticate(request, user=self.user) response = view(request) urls.py urlpatterns = [ ... ... url(item/(?P<item_id>[a-zA-Z0-9-]+)/$', views.ItemList.as_view(), name='item-detail'), ... ... ] views.py class ItemList(generics.ListAPIView): permission_classes = (IsBotOrReadOnly,) """ API endpoint that allows users to be … -
automated tax calculations using stripe in django python
I am new to django python and I want to calculate tax on checkout page when customer add shipping address automatically using strip on billing address in python django -
default language value overrides translation field in admin
I am using Django model translation for the multi-linguistic site(English(default), Arabic, French), the problem is when saving data in django admin default overrides both Arabic and French translation fields. But in database actual value presents. My Model: plan/models.py class operators(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) operator = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(verbose_name=_('Operator Logo'), max_length=255,null=True,blank=True) class Meta: verbose_name = 'Operator' verbose_name_plural = 'Operators' db_table = 'operator' def __str__(self): return self.operator plan/translation.py: @register(operators) class OperatorsTranslationOptions(TranslationOptions): fields = ('operator',) plan/admin.py: class OperatorAdmin(admin.ModelAdmin): list_display = ('operator', 'country') . . . admin.site.register(operators, OperatorAdmin) settings.py: INSTALLED_APPS = [ 'modeltranslation', . . . 'plan', ] . . . LANGUAGES = ( ('en', gettext('English')), ('ar', gettext('Arabic')), ('fr', gettext('French')), ) . . MODELTRANSLATION_TRANSLATION_FILES = ( 'plan.translation', ) MODELTRANSLATION_DEBUG = True Below is the database value planbaker=# select * from operator; id | operator | image | country_id | operator_ar | operator_en | operator_fr ----+------------+-----------------------+------------+--------------+-------------+------------- 1 | airtel-ind | pb_Zu2y9BE.jpeg | 1 | | | 3 | aircel | 360_360_1_vsXSDEo.JPG | 2 | ايرتل | aircel | 2 | aircel-sa | 352_hQ4TZVq.jpeg | 2 | زين السعودية | aircel-sa | aircel-sa But in Admin all the field have operator value only in english . Can somebody please tell me where … -
Django unable to find css file in STATICFILES_DIR
My base.html cannot find base.css. I configured my settings.py file to point to where the css file resides but still get 404. I have the following at bottom of settings.py STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] File system tree: . ├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── blog_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── Pipfile ├── Pipfile.lock ├── static │ └── css │ └── base.css └── templates ├── base.html └── home.html Thank you. -
How to manage users that put wrong email in registration but saved in the database
I write some code to register a user. In my fonction "register(request)", Before i do email verification i save the user and he is saved in the database but he is not active. Then i use this user to activate him in my function "activate(request)" and i activate the user. But there is a problem, if the user put a wrong or not email, he will be saved in database, and this can take useless memory space in database. And the other problem is that if the user want to correct his informations on registration page, he will not be able to do that because his username and email already exists in database. def register(request): registered = False if request.method == 'POST': form = UserForm(data=request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activez votre compte acquisitor.' message = render_to_string('users/acc_active_email.html',{ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return render(request, 'users/mail_registration.html') else: print(form.errors) else: form = UserForm() return render(request, 'users/registration.html', {'user_form': form, 'registered': registered}) def activate(request, uidb64, token, backend='django.contrib.auth.backends.ModelBackend'): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = … -
The 'img' attribute has no file associated with it
I'm trying to use CBV for my Django project. I made a simple form where the admin is able to add new data using the CreateView. The data is successfully and the user is redirected to the page. But as soon as I load my home page an error is generated, which I'm not able to find the solution to. ** Trace back error** Environment: Request Method: GET Request URL: http://127.0.0.1:8000/home/ Django Version: 1.11.21 Python Version: 2.7.16 Installed Applications: ['projectfiles', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Bitswits 3\Desktop\Maala\MaalaWeddings\projectfiles\templates\projectfiles\HomePage.html, error at line 16 The 'food_pic' attribute has no file associated with it. 6 : 7 : {% block asd %} 8 : 9 : <div class='box' align='right'> 10 : Food<hr> 11 : {% if food_count %} 12 : {% for i in food_data %} 13 : {{ i.item_name }} 14 : Rs.{{ i.item_price }} 15 : if 16 : <img src="{{ i.food_pic }}" alt=' {{ i.food_pic.url }} ' width="124" height="124"/> 17 : <img> 18 : {% endfor %} 19 : {% else %} 20 : <h6>NO DATA</h6> 21 : {% endif %} 22 : </div> 23 : 24 … -
How can I use Djano's bulk_create objects except dulplicate one?
Here's the question. I have a model table Campaign like: class Campaign(models.Model): campaign_id = models.CharField(max_length=64, blank=True, null=True) name = models.TextField(blank=True, null=True) ... And campaign_id is unique key of the table. Then after each http-request, I got manycampaign origin data and I want to save it into my mysql db. So I want to use bulk_create to do db work like : with s.post("https:/xxxxxxx/", params=params) as response: return_data = json.loads(response.text) for item in return_data: base_data = json.loads(item["body"]) campaign_list = json.loads(item["body"])["data"] campaign_bulk = [] for item in campaign_list: try: campaign_obj = Campaign( campaign_id = item.get('id', None), name = item.get('name', None) #... ) campaign_bulk.append(campaign_obj) except: continue Campaign.objects.bulk_create(campaign_bulk) But the return campaigns data sometimes are dulplicated, so I might get error like Duplicate entry 'xxxxx' for key 'campaign_id ' Say campaign_bulk above is campaign_bulk = [ Campaign(campaign_id=1,name='name_1'), Campaign(campaign_id=2,name='name_2'), Campaign(campaign_id=3,name='name_3'), ... ] As campaign whose id is 1 already exist, when I run bulk_create to do db work, how can I save other objects not duplicated in db?