Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
df.to_html() method is displaying the actual html on the webpage and not the representation it should (Django website)
I'm currently making a django website for a Software Engineering class. I'm having a problem with displaying a pandas dataframe using the .to_html() method. The webpage template is rendering the actual html code on the UI instead of the representation of the html code. I don't understand why and have looked for similar problems on the internet. I think I can't find a similar problem because I don't know the right words to use in the search engine to get the answer I want. The webapp template (called graphs.html) is displaying the actual code itself. Here is a code fragment: <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>itemId</th> <th>title</th> <th>endPrice</th> <th>location</th> <th>endTime</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>283584749546</td> <td>1979 80 TOPPS #18 WAYNE GRETZKY ROOKIE CARD PSA 6 EX-MINT</td> <td>500.0</td> <td>Canada</td> <td>2019-11-17T08:08:30.000Z</td> </tr> <tr> <th>1</th> <td>163940352354</td> <td>1979 Topps Hockey Unopened Wax Pack Gretzky PSA ?</td> <td>103.5</td> <td>Rice Lake,WI,USA</td> <td>2019-11-16T16:27:42.000Z</td> </tr> <tr> <th>2</th> <td>293329130191</td> <td>1979/80 Topps Wayne Gretzky Rookie #18 High End PSA 6 RC Priced to Sell</td> <td>345.0</td> <td>Liberty Lake,WA,USA</td> <td>2019-11-15T22:04:27.000Z</td> </tr> <tr> As you can see, the UI is displaying html tags when it shouldn't. Below, the html is displaying without the tags showing, and would look like … -
django Arabic Hijri calendar
I use Django 2.2 When I have a field that has DateTimeField type, Django automatically uses Django calendar. But in Saudi Arabia we use Islamic Hijri Calendar. How can I define a field with Hijri calendar? -
Can't Login into Django Admin
What I know about AbstractUser and AbstractBaseUser is that AbstractBaseUser allow you to start from scratch but AbstractUser is to work with existng fields in USER. Similarly I created model using AbstractBaseUser and changed name of some fields like is_admin and is_staff but when I tried to login in Django Admin it doesn't allows. I figure out the problem and change name back to default and it worked. So if I wan't to login in to django admin what should I do. -
Adding a Custom DateTimePicker in a Django form
I'm quite new to Django, so I decided to build a simple app to test my skills. On one of the model forms, I have a DateTimeField, but that only defaults to a TextField. I would like to create a custom datetime picker with bootstrap, but I didn't know how to implement it. I followed a tutorial for Tempus Dominus Bootstrap 4 here. I have everything they say, but when I navigate to my form, it displays an error: 'BootstrapDateTimePickerInput' object has no attribute 'is_hidden'. Models.py from django.db import models class ToDoItem(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() remind_time = models.DateTimeField() Widgets.py from django.forms import DateTimeField class BootstrapDateTimePickerInput(DateTimeField): template_name = 'main/bootstrap_datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = 'datetimepicker_{name}'.format(name=name) if attrs is None: attrs = dict() attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context forms.py from django import forms from .widgets import BootstrapDateTimePickerInput from .models import ToDoItem class NewEventForm(forms.ModelForm): start_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) end_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) remind_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) class Meta: model = ToDoItem fields = ['title', 'description', 'start_time', 'end_time', 'remind_time'] views.py from django.shortcuts … -
Query through intermediate models that returns multiple results, using Django Q object
How to follow an intermediate 'through' model, in a Q object? I'm trying to get a list of the ids of all Property objects that a User is a member of, in one query. A User is a member of a BusinessUnit through BusinessUnitMember. How do I make a filter with a Q object that finds all (multiple) BusinessUnitMembers for a particular User, and then finds all (multiple) BusinessUnits for those BusinessUnitMembers? class Property(BaseModel): """Physical Things belonging to various Business Units""" category = models.CharField(max_length=255, choices=CATEGORY_CHOICES) objects = PropertyQuerySet.as_manager() @property def asset(self): asset_maps = { 'typea': 'type_a_asset', 'typeb': 'type_b_asset', } if self.category not in asset_maps: return None return getattr(self, asset_maps.get(self.category), None) class AssetBase(models.Model): """Abstract Base Asset model.""" business_unit = models.ForeignKey('BusinessUnit', null=True, on_delete=models.SET_NULL) class TypeAAsset(AssetBase): """Type A Assets""" property = models.OneToOneField('Property', null=True, on_delete=models.CASCADE, related_name='type_a_asset') class TypeBAsset(AssetBase): """Type B Assets""" property = models.OneToOneField('Property', null=True, on_delete=models.CASCADE, related_name='type_b_asset') class BusinessUnit(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey('core.User', null=True, on_delete=models.SET_NULL, related_name='owned_business_units') class BusinessUnitMember(models.Model): """ ``through`` model for BU and members. """ business_unit = models.ForeignKey('BusinessUnit', on_delete=models.CASCADE) member = models.ForeignKey('core.User', on_delete=models.CASCADE) I need to find the ids of all Property objects that the current User is a member of. I'm thinking of a filter like: available_ids = Property.objects.filter(Q(type_a_asset__business_unit__in=user.businessunitmember.all().businessunit_set.all())).values_list('id', flat=True) … -
django-select2: Select Field doesn't open when tabbed
In my simple Django App, I've implemented django-select2. I have a form with 2 fields: product and category. When I create a new product I first give it a title and than tab to the category-field, but the dropdown does not open automatically. Only when I press Space-Bar or Enter the dropdown opens. What can I do so that the dropdown opens automatically, when it is reached? Here my code: forms.py from django import forms from django_select2.forms import Select2Widget, ModelSelect2Widget, Select2MultipleWidget from .models import Product, Category class MyForm(forms.ModelForm): category = ModelSelect2Widget(queryset=Category.objects.all()) class Meta: model = Product fields = ['name', 'category'] widgets = { 'category': Select2Widget, } models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=120) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name product.html {% extends 'base.html' %} {% block content %} {{ form.media.css }} <br> <form action="" method="POST"> {% csrf_token %} {{ form}} <button type="submit">Save</button> </form> {{ form.media.js }} {% endblock content %} -
How can make django find a specific css file forSphinx?
I am using Sphinx to document my django application. My directory tree, based on this django tutorial is: . ├── db.sqlite3 ├── help │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── templates │ │ └── help │ │ ├── _images │ │ ├── index.html │ │ ├── _modules │ │ ├── objects.inv │ │ ├── _sources │ │ │ └── index.rst.txt │ │ └── _static │ │ ├── css │ │ │ ├── badge_only.css │ │ │ └── theme.css │ │ ├── fonts │ │ └── js │ │ ├── modernizr.min.js │ │ └── theme.js │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── mysite │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── users ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views. The code to set the css file in the html is: <link … -
Mocking a Django model specific instance function
I have a test that has two django model instances. I want to mock two functions in a django model instance - only for one of the instances. I want the other instance to not have mocks. This is my code: The model: class MyModel(models.Model): id = models.AutoField(primary_key=True) def __init__(self, *kargs, **kwargs): super(self.__class__, self).__init__(*kargs, **kwargs) @property def count(self): logic.... return count def get_data(self, parameter=None): logic..... return data The test: def test(self): data_dict = {....} my_model = MyModel(**data_dict) my_model.save() data_dict2 = {....} data_dict2['parent'] = my_model my_model2 = MyModel(**data_dict) my_model2.save() with patch.object(my_model2, 'count', lambda x: 20), \ patch.object(my_model2, 'get_data', lambda x: {[{'Id': str(i)} for i in range(20)]}): self.assertEqual(my_model2.count, 3) # This will also call my_model.get_data and my_model.count - of the instance I am trying to mock These mocks don't work - I get this error: Error Traceback (most recent call last): File "x.py", line x, in test with patch.object(my_model2, 'count', lambda x: 20), \ File "x/mock/mock.py", line 1485, in __enter__ setattr(self.target, self.attribute, new_attr) AttributeError: can't set attribute How can I mock a django model instance functions? Thanks -
How to gert id from foreign key model in django
How Do I get id of to_user from the below model: class Friend(models.Model): status = models.CharField(max_length=10) from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user') to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user") date_modified = models.DateTimeField(auto_now=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def create(self,request, **kwargs, ): friend = self.create(from_user_id=request.user.id, status="Pending") return friend class Meta: unique_together = (('from_user', 'to_user'),) def __str__(self): return self.to_user.email my view : def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" Friend.status = "pending" try: uid = urlsafe_base64_decode(uidb64) friend_user = User.objects.filter(id=Friend.to_user.id) f = Friend.objects.filter(friend_id = friend_user) if f: f.status=status f.save() f.status = "accepted" return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status}) else: f.status = "rejected" f.save() return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status}) except AttributeError: return render(request, 'blog/base.html') I cannot retrieve the friend_user = User.objects.filter(id=Friend.to_user.id) Thanking you in advance, -
Deploy angular 8 and django rest framework
I have successfully deployed django rest framework backend and angular 8 frontend apps independently on Heroku. I'm clueless whether they should be deployed as separate apps or should be integrated on single instance. What is the best practice when it comes to DRF and SPA,particularly angular? If to be deployed as independent app,how can I configure DRF backend to respond to the frontend in another server. Any help would be appreciated. Thanks -
Django database keeps vanishing on Heroku
I have a Django project that is live on Heroku. I'm trying to create a superuser on remote, but I get: django.db.utils.OperationalError: no such table: auth_user So I run heroku run python manage.py migrate and get the expected response. Running python manage.py migrate on ⬢ MyWebsite... up, run.5296 (Free) Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK ... But when I run heroku run python manage.py createsuperuse, I get the same old django.db.utils.OperationalError: no such table: auth_user No matter how many times I run migrate, the table just seems to vanish right after. Any ideas on whats going on? Thanks! -
show in a table html template the result of a SQL query using DJANGO
I have DDBB with a specifict table that is the result of a store procedure calculation. I would like to show this SQL table in a table in html using a DJANGO Template. I have tried in many differents ways but the nearest I got was show only one register. views.py cursor.execute("SELECT NIVEL, COMP, PONDERACION FROM COMP ORDER BY NIVEL ") COMP = cursor.fetchall()[0] index.html: <table> <tr> <th>NIVEL</th> <th>COMPONENTE</th> <th>PONDERACION</th> </tr> {% for row0 in COMP %} <td>{{ row0 }}</td> {% endfor %} </tr> </table> I know that a query es a tuppla but i dont know how to transform a tuppla with many registers in a table just like the result of a sql query... thanks you very much... -
Filling ManyToMany field of a form in class based view - Django
I am trying to create a ManyToMany relationship between Project and User model. I created a users_list field for Project model to hold the list of users that can access a specific project. While creating a project in, I fill the field user, successfully, with the current logged in user. For the users_list field, initially, I try to add the current logged in user to the users_list (other uses shall be added later when invited). However, I cannot. I get the following error: ValueError: invalid literal for int() with base 10: '' models.py class Project(models.Model): title = models.CharField(max_length=1000) user = models.ForeignKey(settings.AUTH_USER_MODEL, default="", on_delete=models.CASCADE) users_list = models.ManyToManyField(User, related_name='users_list') def __str__(self): return self.title + " - " + str(self.user) def get_absolute_url(self): return reverse("planner:projects_listed") views.py class ProjectCreateView(CreateView): model = Project fields = ["title"] template_name = "planner/projects_listed.html" def get_success_url(self): return reverse("planner:projects_listed") def get_context_data(self, **kwargs): kwargs["project_list"] = self.model.objects.filter(user=self.request.user) return super(ProjectCreateView, self).get_context_data(**kwargs) def form_valid(self, form): form.instance.users_list.add(self.request.user) form.instance.user = self.request.user return super(ProjectCreateView, self).form_valid(form) -
get_form in ModelAdmin causing TypeError
This question refers to the issue I was having here which has not been solved. I have created a new simplified version of the MemoForm called AdminMemoForm to help me isolate the issue. After creating the new version of the form I have come to find that the get_form method is what is causing the TypeError: MemoForm object not callable. Here is a snippet of the new code that is throwing the error: Forms.py: class AdminMemoForm(forms.ModelForm): """ Memo creation form, related to: :model: 'memos.Memo', """ class Meta: model = Memo fields = ( 'title', 'content', 'important', 'word_file', 'receiver', 'read', 'unread', ) Admin.py: class CustomMemoAdmin(admin.ModelAdmin): form = AdminMemoForm def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) # if not request.user.is_superuser: # self.fields = ( # 'title', # 'content', # 'important', # 'receiver', # 'read', # 'unread', # 'word_file', # ) # self.filter_horizontal = ('casino',) return form() This is probably simple but I don't get why this error is arising. Any help would be appreciated. -
Add custom url action parameter to django-cms
The common url action parameters in django-cms are for example: ?edit to enter Edit-mode, ?toolbar_off to disable/hide the toolbar. Now I'd like to add a new action parameter e.g. ?logout which just logs out the user no matter on which url he/she currently is. I'd tried to include this in the urls.py with the following pattern: url(r'^.*\?logout$', RedirectView.as_view(url='/admin/logout/')), I read in another SO answer that you shouldn't catch URL Params with an url pattern... Should I do this in a kind of middleware? Or where else? -
How lazy_model_operation in app register wait to run in Django?
I have read source code Django, and I get a stuck when reading method lazy_model_operation in module registry belong to apps package. def lazy_model_operation(self, function, *model_keys): """ Take a function and a number of ("app_label", "modelname") tuples, and when all the corresponding models have been imported and registered, call the function with the model classes as its arguments. The function passed to this method must accept exactly n models as arguments, where n=len(model_keys). """ # Base case: no arguments, just execute the function. if not model_keys: function() # Recursive case: take the head of model_keys, wait for the # corresponding model class to be imported and registered, then apply # that argument to the supplied function. Pass the resulting partial # to lazy_model_operation() along with the remaining model args and # repeat until all models are loaded and all arguments are applied. else: next_model, *more_models = model_keys # This will be executed after the class corresponding to next_model # has been imported and registered. The `func` attribute provides # duck-type compatibility with partials. def apply_next_model(model): next_function = partial(apply_next_model.func, model) self.lazy_model_operation(next_function, *more_models) apply_next_model.func = function # If the model has already been imported and registered, partially # apply it to the … -
raise ConnectionError(self._error_message(e)) kombu.exceptions.OperationalError: Error 111 connecting to localhost:6379. Connection refused
minimal django/celery/redis is running locally, but when deployed to heroku gives me the following error, when I run on python: raise ConnectionError(self._error_message(e)) kombu.exceptions.OperationalError: Error 111 connecting to localhost:6379. Connection refused. This is my tasks.py file in my application directory: from celery import Celery import os app = Celery('tasks', broker='redis://localhost:6379/0') app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) @app.task def add(x, y): return x + y Requirements.txt: django gunicorn django-heroku celery redis celery-with-redis django-celery kombu I have set worker dyno to 1. Funny things is i could have sworn it was working before, now it doesnt work for some reason. -
AttributeError: Cutome User model object has no attribute 'password'
I have a Profile model customizing the User model by having a one to one relationship to the User model, the code for the model is the following class Profile(models.Model): user = models.OneToOneField(User, parent_link=True, on_delete=models.CASCADE) bio = models.TextField() slug = models.SlugField(unique=True, blank=True) avatar_thumbnail = ProcessedImageField(upload_to='images/', default='/images/default.png', processors=[ResizeToFill(300, 300)], format='JPEG', options={'quality': 60}) location = models.TextField() tags = models.ManyToManyField(Tag) contact_information = models.TextField() verified = models.BooleanField(default=False) counter = models.IntegerField(default=0) def __str__(self): return self.user.username def save(self, *args, **kwargs): print('self.username') print(self.user.username) self.slug = self.user.username super(Profile, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('infrastructure:edit-user-profile', kwargs={'slug': self.slug}) whenever I enter the shell with python manage.py shell and get the Profile queryset Profile.objects.all() I get the error AttributeError: 'Profile' object has no attribute 'password' and whenever I enter the admin panel and click on the Profiles section I get the same error saying the same thing what's wrong ? my admin.py code from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User # Register your models here. from . import models class SubjectTagAdmin(admin.TabularInline): model = models.SubjectTag.tags.through class TagAdmin(admin.ModelAdmin): inlines=[SubjectTagAdmin, ] admin.site.register(models.Tag, TagAdmin) admin.site.register(models.SubjectTag) admin.site.register(models.Profile) admin.site.register(models.Organization) -
Is there a default file upload size limit in django?
I am using django FileField and ImageField in my models but I am wondering is there any default upload size limit for files.I researched about it and I found that we can limit the file upload size to some size by configuring MAX_UPLOAD_SIZE in the project's settings.py but what If i didn't handle any validation for the Image/file field?Then will the user be able to upload image of any unlimited size or is there any default size limit for this ? -
How can i customize login api from djoser package?
I just want to give a user details in a login response, currently, I'm getting 'token' and 'refresh' in http://127.0.0.1:8000/auth/jwt/create/ JWT login API response. I want to return with login user details here is the response snapshot of jwt/create/, JWT Response Image -
django: getting error in django registration, in _wrapped_view() missing 1 required positional argument: 'request'
I want to use django's registration form, for that i installed django-registration-redux.i have changed my settings.py accordingly. im new to django so by reading this error message i can not resolved this. plz help settings.py """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'blog', ] 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', ] ROOT_URLCONF = 'myregi.urls' 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', ], }, }, ] WSGI_APPLICATION = 'myregi.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('accounts', include('registration.backends.default.urls')), ] blog.urls.py from django.conf.urls import url from .views import index from django.urls import path urlpatterns= [ url(r'', index, name="index"), ] views.py from django.shortcuts import render from .models import Detail from django.utils.decorators import method_decorator from django.contrib.auth.decorators … -
DRF: custom update method not being executed in ModelSerializer class
I am writing a REST API using Django Rest Framework. I'm encoutering a wierd problem here. I have an app called user. Models.py: @python_2_unicode_compatible class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile_picture = models.ForeignKey(File, on_delete=models.DO_NOTHING, default=None, null=True, blank=True) email = models.EmailField('Email address', unique=True) name = models.CharField('Name', default='', max_length=255) phone_no = models.CharField('Phone Number', max_length=255, unique=True) company_name = models.CharField('Company Name', default='', max_length=255) verification_token = models.CharField('Verification Token', default='', max_length=255) address = models.CharField('Address', default='', max_length=255) address_coordinates = models.CharField('Address Coordinates', default='', max_length=255) country = models.CharField('Country', default='', max_length=255) pincode = models.CharField('Pincode', default='', max_length=255) pan_number = models.CharField('Pan Number', default='', max_length=255, blank=True) gst_number = models.CharField('GST Number', default='', max_length=255, blank=True) is_advertisor = models.BooleanField(default=False) is_signage_owner = models.BooleanField(default=False) phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now_add=True) from_time = models.TimeField(blank=True, default='00:00') to_time = models.TimeField(blank=True, default='00:00') category = models.CharField('Category', default='', max_length=255, blank=True) reset_token = models.CharField(max_length=255, default='') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email Views.py: class UserViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = User.objects.all() permission_classes = (AllowAny,) filter_backends = [DjangoFilterBackend] filterset_fields = ['id', 'email', 'phone_no'] def get_serializer_class(self): if self.action == 'create': return CreateUserSerializer elif self.action == 'update': return UpdateUserSerializer else: return UserSerializer Serializers.py: class CreateUserSerializer(serializers.ModelSerializer): def create(self, validated_data): token = account_activation_token.make_token(validated_data['email']) validated_data['verification_token'] = token user = User.objects.create_user(**validated_data) subject = 'Account … -
How to generate a magic number and populate it to the database upon user registration?
I am in search of a way to assign a random generated number-letter combination to a user upon registering on my page. So if a user registers on my site, there shall be a random generated number-letter combination (let's call it magic number) assigned to this user and populated to the PostgreSQL users table. Is there a common approach to do so? Would I have to define such function within the existing class or is there a different workflow? This is my model (inherited from Djangos AbstractUser model): from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass first_name = models.CharField(max_length=500, blank=False) last_name = models.CharField(max_length=30, blank=False) def __str__(self): return self.username -
Return posts and projects with the same category (in 2 different table) to be handled in one view function
I want to return all blog posts and projects with the same categories and display it in one page. I have 2 Django apps with 2 different models. What these two models has in common is a Category class, I understand that this will create 2 different tables in the db, 1 for blog category and 1 for project category. These are my models: Blog models.py class Category(models.Model): category_name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='category_name', always_update=True, max_length=500, unique=True) class Meta: verbose_name_plural = 'categories' # to make sure a human readable string is returned and not Object def __str__(self): return self.category_name class Post(models.Model): title = models.CharField(max_length=500, unique=True) slug = AutoSlugField(populate_from='title', always_update=True, max_length=500, unique=True) summary = models.CharField(max_length=500) body = MarkdownxField() image = models.FileField() date_posted = models.DateTimeField(default=timezone.now) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField(Category, related_name='posts') status = models.CharField(max_length=10, choices=STATUS, default='draft') author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-created_on'] def __str__(self): return self.title Project models.py class Category(models.Model): category_name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='category_name', always_update=True, max_length=500, unique=True) class Meta: verbose_name_plural = 'categories' # to make sure a human readable string is returned and not Object def __str__(self): return self.category_name class Project(models.Model): project_title = models.CharField(max_length=500, unique=True) slug = AutoSlugField(populate_from='project_title', always_update=True, max_length=500, unique=True) summary = … -
Data not getting replicated in my django master slave database architecture
I have been working on setting up multiple databases for a django project. I have one master database and four slave. I want to replicate data saved on master(which is my write database) to all my slaves, from where i read my data. But my data is not replicating in my slaves after I save it is getting written in master which is correct but if it does not update on slaves well then I will be reading empty data always. I fixed this by overriding save method, But I don't It is correct or not. Also please go through my settings and routing code below and suggest the better way if any to do replicate data into readonly slaves. and what to do if master goes down due to some reason. Overriding save class MultiDbModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): for dbname in settings.DATABASES: super(MultiDbModel, self).save(using=dbname) Below are my settings and database router. Settings DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'USER': '---', 'NAME': 'main_db', 'HOST': 'localhost', 'PORT': '', 'PASSWORD': '---' }, 'slave_1': { 'ENGINE': 'sql_server.pyodbc', 'USER': '---', 'NAME': 'slave_1', 'HOST': 'localhost', 'PORT': '', 'PASSWORD': '---' }, 'slave_2': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'slave_2', 'USER': '---', …