Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model form foreign key field to duration field not working
I have the following form where the user selects a value which corresponds to a duration field of the name value in a model called Duration. When the form is submitted I'm getting this error return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds Attribute Error - 'str' object has no attribute days. Clearly Django expects the argument to be a timedelta object when this method is called and it is getting a string instead. Where am I at fault ? The form : class AuctionCreateForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'reserve'] exclude = ('duration',) labels = {'reserve': _('Reserve')} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["duration_value"] = forms.ModelChoiceField( queryset=Duration.objects.all(), empty_label=None, to_field_name="value", ) The view : class AuctionCreate(CreateView): """ View function for creating an auction """ form_class = AuctionCreateForm template_name = "auction/auction_form.html" def form_valid(self, form): form.instance.start = timezone.now() duration_value = form.cleaned_data.get('duration_value') form.instance.duration = Duration.objects.get(value=duration_value) form.instance.creator = self.request.user return super().form_valid(form) And here are the two models if it helps. class Auction(models.Model): """ Model for an auction """ uuid = models.UUIDField( db_index=True, default=uuid.uuid4, editable=False, ) title = models.CharField(max_length=10) valid_from = models.DateTimeField(auto_now_add=True) duration = models.ForeignKey( Duration, on_delete=models.SET_NULL, null=True ) reserve = models.PositiveIntegerField(default=0) creator = models.ForeignKey( get_user_model(), … -
Binding excel sheet row valueto text box using django python
I have some excel sheet data. My task is to bind those row values to text boxes in view.html using django framework I am using openpyxl library. -
Django save in two models with onetoone filed
I m beginner in Django and I have a problem and i can t resolve it I want to save address to every person in a different model I tried in this way but doesn t work Sorry for my english models.py class Person(models.Model): user - models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.EmailField("E-mail", max_length=50, blank=True) address = models.OneToOneField(AddressPerson, on_delete=models.CASCADE) class AddressPerson(models.Model) domicile = models.CharField(max_length=100) county = models.ForeignKey(County, on_delete=models.PROTECT) locality = models.ForeignKey(Locality, on_delete=models.PROTECT) views.py def add_person(request): address = AddressForm(request.POST or None) person = PersonForm(request.POST or None) if address.is_valid() and person.is_valid(): address.save() person.save() return redirect('myapp:add_person' else: address = AddressForm() person = PersonForm() context = { 'form_p': pacient, 'form_a': adresa } return render(request, 'person/add.html',context) -
How to correctly set up the modelform with multiple foreignkeys
I am making a digital menu where you can make an order. I am having some troubles with getting the forms and views for it set up correctly however. The Order has two foreignkeys. FKtable is gained through the GET. FKmenuitem is the problem however. Menuitem has a foreignkey to FKitem which means through the post a Menuitem object has to be made before an Order object can be made. I am not sure how the logic within the view should be done to properly handle this. Here is the model as shown in the picture. class Table(models.Model): number = models.IntegerField(blank=False) def __str__(self): return f'Tafel nummer {self.number}' class Category(models.Model): category_name = models.CharField(max_length=255) def __str__(self): return self.category_name class Item(models.Model): item_name = models.CharField(max_length=255) item_price = models.DecimalField(max_digits=5, decimal_places=2) item_description = models.TextField(max_length=255) FKcategory = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.item_name class Menuitem(models.Model): FKitem = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return f'{self.FKitem.item_name} - {self.quantity}' class Order(models.Model): FKtable = models.ForeignKey(Table, on_delete=models.CASCADE) FKmenuitem = models.ManyToManyField(Menuitem) prepped = models.BooleanField(default=False) delivered = models.BooleanField(default=False) paid = models.BooleanField(default=False) def __str__(self): return f' Bestelling voor {self.FKtable}' -
Associate orders models with address model
i,m creating my ecommerce site in which i need to make posted address by user associated to his order , i followed all instructor step but it still not working hope any one help me to find where is my error, thanks in advance, code followed: -addresses.models.py: from django.db import models from billing.models import BillingProfile class Address(models.Model): billing_profile = models.ForeignKey(BillingProfile,null=True, on_delete=models.CASCADE) address_line_1 = models.CharField(max_length=120) address_line_2 = models.CharField(max_length=120, null=True, blank=True) city = models.CharField(max_length=120) country = models.CharField(max_length=120, default="Egypt") postal_code = models.CharField(max_length=120) def __Str__(self): return str(self.billing_profile) -orders.models.py: import math from django.db import models from carts.models import Cart from django.db.models.signals import pre_save,post_save from ecommerce.utils import unique_order_id_generator from billing.models import BillingProfile from addresses.models import Address ORDER_STATUS_CHOISES=( ('created', "Created"), ('paid', "Paid"), ('shipped', "Shipped"), ('refunded', "Refunded"), ) class OrderManager(models.Manager): def new_or_get(self, billing_profile, cart_obj): qs = self.get_queryset().filter(billing_profile= billing_profile , cart=cart_obj, active=True) created=False if qs.count()==1: obj=qs.first() else: obj= Order.objects.create(cart=cart_obj, billing_profile=billing_profile) created=True return obj, created class Order(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete='CASCADE', null=True) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) # billing_address = models.ForeignKey(Address,related_name="billing_address", on_delete=models.CASCADE, null=True) order_id = models.CharField(max_length=120, blank=True) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) objects = OrderManager() def __str__(self): return self.order_id def update_total(self): cart_total = … -
Coverage is skipping return statements
I have a class and some tests for it. Coverage runs everything just fine, but reports that the lines containing return are not executed. The rest of the multi-line return statement is executed just fine, just not the return itself. Class: class Game(models.Model): ... def __str__(self): return ( f'Name: {self.name}\n' f'Status: {self.status}\n' ) def render_html(self): return ( f'Name: {escape(self.name)}<br/>' f'Status: {escape(self.status)}<br/>' ) The test is calling both render_html and __str__. I'm using Django and running with coverage run --branch ./manage.py test -
SMTP not sending email verification
I am going to send email verification with django-allauth when the user is registered but it is not working I looked at some solutions it is the same what I did but in my case it did not work. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) SITE_ID = 1 EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 587 EMAIL_HOST_USER = 'aagaybullaev@gmail.com' EMAIL_HOST_PASSWORD = '******' SERVER_EMAIL = 'aagaybullaev@gmail.com' when mail backends is console it works perfect but with smtp it showed this error Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Zako5\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "C:\Users\Zako5\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Zako5\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 307, in _get_socket self.source_address) File "C:\Users\Zako5\AppData\Local\Programs\Python\Python37\lib\socket.py", line 727, in create_connection raise err File "C:\Users\Zako5\AppData\Local\Programs\Python\Python37\lib\socket.py", line 716, in create_connection sock.connect(sa) Please any suggestion! thank you -
TypeError Exception: argument must be int or float on a view argument inside a template
I'm trying to check if there are any products on the productList, but this shows up: Exception Value: argument must be int or float - on this line {% if listaProdutos %} in home.html If you need extra information let me know. Thanks in advance for your help! views.py from django.shortcuts import render from .models import Product def home(request): context = {'productList': Product.objects.all() } return render(request, 'main/home.html', context) models.py from django.db import models class Product(models.Model): name = models.CharField(max_length = 200) price = models.DecimalField(max_digits=10, decimal_places=2) description = models.TextField() def __str__(self): return self.name home.html <section class="mainContent"> {% if productList %} ----DO SOMETHING---- {% endif %} </section> -
File Permissions on Docker Container
I am facing a very weird issue when uploading files to my application directory using web forms. While everything in terms of backend seems to work very well, when files of certain extensions are uploaded (e.g. .apk ) the permissions are set so that only root has read access to those files, while when other types of files (e.g. images ) are normally accessible. I do not know if the extensions or the big size ( around 15 MB comparing to KBs ) but it looks like there is some kind of filtering going on, on the background -
RuntimeError: Model class captcha.models.CaptchaStore doesn't declare an explicit app_label and isn't in an application in INSTALLED _APPS
After minor migration I have keeping receive from django during RUNSERVER command following errors: RuntimeError: Model class captcha.models.CaptchaStore doesn't declare an explicit app_label and isn't in an application in INSTALLED _APPS. This is caused by django-simple-captcha and this app had been working for quite a while ( a month) before and I wasn't changed something in this exact app. My settings are like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # custom "boats.apps.BoatsConfig", "articles.apps.ArticlesConfig", #3rd party "captcha", "bootstrap4", "django_cleanup", "easy_thumbnails", "social_django", "crispy_forms", "extra_views", "debug_toolbar", "reversion", "dynamic_validator", "django.forms", # new for a custom widgets How I can fix this problem? It seems weird… Or alternativelly how to roll back the last migration? full trace-back is bellow: (myproject) C:\Users\hardcase1\PycharmProjects\myproject>python manage.py runserver Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "C:\python\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\python\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\core\management\commands\runserver.py", line 109 , in inner_run autoreload.raise_last_exception() File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exc eption raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\hardcase1\.virtualenvs\myproject-N1oU6R8w\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File … -
How to connect database for django-erp
I am unexperienced with python, My problem is I am connecting to django-erp it asks for username and password in localhost. How can I set username and password? Thanks for helping. ADMINS = ( # ('example', 'example@gmail.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'default.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } -
How to Raise Error on @permission_required decorator in Function Based View
How to raise an error message if permission_required is failed on Function Based View?i want to raise error message instead redirect to login page, i know how to raise an error message in CBV but i don't know how to raise it in Function based view, Please Help Me. Thanks and here is a code. @permission_required('request.user.projectuser.change_projectusermodel') def update(request, id): test = User.objects.get(id=id) try: second_form = UpdateAccountDetailForm(request.POST or None, instance=test.profile) except: second_form = UpdateAccountDetailForm(request.POST or None) try: third_form = UserRoleForm(request.POST or None, instance=test.roles) except: third_form = UserRoleForm(request.POST or None) if request.method == 'POST': form = UsersForm(request.POST, instance=test) form2 = second_form form3 = third_form else: form = UsersForm(instance=test) form2 = second_form form3 = third_form return save_all(request, form, form2, form3,'projectuser/update.html') -
django: The database driver doesn't support modern datatime types
I am trying the connect the MSSQL server and pull the data from the SQL server. I landed on below error. "django.core.exceptions.ImproperlyConfigured: The database driver doesn't support modern datatime types." Version: Django: 2.2 Python: 3.7 django-pyodbc-azure-2.1.0.0 pyodbc-4.0.26 DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'server\\DB', 'NAME': 'Archive', 'USER': 'Admin', 'PASSWORD': '*****', 'PORT': '49422', 'OPTIONS': { 'driver': 'SQL Server', 'dsn': 'Django', 'extra_params': "Persist Security Info=False;server=server\\DB", }, } } please help!!! -
What's wrong with this simple view function?
The models.py file conatains: class Story(models.Model): title = models.CharField(max_length=255) text = models.TextField() author = models.ForeignKey(User) The forms.py file contains: class StoryForm(forms.Form): class Meta: model = Story The views.py file contains: def story(request): if request.method == 'POST': story_form = StoryForm(request.POST) if story_form.is_valid(): story_form.cleaned_data['author'] = request.user.id The problem here has to be one of these 4 options: Story.author must be a "User" instance because objects in Form.cleaned_data dict are converted to python objects by to_python() method Form.cleaned_data is not yet defined Form.cleaned_data must only be filled in the Form.clean() or Form.clean_() methods Nothing is wrong My best guess was 3, because I thought that 2 is invalid because cleaned_data is a predefined function, and I couldn't really make sense of 1. Which of the 4 is the real issue? -
how to make django tempory list
i want to know that is it have way to make a tempory list that it can add by input field and not save to server until click some button. like add to cart button. I will use this for POS system. sorry for bad grammar -
how concurrency handled in django?
I'm coming from java & spring framework. In spring, there's a clear mention of how many instances of your classes are running, and whether two threads can be given the same instance of a class, so you know if you need to take care of thread-safety in some operations. I'm reading django's documentation and I'm seeing no mention of what happens under the hood. For example, how are class based views instantiated? Do all threads share a common instance of the class? Is a single instance created for each request? Similar questions for model classes. Is there any mention of such topics in the documentation? -
How to do clean logging, without making code look awful?
I am trying to write clean code, so i don't want my code to be polluted with random logging. This for me looks awful: def generate_auth_token(self): logger.debug("Existing auth token: {}".format(self.auth_token)) self.auth_token = uuid.uuid4() self.save() logger.debug("Updated auth token: {}".format(self.auth_token)) return str(self.auth_token) The logs then looks like this: backend-api_1 | DEBUG: Device token: 66f4b515-c6f5-433c-885f-61c8a1f63ce5 backend-api_1 | Debug: Existing auth token: 66f4b515-c6f5-433c-885f-61c8a1f63ce5 backend-api_1 | Debug: Updated auth token: 66f4b515-c6f5-433c-885f-61c8a1f63ce5 It just difficult to read code like that. I came up with idea, to log every function, by using decorator. def log_input_output(logger_name='', func_name=None, log_input_values=True): logger = logging.getLogger(logger_name) def _log_input_output_decorator(func): if not func_name: message_prefix = f'{func.__name__}' else: message_prefix = f'{func_name}' @wraps(func) def wrapper(*args, **kwargs): logger.info(f'{message_prefix} started') if log_input_values: if args: logger.debug(f'{message_prefix} input args: {args}') if kwargs: logger.debug(f'{message_prefix} input kwargs: {kwargs}') try: result = func(*args, **kwargs) except Exception as e: logger.error(f'{message_prefix} error: {e}') raise e logger.info(f'{message_prefix} finished successfully') logger.debug(f'{message_prefix} finished with result: {result}') return result return wrapper return _log_input_output_decorator Example from above, now looks much more clean @log_input_output(logger_name=__name__) def generate_auth_token(self): self.auth_token = uuid.uuid4() self.save() return str(self.auth_token) but the logs are, less clean backend-api_1 | INFO: generate_auth_token started backend-api_1 | DEBUG: generate_auth_token input args: (<self object at 0x7fc18085d1c8>) backend-api_1 | INFO: generate_auth_token finished successfully backend-api_1 | DEBUG: … -
Django-ajax upload file
I've been trying to upload a text file but can't seem to get it working. except FileField Data all other Data is send to view successfully. when trying to print(request.FILES) i get MultiValueDict:{}, it show dictionary is blank. form's FileField data is not passed in view. I think some problem is in create.js but can't figure it out please help. create.js $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-certificate').modal('show'); }, success: function(data){ $('#modal-certificate .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#Certificate-table tbody').html(data.list); $('#modal-certificate').modal('hide'); jQuery("body").load(window.location.href); } else { $('#modal-certificate .modal-content').html(data.html_form) jQuery("body").load(window.location.href); } } }) return false; } // create $(".show-form").click(ShowForm); $("#modal-certificate").on("submit",".create-form",SaveForm); //update $('#Certificate-table').on("click",".show-form-update",ShowForm); $('#modal-certificate').on("submit",".update-form",SaveForm) //delete $('#Certificate-table').on("click",".show-form-delete",ShowForm); $("#modal-certificate").on("submit",".delete-form",SaveForm); }); form.py from django import forms from SharedApps_Application.models import certificateDb from django.contrib.admin.widgets import AdminDateWidget from django.forms.fields import DateField class CertificateForm(forms.ModelForm): startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) class Meta: model = certificateDb fields = ('application', 'startdate', 'expiredate', 'environment_type','pdf' ) view.py from SharedApps_Application.models import certificateDb from SharedApps_Application.forms import CertificateForm from django.http import JsonResponse from django.template.loader import render_to_string def list(request): certificatedata = certificateDb.objects.all() context … -
Every time I run migration or runserver command, I get "NodeNotFoundError" error
I can't initiate any django project, I tried uninstalling and reinstalling but didn't help. The error looks like this: raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0010_user_following dependencies reference nonexistent parent node ('account', '0002_contact') Even if I start a fresh project, somehow django throws this same error. I tried : python manage.py migrate myproj --fake-initial, but it didn't help. I was working on git as well and it's happening since. -
Why else block is executing while if block is true in Django signals?
I am writing a signal function that will send a signup notification email to the user when s/he signs up and an update notification email when s/he updates the user profile. For that, I have used an if-else block to check the created parameter. If it is true, the user will get signup notification. Otherwise, the user will get a profile update notification. It works fine when the user object is updated. But when a new user signs up, both of the if and else blocks are executing and the new signed up user gets two email notification: one signup notification and one profile update notification. The full signal code is given below: #myapp/signals.py from django.core.mail import send_mail from django.db.models.signals import post_save from django.dispatch import receiver from django.template.loader import render_to_string from django.utils.html import strip_tags #getting custom user model User = get_user_model() @receiver(post_save, sender=User) def send_user_notification(sender, instance, created, **kwargs): if created: subject = 'Signup Notification' html_message = render_to_string( 'email/signup_notification.html', { 'username': instance.username, 'email': instance.email, } ) message = strip_tags(html_message) send_mail(subject, message, from_email='info@silatechnologies.com', recipient_list=[instance.email,], html_message=html_message) else: send_mail(subject='Your profile on Sila Crowdfunding updated!', message='Dear ' + instance.username + ', your profile information is updated successfully.', from_email='info@silatechnologies.com', recipient_list=[instance.email, ] ) I have also used … -
How to insert URL into SVG icon
I heed to put links into svg icons of social medias. Here I have svg icons http://joxi.ru/a2XqZEPHwl9JWA Those are svg code put into html page like this <div class="facebook-container"> <svg class="socials-icons facebook-icon" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <title>Share on Facebook</title> <path d="M22.676 0H1.324C.593 0 0 .593 0 1.324v21.352C0 23.408.593 24 1.324 24h11.494v-9.294H9.689v-3.621h3.129V8.41c0-3.099 1.894-4.785 4.659-4.785 1.325 0 2.464.097 2.796.141v3.24h-1.921c-1.5 0-1.792.721-1.792 1.771v2.311h3.584l-.465 3.63H16.56V24h6.115c.733 0 1.325-.592 1.325-1.324V1.324C24 .593 23.408 0 22.676 0"/> </svg> {% post_to_facebook object.get_absolute_url "" %} </div> SVG has styles - fill color and :hover color, it wors well. But you might notice this code within .facebook-icon - {% post_to_facebook object.get_absolute_url "" %} This is Django plugin, which creates the share-link for this icon. Actually it creates div with class .facebook-this which contains tag with the link. Like this: <div class="facebook-this"> <a href="https://www.facebook.com/sharer/sharer.php?u=http%3A//127.0.0.1%3A8000/news/middle-east-investors-meetup" target="_blank"></a> </div> What I did, is placed this link on top of facebook svg icon, apple to apple using css. But after that, the link became to cover the icon and :hover doesn't work any more. I've made the link transparent, but it still covers whole svg and doesn't let hover work for svg. The problem is that plugin creates link automatically during rendering of the page, … -
Handling multiple exceptions in CBV Django
Is there a way i can handle both the exceptions from different models and still pass none as context individually. Views.py class ProfilePage(DetailView): model = models.UserCreation context_object_name = 'profile' def get_context_data(self, *args, **kwargs): context = super(ProfilePage, self).get_context_data(*args, **kwargs) user = User.objects.get(username=UserCreation.objects.get(id=self.kwargs.get('pk'))) print(self.request.user,user,self.kwargs.get('pk')) try: context['data'] = ProfileData.objects.get( user=user) context['userdata'] = User.objects.get( username=user) context['creationdata'] = UserCreation.objects.get( user=user) context['friends'] = Friends.objects.get( user=self.request.user,added=user) context['sorted'] = sorted(chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)), key=lambda instance: instance.date, reverse=True) except ((ProfileData.DoesNotExist as e) or (Friends.DoesNotExistas as f)) : if e: context['data']= None elif f: context['friends'] = None return context -
Django - How to extend Custom User using CreateView
I want to create user register form using CreateView. But, I don't know how to combine User Model to Profile Model in view.py My environmental ・Django2.2 Here is the code I wrote: ▪️model.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) gender = models.CharField(max_length=20, blank=True) ▪️form.py class UserCreateForm(UserCreationForm): class Meta: model = User if User.USERNAME_FIELD == 'email': fields = ('email',) else: fields = ('username', 'email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' class ProfileForm(forms.ModelForm): CHOICES = ( ('female', 0,), ('male', 1,), ('not_applicable', 2,) ) gender = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, required=False) ▪️View.py from django.views import generic from .forms import UserCreateForm class UserCreate(generic.CreateView): template_name = 'accounts/create.html' form_class = UserCreateForm def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) domain = current_site.domain context = { 'protocol': 'https' if self.request.is_secure() else 'http', 'domain': domain, 'token': dumps(user.pk), 'user': user, } subject_template = get_template('accounts/mail/create/subject.txt') subject = subject_template.render(context) message_template = get_template('accounts/mail/create/message.txt') message = message_template.render(context) user.email_user(subject, message) return redirect('accounts:user_create_done') ▪️create.html <form action="" method="POST"> {{ form.non_field_errors }} {% for field in form %} <p>{{ field }} {{ field.errors }}</p> {% endfor %} … -
Is there any support in Django Rest Framework for multi-tenancy with MongoDB?
I have multiple customers and I have to create separate DB for different customers to separate customers info. Now based on the URL, I have to switch the DB for the specific customer. For example, cust1.domain.com means cust1 is the customer and DB name both. I have tried "rest_framework_mongoengine" but how to achieve DB routing using rest_framework_mongoengine's DocumentSerializer in the query itself? For example, the default DRF approach: ModelName.save(using='db_name'). This is example is not working with mongoengine's Document type model. Model: from mongoengine import fields, Document class ModelName(Document): param1 = fields.StringField() Serializer: from rest_framework_mongoengine.serializers import DocumentSerializer class ModelNameSerializers(DocumentSerializer): class Meta: model = ModelName fields = ('param1',) Is there any default DRF approach to do the DB routing in each API call? Is there any 3rd party library to achieve the same? Is there any way I can manually save the data specifying the DB name directly? eg: ModelVarName.save(using='db_name'). Answer the questions considering (a) No migrations should be required. (b) I have to only NoSQL DB. -
Should a Kafka Consumer be a part of Django Web Layer or a separate service?
I have a Django application which has a Kafka integration to process some orders. The topics on the Kafka queue are created dynamically so the consumers has also to be subscribed dynamically. Now when I initialise a consumer it goes to block the main thread so I have to start the consumer in a background thread, but I am not able to see any print statements so I am not sure if the consumer is initialized, also if this is the right approach to do so ? def kafka_consumer(topic) : try : if topic is None : raise Exception("Topic is none, unable to initialize kafka consumer") conf = {'bootstrap.servers': "localhost:9092", 'group.id': 'test', 'session.timeout.ms': 6000, 'auto.offset.reset': 'earliest'} c = Consumer(conf) print("Subscribing consumer to topic ",topic[0]) c.subscribe(topic) # Read messages from Kafka, print to stdout try: while True: msg = c.poll(timeout=1.0) if msg is None: continue if msg.error(): raise KafkaException(msg.error()) else: sys.stderr.write('%% %s [%d] at offset %d with key %s:\n' % (msg.topic(), msg.partition(), msg.offset(), str(msg.key()))) try : print(json.loads(msg.value())) print("---------------------------------") objs = serializers.deserialize("json", msg.value()) for obj in objs : print(obj) print(obj.object) except Exception as e : import traceback print(traceback.format_exc()) except Exception as e: import traceback print(traceback.format_exc()) finally: c.close() except Exception as e: import …