Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to update model field from QueryDict
I am a newbie in Django, maybe this will be a very simple question that I am not get the answer up until today. Straight to my problems. I have a submitted form and generated this: <QueryDict: {'csrfmiddlewaretoken': ['bla bla bla'], 'id_number': ['1', '5', '17'], 'Status': ['Registered', 'Pending', 'Confirmed']}> I want to update my model field after the admin click on Update button something like this: id# 1 --> Status change to Registered id# 5 --> Status change to Pending id# 17 --> Status change to Confirmed Very appreciate for the help... -
django.db.utils.OperationalError: no such table: theblog_category
I wanted to add tags to my blog in the same way as a category, unfortunately during "makemigrations" I got an error: "django.db.utils.OperationalError: no such table: theblog_tag" Then I tried every way I found, removed the migrations (except init.py) and db.sqlite3 and tried to do the migrations again. Unfortunately for now, the bug also affects the categories. Here is traceback: Traceback (most recent call last): File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\plantblog\virt\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: theblog_category The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\plantblog\blogplant\manage.py", line 22, in <module> main() File "C:\plantblog\blogplant\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\plantblog\virt\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\plantblog\virt\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\plantblog\virt\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\plantblog\virt\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\plantblog\virt\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\plantblog\virt\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\plantblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res … -
want help on writing .circleci/config.yml file
I am going through a tutorial. In that tutorial I learn how to CI in Travis-CI. But as I am learner I am not able to find a way to write the same configure file in circleci. please help. .travis.yml to .circleci/config.yml Dockerfile FROM python:3.8-alpine ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user docker-compose.yml version: "3.9" services: app: build: context: . ports: - "8000-8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" .travis.yml language: python python: "3.8" services: docker before_script: pip install docker-compose script: docker-compose run app sh -c "python manage.py test && flake8" -
How to pip install django-auth-ldap on a Mac
I want to implement ldap for active directory auth in my Django app. The development is taken place on a Mac. After I ran pip install django-auth-ldap I got a bunch of errors. The reason might be, because I have no OpenLDAP libraries and headers installed. But how do I do it on a Mac? Appreciate any help. -
Django poor request response performance when using threads
I'm trying to optimize the response time on a specific endpoint so I try using vanilla threads to make things on parallel. The problem is that the performance does not seems to improve and actually removing the threads from the view is giving me half of the time, when it should be running in parallel. Here is some example: def myView(): do_a() return Response("ok") def myView(): do_a() thread = Thread(target=do_b) thread.start() return Response("ok") myView without the thread is taking 30ms when the view with the thread that should be running do_b in paralle is actually taking 60ms. I'm using django, django-restframework and mongodb when using the do_b thread (with djongo interface) What's my problem here? -
Javascript url refresh page not found in Django
I am getting page not found error when refresh the page. Page url is set through javascript and render through Django. Please help what's the issue? and how to solve this? urls.py urlpatterns = [ path('',views.index,name='index'), path('section/<int:num>',views.section,name='section') ] Javascript code function ShowSection(section){ fetch(`/section/${section}`) .then(response => response.text()) .then(text => { console.log(text); document.querySelector('#content').innerHTML = text; }); } document.addEventListener('DOMContentLoaded', function () { document.querySelectorAll('button').forEach(button => { button.onclick = function () { const section = this.dataset.section; history.pushState({section: section},'',`section${section}`); ShowSection(section); }; }); }); -
Central align field using FormHelper
I try put form field in central with some size of this field, but I have problem. It's look like on the screen. https://pastebin.com/fa8DLq1y class Test(forms.ModelForm): pole1 = forms.CharField() class Meta: model = User fields = ('pole1',) # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) helper = FormHelper() helper.form_class = 'form-horizontal col-md-6 m-auto' helper.field_class = '' helper.label_class = '' helper.layout = Layout( Row( Column( # Field('pole1', style='margin-left:200px'), Field('pole1', css_class='form-group m-auto'), ) ) ) -
Javascript in Django child HTML template not working
I am tried incorporating this onload Javascript effect but the effect is not happening. Here is my example.html: {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-2 left top"> <div class="card-body"> <div id="div1" style="margin:0px;width:100px;background:#666;border:1px solid black;position:relative;" >Waka Waka</div> {% block extra_js %} <script> $(document).ready(function() { $("#div1").effect("highlight", {}, 3000); //this will highlight on load $("#div1").click(function () { $(this).effect("highlight", {}, 3000); }); }); </script> {% endblock extra_js %} <!-- div { margin: 0px; width: 100px; background: #666; border: 1px solid black; position: relative; }--> <!-- <p class=" text-muted">{{ object.author }} | {{ object.created_on }}</p>--> <!-- <p class="card-text ">{{ object.content | safe }}</p>--> </div> </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %} </div> </div> {% endblock content %} And here is my base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} {% endblock %}</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <!-- For accordions --> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <link rel="stylesheet" href="{% static 'css/highlight.min.css' %}"> <link ref="stylesheet" href="{% static 'ajax-live-search/css/ajaxlivesearch.min.css' %}"> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> <script src="{% static 'ajax-live-search/js/ajaxlivesearch.js'%}"></script> <script src="{% static … -
Python WebAuthn: Unable to verify attestation statement format
I have implemented some sort of password-less authentication using DUO lab's webauthn using Django. However, I keep getting this error: Unable to verify attestation statement format.. when authenticating on my Android phone (at least for now). How can I include more attestation formats to incorporate Android, Windows hello and any other device in this library's attestation formats? -
How would I convert this datetime format into a DateTimeField using datetime.strptime()?
I have a list of strings formatted as follows: 10:00am - Tuesday, March 16, 2021' I have been messing around with datetime.strptime() and am not sure how to convert this correctly since it includes the name of the day of the week as well as the actual date. -
Based on user input generate a formset in django
Let's say, I have a dropdown as an input with the following options. Video games Food Sports By default, I display the Sports formset table which is a DB table that displays Sports info. When I select Video Games and submit a post request it should display the Video Games formset table. I initialize the formset if there's a post request: if request.method == 'POST': formset = display_formset(request.POST, form_kwargs=create_forms, initial=initial_values) if formset.is_valid(): for form in formset: print(form.cleaned_data) return HttpResponseRedirect("/home/") else: print('not valid') else: formset = display_formset(form_kwargs=create_forms, initial=initial_values) The issue I am facing: When I submit 'Video Games' the formset table displays the correct columns for the 'Video Games' formset table, but no data is being populated. It looks like the previous submitted 'Sports' data is getting passed into the request.POST argument in the formset That is why all the forms are empty and no data is being populated What I tried: I removed the request.POST argument from the formset and on user input the tables were getting displayed and were populated with the correct data. However, the formset was returning invalid because no data was being sent to the formset on a post request. Although everything was working on the … -
Different results when accessing Django polymorphic model via query or ORM
I've been using Django's model polymorphism for a while now without a problem, but I've suddenly run into something that's making me question my basic understanding of how this works. Here's basically how I've got things set up. from django.db import models from polymorphic.models import PolymorphicModel class Data(PolymorphicModel): parent = models.ForeignKey('Data', null=True, blank=True, on_delete=models.CASCADE) class Listing(Data): name = models.CharField(max_length=128) def __str__(self): return '%s (%d)' % (self.name, self.id) class Qualification(Data): target_listing = models.ForeignKey(Listing, on_delete=models.SET_NULL, blank=True, null=True) class Job(models.Model): data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name="job_data") Long story short, Jobs can carry Data with them, which for now are of two types: Qualification and Listing. Qualifications themselves can point to a Listing. I suddenly noticed that in the admin site, a particular Qualification instance didn't have its target listing set, so I put in some print statements and discovered this. q = job.data print("job.data.id", job.data.id) // Yields 'job.data.id 20' print("q.id", q.id) // Yields 'q.id 20' print("job.data.target_listing", job.data.target_listing) // Yields 'job.data.target_listing myListing (12)' print("q.target_listing", q.target_listing) // Yields 'q.target_listing myListing (12)' qq = Qualification.objects.get(id=q.id) print("qq.target_listing", qq.target_listing) // Yields 'qq.target_listing None' !!!!! How can it be that I get different results when I access the apparently same data in different ways? Is my database corrupt or am … -
What things one should not store in cache? [closed]
Consider an Application like facebook, there is user data, timeline data, friends data etc. In such a backend application what things one should keep in mind while moving some data to cache. What principles you should know and follow while caching things. What things you should not cache. -
I Have created Custom User Model but i have "NO MODULE FOR managers.py"
I'm register my app in INSTALLED_APP but it showing no module that is "ModuleNotFoundError: No module named 'myapp.mangers' " help me!!!! 1.myapp/managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as lagy class UserManager(BaseUserManager): def create_user(self,email,password,**extra_fields): if not email: raise ValueError(lagy("Email Must ")) email =self.normalize_email(email) user=self.model(email=email,**extra_fields) user.set_password(password) user.save() return user def create_superuser(self,email,password,**extra_fields): extra_fields=setdefault('is_staff',True) extra_fields=setdefault('is_active',True) extra_fields=setdefault('is_superuser',True) if extra_fields.get('is_superuser') is not True: raise ValueError(lagy("must be is superuser")) if extra_fields.get('is_staff') is not True: raise ValueError(lagy('Must is_staff category')) return create_user(email,password,**extra_fields) 2.myapp/models.py from django.db import models from django.contrib.auth.models import AbstractUser, PermissionsMixin from django.utils.translation import ugettext_lazy as lagy from django.utils import timezone from .mangers import UserManager class UserModel(AbstractUser): username = None email = models.EmailField(lagy('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email Then Error is like: ModuleNotFoundError: No module named 'myapp.mangers' -
keyerror while migrating in python
i am trying to run but it is not working python manage.py migrate its showing error Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, signup Running migrations: Applying signup.0002_auto_20210511_2201...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\migration.py", line 116, in apply operation.state_forwards(self.app_label, project_state) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\operations\fields.py", line 92, in state_forwards state.models[app_label, self.model_name_lower].fields[self.name] = field KeyError: ('signup', 'students') what does keyerror mean. I have been trying to solve it. I tried deleting migrated files but after running makemigrations again it made no difference and said No changes detected -
Query @property values in ManyToMany relationships
I need to query certain fields in a ManyToMany relationship. Here is the setup; class Yacht(models.Model): name = models.CharField(max_length=50) multiplier = models.DecimalField(max_digits=5, decimal_places=3) def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=50) yachts = models.ManyToManyField(Yacht, through='Result') def __str__(self): return self.name class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) result = models.FloatField() @property def result_adjusted(self): # returns the adjusted result based on the yacht's multiplier return self.result * self.yacht.multiplier Question: How can I query the adjusted result for a given yacht in a given event? -
How do I access read and write access to the Django project database?
I want to read and write to the Django project database, but I don't know how to do it. A piece of code what I'm trying to do: def __init__(self): self.connection = sqlite3.connect(DB_PATH, password='1234') self.cursor = self.connection.cursor() Error: sqlite3.OperationalError: unable to open database file -
django admin new user registration fails
I have created a custom user model derieved from AbstractUser but for some reason when I am creating a new user from admin, it is failing. What could be the issue. models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.fields import CharField, BooleanField # Create your models here. class User(AbstractUser): email = models.CharField(unique=True,max_length=100) company = models.CharField(max_length=100) phone = models.CharField(max_length=10) emailVerified = models.BooleanField(default=False) phoneVerified = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','phone'] def __str__(self): return self.email forms.py from django import forms from .models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UserChangeForm class SignUpForm(UserCreationForm): email = forms.CharField(max_length=100,required=True) phone = forms.CharField(max_length=10,required=True) company = forms.CharField(max_length=100,required=True) class Meta(UserCreationForm.Meta): model = User fields = ('username','email','password1','password2','phone','company') class LoginForm(AuthenticationForm): email = forms.CharField(max_length=100,required=True) class Meta: model = User fields = ('email','password','username') class CustomChangeForm(UserChangeForm): email = forms.CharField(max_length=100,required=True) phone = forms.CharField(max_length=10,required=True,min_length=10) company = forms.CharField(max_length=100,required=True) class Meta(UserChangeForm.Meta): model = User fields = ('username','email','phone','company') admin.py from django.contrib import admin from .models import User from .forms import SignUpForm,CustomChangeForm from django.contrib.auth.admin import UserAdmin # Register your models here. class CustomUserAdmin(UserAdmin): add_form = SignUpForm form = CustomChangeForm model = User list_display = ['email', 'username','phone','company','emailVerified','phoneVerified'] fieldsets = UserAdmin.fieldsets +( ('Additional info', {'fields': ('phone', 'company','emailVerified','phoneVerified')}), ) #this will allow to change these fields in admin module … -
Django - How to access a python global variable in multiple pages?
In one of my Django application, I use a python global variable in a Django page (page One), as follows: global abc abc = test Now what I want is, I want to access that variable from another page (page Two). How can I access that? -
Difficulty Calculating Interest in django
I have asked this questions two times before and I didn't receive a good answer. Am putting the question forward again and I hope to get help this time. I want to calculate 8 percent of the amount in investment model in every 10 days. When the user deposit with any amount 8 percent of the amount deposited will be calculated and added to the user balance in every 10 days and it will continue to roll over every ten days continually. Look at my code below and help me. Models.py class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) added = models.DateTime() def percentages_in_ten_days(self): return self.amount *0.08 I want to fetch the percentage of the user investment amount here Views.py def get_percentage(self, day=10): pef_of_amount = Investment.objects.filter([x for for x in get_percentage_ten_days]).annotate(day=Sum('x')) return get_percentage def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance Can someone help me retrieve 8 percent of the amount and … -
Add new field and value to the request - Django - Django Rest Framework (viewset, serializer)
i have a endpoint in django-rest-framework and receive a object name and date. I need include user (fk_model_user) in object before save my database, how save or update including new item in body request? Viewset: class MusicStylesViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.AllowAny] queryset = MusicStyleModel.objects.all() serializer_class = StyleSerializer Serializer: class StyleSerializer(ModelSerializer): class Meta: model = MusicStyleModel fields = ('id', 'name', 'date', 'user') Model: class MusicStyleModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) name = models.CharField(max_length=150, null=False, blank=False) date = models.DateTimeField(null=False, blank=False) user = models.ForeignKey( CustomUser, null=True, blank=False, on_delete=models.CASCADE ) Example - Post Request: { "name": "test", "date": "2021-05-14T15:47:06.794639-03:00" } Example - Post Response: { "id": "810ae929-2f6d-411a-8d10-77c8f613a8ac", "name": "test", "date": "2021-05-14T15:47:06.794639-03:00", "user": "c6fbbfee-2f16-49f3-b4cd-b99e05a66ea8" } "id": "810ae929-2f6d-411a-8d10-77c8f613a8ac", automatically generated in the model "user": "c6fbbfee-2f16-49f3-b4cd-b99e05a66ea8" user id request intercepted, and save -
Struggling with queries through Django M2M field
I have these models, with a M2M field from WordCloud to Source through WordCloudSouce class Source(Model): source_id = models.AutoField(primary_key=True) source_name = models.CharField(max_length=64, default="foobar") class WordCloud(Model): cloud_id = models.AutoField(primary_key=True) cloud_name = models.CharField(max_length=125, unique=True) sources = models.ManyToManyField(Source, related_name="sources", through='WordCloudSource') class WordCloudSource(Model): wordcloud_sources_id = models.AutoField(primary_key=True) wordcloud = models.ForeignKey(WordCloud, on_delete=models.CASCADE) source = models.ForeignKey(Source, on_delete=models.CASCADE) I want to construct a query that finds a wordcloud that has cloud_name='frank' and sources as a list of strings (e.g ['a', 'b'] or ['a']). I am looking for something like: WordCloud.objects.filter(cloud_name='frank', sources=['a', 'b']) but I am unclear how to write a query that traverses the sources M2M field to get a list of the associated sources for a wordcloud. I have read through the Django docs for 3.0, and it still is not making any sense to me. I got as far as WordCloud.objects.filter(cloud_name='frank', sources__source_name__in=['aa', 'bb']) But it is not correct as it returns wordclouds named frank with both sources=['aa'] and sources=['aa', 'bb'], which is not what I want. Thanks! -
How do i append an array of objects inside an array of objects
@require_http_methods(["GET"]) @login_required def get_questions(request): res = {} questions = models.Questions.objects.raw( """ SELECT SELECT Q.question_id,Q.question,Q.description,Q.qn_total_mark,QP.part_desc, QP.part_total_marks, PMA.part_model_ans,PMA.part_answer_mark,PMA.part_answer_id FROM "QUESTIONS" Q LEFT JOIN "QUESTIONS_PART" QP ON QP.question_id = Q.question_id LEFT join "PART_MODEL_ANSWER" PMA ON PMA.part_id = QP.part_id """ ) for question in questions: if question.question_id not in res: res[question.question_id] = { "key": question.question_id, "question": question.question, "description": question.description, "qn_total_mark": question.qn_total_mark, "question_parts": [ { "part_desc": question.part_desc, "part_model_ans": question.part_model_ans, "part_guided_answer":[ { "part_answer_id":question.part_answer_id, "part_model_ans": question.part_model_ans, "part_answer_mark": question.part_answer_mark, } ], "part_total_marks": question.part_total_marks, } ] } else: res[question.question_id]["question_parts"].append( { "part_desc": question.part_desc, "part_model_ans": question.part_model_ans, #part guided answer is appended in here i think "part_total_marks": question.part_total_marks, } ) return success({"res": list(res.values())}) What am i trying to do is to append the array of part_guided_answer inside question parts for use but i do not think this is a good idea, is it possible to do it like this and if so how could it be done? Also is there a better alternative for it -
Django: Exclude apps from python manage.py migrate when using multiple databases
QUESTION : How to exclude the logs migrations from the default database, when using multiple databases in Django I've found that I need to remove the app from the INSTALLED_APP. Can this be done dynamically, or is there another way to achieve this ? I am using the default database for all models in my application and I need new database Logs, for only one model (the model is in different app - logs) I successfully connected the application with the both databases. Also I am using a Router to control the operations class LogRouter: route_app_labels = {'logs'} def db_for_read(self, model, **hints): ... def db_for_write(self, model, **hints): ... def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the logs app only appear in the 'logs' database. """ if app_label in self.route_app_labels: return db == 'logs' if db != 'default': """ If the database is not default, do not apply the migrations to the other database. """ return False return None With allow_migrate I am faking the logs migrations in the default database which is updating the table django_migrations with the logs migration. Also with if db != 'default': """ If the database is not default, do not apply the migrations … -
Rest Framework - Many 2 Many relation, include through model fields in API
I have 2 models connected via M2M model: class Person(models.Model): name = models.CharField(max_length=30) class Group(models.Model): name = models.CharField(max_length=100) members = models.ManyToManyField(Person, through='GroupPerson', related_name='groups') class GroupPerson(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) rank = models.CharField(max_length=100', default='New') and serializers class GroupPersonSerializer(serializers.ModelSerializer): class Meta: model = GroupPerson fields = '__all__' class GroupSerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField(many=True, queryset=Person.objects.all()) class Meta: model = Group fields = '__all__' class PersonSerializer(serializers.ModelSerializer): groups = serializers.PrimaryKeyRelatedField(many=True, queryset=Group.objects.all()) class Meta: model = Person fields = '__all__' And API go get a group returns [ { "name": "...", "members": [ IDs of all members ] } ] How do I get a response something like following: [ { "name": "...", "members": [ { "group_id": 1, "person_id": 1, "rank": "New" }] } ] I.e., I want to GET/POST/PATCH all fields of the through relation