Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get data from another table which have foreign key relation with user table django?
I have three tables user, Profile and booking. Profile and booking table have foreign key with user table. Profile and Booking table are not directly linked. In BookingList view i want to access the profile data is it possible if yes how i can i do this. models.py class Profile(models.Model): uid = models.UUIDField(unique=True, editable=False, default=uuid.uuid4) name = models.CharField(max_length=100, unique=True) contact_person = models.CharField(max_length=100) mobile = models.CharField(max_length=15) email = models.CharField(max_length=40) created_by = models.ForeignKey(User, on_delete=models.PROTECT) profile_status = models.BooleanField(default=False) def __str__(self): return self.name class Booking(models.Model): port_of_loading = models.ForeignKey(LoadPort, on_delete=models.PROTECT) port_of_discharge = models.ForeignKey(DestinationPort, on_delete=models.PROTECT) equipment_type = models.CharField(max_length=10, choices=CONT_TYP) quantity = models.IntegerField() pick_up_date = models.DateField(null=True, blank=True) hand_over_date = models.DateField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.port_of_loading views.py class BookingList(LoginRequiredMixin, ListView): model = Booking template_name = 'documentation/details_booking.html' context_object_name = 'all_bk' def get_queryset(self): queryset = super(BookingList, self).get_queryset().order_by('-pk') return queryset In template i want to access the profile.name {% for item in all_bk %} <tr> <td>{{ item.created_by.profile.name }}</td> </tr> {% endfor %} -
connect mongodb with djongo (Django)
i try connect to mongodb with djongo after reading githup page of djongo and this find same question here but no answer as well change setting.py like this DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'namename', } } after run python manage.py makemigrate i get this error: djongo' isn't an available database backend try using "django.db.backend.XXX" where XXX is one of : "mysql" , "oracle" , "postgresql" , "sqlite3" -
'NoneType' object has no attribute (foreign key) csv?
When all set foreign key (sku_id) it's working fine if null foreign key it's showing error object has no attribute How to print 'none' instead of error in CSV columns def seller_report(request): loginned_user = request.user if request.method=="POST": from_date = request.POST.get('from_date') to_date = request.POST.get('to_date') new_from = datetime.datetime.strptime(from_date, '%Y-%m-%d').date() new_to = datetime.datetime.strptime(to_date, '%Y-%m-%d').date() min_dt = datetime.datetime.combine(new_from, datetime.time.min) max_dt = datetime.datetime.combine(new_to, datetime.time.max) space = ' ' to = 'to' download_name = space + from_date + space + to + space + to_date daily_en = All_enquiries.objects.filter(enquired_at__range = (min_dt, max_dt)) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Report{}.csv"'.format(download_name) writer = csv.writer(response, delimiter=',') writer.writerow(['created_at','product_name','product_category','price','seller_name','seller_mobile','seller state','seller city','seller pincode', 'seller type','customer_name','customer_mobile','state','district','city','pincode','status','remarks','source','username']) for obj in daily_en: if obj.sku_id is None: obj.sku_id is 'None' writer.writerow([obj.enquired_at,obj.product_name,obj.product_category,obj.price,obj.sku_id.seller_id.seller_name, obj.sku_id.seller_id.mobile_number,obj.sku_id.seller_id.state,obj.sku_id.seller_id.city,obj.sku_id.seller_id.pincode,obj.sku_id.seller_id.get_seller_type_display(), obj.customer_name,obj.customer_mobile,obj.state,obj.district,obj.city,obj.pincode,obj.status,obj.remarks,obj.get_source_display(),obj.user_id]) return response return render (request,'enquiries/admin/report.html') -
How to get changed_fields in Django REST Framework Serializers during update?
Is there any way that I can get the 'changed_fields' before updating the model using ModelSerializer? I want functionality like: class MySerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = MyModel def update(self, validated_data): // Access old values and new values of model so that I can compare them. super(MySerializer, self).update(validated_data) I don't want to query the database to fetch the old_values, because we've over millions of rows and it will take time to fetch that. -
from django.utils import translation not working on shell
I am using Django translation for the first time, Please help me to fix the issue. According to the Django doc for translation Using translations outside views and templates I have tried below code on shell but unfortunately thats not working: >>> from django.utils import translation >>> def welcome_translated(language): cur_language = translation.get_language() try: translation.activate(language) text = translation.gettext('welcome') finally: translation.activate(cur_language) return text >>> translation.get_language() 'en' >>> welcome_translated('fa-ir') 'welcome' -
Async Api calls
I want to call different api's as a service from one server. In heroku it is giving 503 if request exceedes more than 30 seconds. How can i achieve it as making request from one end to several servers. I am using celery beat on request side for scheduling tasks -
elatic apm, django integration, user id
https://www.elastic.co/guide/en/apm/agent/python/current/django-support.html Is there a way to include user-id for apm messages? We'd like to know if how many unique users are experiencing the error. -
django_pandas.io read_frame() giving too many SQL variable error
I stumbled upon this weird problem, the "TOO MANY SQL VARIABLES" in sqlite3 django error is coming not while fetching the objects via the line objects = Model_Name.objects.filter(CN = some_name) but the error is coming when I convert this to df using django_pandas.io.read_frame() df = read_frame(objects) The queryset here has around 80 variables and nearly ~7000 rows. So I decided to convert the queryset to data frame in a loop with the code df = [] for items in range(0, len(objects), 100): df.append(read_frame(objects[items:items+100])) df.append(read_frame(objects[-1*len(objects)%100:])) but this is giving me another error at df.append(read_frame(objects[items:items+100])) saying AttributeError: 'list' object has no attribute '_iterable_class' Note:- The code for only one-time indexing like read_frame(objects[100:168]) runs fine but the same line gives that Attribute error when running in a loop. Please help. -
auto_now_add and auto_now as epoch
I wanted to save the Create_at (auto_now_add = True) and Updated_at (auto_now = true) fields as epoch Model class EpochTest(models.Model): name = models.CharField(max_length=32) # Auto-update Filed created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) How do I do that? -
mysqlclient 1.3.13 or newer is required; you have 0.9.3
It's a bit weird. My project is working all the time and Just today morning got this issue. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "Users..\\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\options.py", line … -
django throws "AppRegistryNotReady: Apps aren't loaded yet." when a view is imported
I get this error when I try to import a view into the apps.py module of a django app. I am using django 2.2.9, python 3.7.6, django-oscar 2.0.4. I have overridden the checkout app but this error prevents me from adding views or changing urls for all of django oscar's apps. What is causing this error ? (vsosci) c:\Users\anon\Documents\sosci.git>python manage.py check Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\anon\Envs\vsosci\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\anon\Envs\vsosci\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\anon\Envs\vsosci\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\anon\Envs\vsosci\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\anon\Envs\vsosci\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\anon\Envs\vsosci\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "c:\Users\anon\Documents\sosci.git\checkout\apps.py", line 3, in <module> from checkout.views … -
502 Bad Gateway nginx/1.14.0 (Ubuntu) digitalocean vps django, nginx and gunicorn
I put up a site in production a week ago made using django and postgres on digitalocean and followed the django nginx, gunicorn and postgres tutorial here and used digitalspace for our static file. everything was running smoothly and okay for the whole week while we were testing the website in production (left Debug=true for testing reasons). suddenly a few hours ago after i was testing some stuff i got a 502 bad gateway error. i checked the nginx error logs and heres the error: 2019/12/23 00:30:00 [error] 7988#7988: *2202 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 125.0.0.1, server: www.myapp.com, request: "GET /reviews/business/id=3/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/reviews/business/id=3/", host: "myapp.com", referrer: "https://myapp.com/category/Salon/" 2019/12/23 00:30:12 [error] 7988#7988: *2208 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 125.0.0.1, server: www.myapp.com, request: "GET /reviews/business/id=3/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/reviews/business/id=3/", host: "myapp.com", referrer: "https://plentypot.biz/category/Salon/" 2019/12/23 00:30:25 [error] 7988#7988: *2212 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 125.0.0.1, server: www.myapp.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "myapp.com" i ran nginx -t and it returned successful meaning everything is okay with the configurations the gunicorn error logs by using the command journalctl -u … -
how to loop for 2 data in same table in html with cycle tag
so i want to print list of manage user in my database , and i show it in the table that i make in html , but the problem is , when i open the web and see the list of manage user, the email and the username is in the same column def manage_user(request): import cx_Oracle dsn_tns = cx_Oracle.makedsn(, , ) conn = cx_Oracle.connect(user=, password=, dsn=dsn_tns) c = conn.cursor() c.execute("select * from auth_user") c.rowfactory = makeDictFactory(c) databaseusertable = [] databaseemailtable =[] for rowDict in c: databaseusertable.append(rowDict['USERNAME']) databaseemailtable.append(rowDict['EMAIL']) context = { 'obj' : databaseusertable, 'obj2': databaseemailtable, } return render(request,'manage_user.html',context) html {% for item1 in obj %} <tr> <td> {{item1}} </td> {% cycle '' '' '</td></tr><tr>' %} </tr> {% endfor %} {% for item2 in obj2 %} <tr> <td> {{item2}} </td> {% cycle '' '' '</td></tr><tr>' %} </tr> {% endfor %} how to make the email is in the different column? i use cycle tags, thats why im a little bit confuse about it -
Reverse Query Through Django Template File
models.py file class Company(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Contact(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.first_name views.py file class company_detail(DetailView): def get(self, request, *args, **kwargs): company = get_object_or_404(Company, pk=kwargs['pk']) context = {'company': company} return render(request, 'crm/company_detail.html', context) company_detail.html file {% extends 'base.html' %} {% block content %} <div id="container"> <ul> <li>{{company.name}}</li> </ul> {% for company in object_list %} {{ company.name }} {% for Contact in company.contact_set.all %} {{Contact.first_name}} {% empty %} <!-- no entries --> {% endfor %} {% endfor %} </div> {% endblock content %} I'm trying to get the Contacts who are under that company to show up on the company_detail.html page. How do I reverse query it properly to show all Contacts under that company? Thanks in advance -
Test django view which has post request
I am trying to test my django views which contain post request. def save_movie(request): ''' Fetch data and save to Movie model data obtained from post request is a string so need to clean it and convert to json ''' if request.method == 'POST': movie_data = str(request.POST['movie_data']) movie_data = movie_data.replace("\'","\"") b="" for i in range(len(movie_data)): if movie_data[i] is "\"" and movie_data[i-1].isalpha() and movie_data[i+1].isalpha(): b+="\'" else: b+=movie_data[i] json_data = json.loads(b) new_movie, created = Movie.objects.get_or_create(title=json_data['title'],...)//too many fields so ... if created: new_movie.save() return HttpResponse('<h1>Movie Saved</h1>') else: return HttpResponse('<h1>Movie already Saved</h1>') and test.py is def test_save_movie(self): response = self.client.post(self.save_movie_url, {'title':'test', ...}) print(response.status_code) when i run this testcase i get MultiValueDictError File "/home/abhishek/Desktop/SpotDraft/StarWars/favourites/tests/test_views.py", line 58, in test_save_movie response = self.client.post(self.save_movie_url, {'title':'test', 'episode_id':1, 'opening_crawl':'test for movie', 'director':'director', 'producer':'producer', 'release_date':'test_date', 'characters':'test_chars', 'planets':'test_planets', 'starships':'test_starships', 'vehicles':'str_vehicles', 'species':'str_species', 'created':'2014-12-09T13:50:49.641000Z', 'edited':'2015-12-09T13:50:49.641000Z', 'url':'https://test.com'}) File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 526, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 356, in post secure=secure, **extra) File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 421, in generic return self.request(**r) File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 496, in request raise exc_value File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
Django Error: Debug UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 481: invalid continuation byte
I'm trying to debug for first time in Django with: import pdb pdb.set_trace() But every single time i run i got the same error: D:\Users\nahim\Miniconda3\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 481: invalid continuation byte Can somebody help me? Windows 10 - P 3.7 - Django 3.0 - Command Shell - VirtualEnv -
Multiple Get Requests for One Action
I currently have a CRUD reminder app and has a context menu with options such as edit, delete, etc. Buttons on the context menu are updated based on the reminders id, and ids are passed to a bootstrap modal form. function toggleMenuOn(e) { if ( menuState !== 1 ) { menuState = 1; menu.classList.add( contextMenuActive ); } let reminder_id = e.target.id let context_btn1 = document.getElementById("context_menu_btn1"); let reminder_pk = reminder_id.replace("reminder", ""); let reminder_url = "{% url 'update-reminder' 0 %}".replace(/0/, reminder_pk) context_btn1.className = "update-reminder context-menu__link btn btn-light"; context_btn1.setAttribute('data-id', reminder_url); $("#context_menu_btn1").modalForm({formURL: reminder_url}); } However, when I looked in the command line, I saw many GET requests for one button click: [22/Dec/2019 17:50:01] "GET /update_reminder/8/ HTTP/1.1" 200 4650 [22/Dec/2019 17:50:01] "GET /update_reminder/4/ HTTP/1.1" 200 4681 [22/Dec/2019 17:50:01] "GET /update_reminder/8/ HTTP/1.1" 200 4650 [22/Dec/2019 17:50:01] "GET /update_reminder/4/ HTTP/1.1" 200 4681 The interesting thing is, when the page is first loaded and I click edit on a reminder, one GET request appears. But when I click it another time, 2 GET requests appear, with alternating links, as shown above. On the third edit click 3 GET requests show up. I had a look in the network tab in inspect element and shows the same. This is … -
How to access values in object on a related foreign key inDjango templates?
In my model LineItems are related to JournalEntries by foreign key (JournalEntry has many LineItems). In my template I've written the following code which loops through all my JournalEntries showing the LineItems that belong to each one: <ul> {% for journal_entry in journal_entries %} <li>{{ journal_entry.id }} - {{ journal_entry.description}}</li> <ul> {% for line_item in journal_entry.lineitem_set.all %} <li>{{line_item.id}} - {{line_item.description }}</li> {% endfor %} </ul> {% endfor %} </ul> But what I actually need is to is display each Journal Entry and the descriptions from its first and second LineItem all on one line. The code below doesn't work but it might show you what I'm trying to achieve: {% for journal_entry in journal_entries %} <li>{{ journal_entry.id }} - {{ journal_entry.line_item.1.description }} - - {{ journal_entry.line_item.2.description }}</li> -
Django template view to prevent a user defined relative url
In a Django template, I render a URL stored in a database. This URL is defined by the user. What I do not like is that the user defines a relative URL such as /admin and redirect to somewhere irrelevant within the current server domain. Is there any way to prevent bookmark.url being rendered as relative URL? I want it to be rendered as an absolute path only. <div> <a href="{{ bookmark.url }}">{{ bookmark.name }}</a> </div> Note 1: {% get_static_prefix %} looks irrelevant to my question. Please avoid linking to those questions. (Just in case) Note 2: I am after any solution in the template view side or an HTML solution. I know modification of the model object before sending it as a context is always possible. But, I am not after such solutions. Also, I do not like to put an if-else inside the view too because it is too much for such a minor improvement. -
Customize the static files tag
https://github.com/mdbootstrap/Ecommerce-Template-Bootstrap I was trying to customize this e commerce website. But when I was adding the static tags, it doesn't load full images,styling properly. Is there any easier way to add static tags to make the website function fully. Thanks -
Django fetch related child with parent object
I am using Django 2.2 and I have a model with two classes Product and ProductRevision. When I retrieve a Product, or a list of Products, I always fetch the corresponding ProductRevision. ProductRevision objects are incremented and only the last revision should be fetched with the Product. class Product(models.Model): name = models.CharField(max_length=50, null=False, blank=False, verbose_name=_("name")) product_code = models.CharField(max_length=10, null=False, blank=False, verbose_name=_("product code")) slug = models.SlugField(null=False, unique=True) @property def current_item(self): return ProductRevision.objects.filter(product=self, active=True).order_by('-version').first() class ProductRevision(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.PROTECT) version = models.IntegerField(default=0, verbose_name=_("version")) active = models.BooleanField(default=False, null=False, blank=True, verbose_name=_("is active")) qty_close = models.IntegerField(default=0, verbose_name=_("qty of accounts to be closed")) price_eur = models.DecimalField(max_digits=6, decimal_places=2, default=0, verbose_name=_("price in EUR")) I tried to add a property current_item to get the last revision of a given product. While this is working, it is very inefficient because when I use it in a template, it hits the database every time I display a field from the related ProductRevision. I found this answer based on an old version of Django (Fetch latest related objects in django) and I'm wondering if there is no other ways to achieve the same result with current versions of Django? I'm particularly interrested in achieving this in my models. -
Django Banners in Admin
Hi I am looking for advice on setting up side banners on my Django app that can be edited through the admin panel, in a similar way to Wordpress where I can just insert the link into the primary sidebar. I have searched the net extensively and still can't find anything to point me in the right direction. I checked Django-ads but the documentation is a little hard to follow, so I am wondering if anyone has any suggestions for a simpler solution. I would like the following functionality - Create custom banner from admin panel - Ability to resize - Preferably ability to add multiple different types/sizes I understand that this question is a little vague / no example, but if anyone has done something similar I would greatly appreciate a nudge in the right direction. Thanks in advance -
unexpected keyword argument 'instance' in Django ModelForm with formsets
So I have a Folder model, and 2 other models that are related to it via a ForeignKey. I have this method for creating 3 separate objects using 3 forms (creating the Folder object, and uploading files to 2 separate models that are related to Folder): @login_required def nouveaudossier(request): DocumentFormSet = modelformset_factory(DocumentdeBase, form=DocumentdebaseForm, extra=5) PhotoAvantFormSet = modelformset_factory(PhotoAvant, form=PhotoAvantForm, extra=5) if request.method == 'POST': dossierForm = DossierForm(request.POST) formset = DocumentFormSet(request.POST, request.FILES, queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(request.POST, request.FILES, queryset=PhotoAvant.objects.none()) if dossierForm.is_valid() and formset.is_valid() and formset2.is_valid(): dossier_form = dossierForm.save(commit=False) dossier_form.created_by = Prestataire.objects.filter(user=request.user).first() dossier_form.save() for form in formset.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form: image = form['documentdebase_image'] photo = DocumentdeBase(dossier=dossier_form, documentdebase_image=image) photo.save() for form2 in formset2.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form2: image2 = form2['photoavant_image'] photo2 = PhotoAvant(dossier=dossier_form, photoavant_image=image2) photo2.save() messages.success(request, "Dossier créé!") return HttpResponseRedirect("/") else: print(dossierForm.errors, formset.errors, formset2.errors) else: dossierForm = DossierForm() formset = DocumentFormSet(queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(queryset=PhotoAvant.objects.none()) return render(request, 'dashboard/nouveau_dossier.html', {'dossierForm': dossierForm, 'formset': formset, 'formset2': formset2}) The view is working great, here is the screenshot of it: Now I want to make an Edit form, to take the id of the model in … -
Django Create User from Azure Graph AD
My question is regarding the practice of creating/saving users to the Django app when users are logging through an external API like Azure AD. I am following the Azure AD Django project example. In a vanilla Django project, in order to create a new user you would add this new person to the User model that Django creates for you. See documentation: Creating Users >>> from django.contrib.auth.models import User >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') # At this point, user is a User object that has already been saved # to the database. You can continue to change its attributes # if you want to change other fields. >>> user.last_name = 'Lennon' >>> user.save() However, if your app is using something similar to Azure AD Graph, then the user is logging using their Microsoft credentials (e.g. email/password) and a user is obtained from the request object. Here is an example of what you may obtain <class 'requests.models.Response'> <Response [200]> with data {'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity', 'displayName': 'Jon Doe', 'surname': 'Doe', 'givenName': 'Jon', 'id': '8431c9c085f05a72', 'userPrincipalName': 'jondoe@hotmail.com', 'businessPhones': [], 'jobTitle': None, 'mail': None, 'mobilePhone': None, 'officeLocation': None, 'preferredLanguage': None} With this given data is it good practice to then create a new user … -
Custom domain for django tenants
Can my tenant use their custom domain xyz.com instead of the public schema own subdomain like tenant.mydomain.com. Assume I have a django tenant powered site with domain as mydomain.com & all tenants created have t1.mydomain.com, t2.mydomain.com, etc. Can tenant t1 use t1domain.com instead of or alongside to t1.mydomain.com? Same goes for t2, etc.