Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Arrayfiled: Annotate queryset with the first item in the arryafield
I have a model that can be represented by something like this. class BackPack(models.Model): person = models.ForeignKey(Person, db_index=True, related_name='back_packs', on_delete=models.CASCADE) candy = ArrayField(models.CharField(max_length=203, null=True)) I want to build a queryset that is all back packs associated with one person and then annotated with the first item in the candy arrayfield. I tried the following; first_candy = BackPack.objects.filter(person__id=200)\ .annotate(first_candy=F('candy__0')) first_candy = BackPack.objects.filter(person__id=200)\ .annotate(first_candy=ExpressionWrapper(F('candy__0'), output_field=CharField())) The output for first_candy includes every item in the arrayfield not just the first one. Any help for the correct way of doing this is much appreciated. -
Redirect user for his first connexion
I want new users to be redirected to a specific web page only when it's their first connexion ever. I looked up online and on SO, but could not find anything. Is there any easy way to do it with django ? -
which directory is unsafe for deployment?
I'm going to deploy a Django web-application, with Nginx as the web server And I wanna deploy it on /opt/ directory. My question is: Does it matter which directory I'm going to upload my application? And are there any security issues for deploying in some specific directories? -
Django - How can I copy fields in same class
I will create some texts with organize that by "subjects" and "school_classes". Initially the "school_class" name will be the same as the "subject" name. So, when I create a text I need that field "subject" was be auto-filled with the field information of "school_class". This is to make it easier and not to err the subject as I already have the text ready and will just copy and paste it. Like a auto copy only when I create the texts, because I will change the "school_class" name in the future. Look to my models.py I try it: from django.db import models class Texts(models.Model): school_class = models.ForeignKey(School_class, on_delete=models.DO_NOTHING) subject = models.CharField(max_length=200, blank=True) body = models.CharField(max_length=200, null=True, blank=True) def statement(self): return self.collection def __str__(self): return self.subject The problem is that when I change the information in "school_class", automatically change in the "subject". Why I need this? In the future I will modify the "school_class" name of all my texts but I want the "subject" to remain the original when it was created. How to do this? -
django-session-timeout: how to disconnect automatically (without user action)
I am newbie in Django and try to implement 'autologout' using a tierce app django-session-timeout It works but I would like to improve behavior the session expire after time set in settings.py but there is no refresh so that it is disconnect and redirect to login page except if user click elsewhere in other word, the user is disconnect (as user session expire) but not automatically redirect to login page -> need a user event is it possible to improve this without writing my own middleware? settings.py 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', 'django_session_timeout.middleware.SessionTimeoutMiddleware', ] LOGIN_URL = 'home' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SESSION_EXPIRE_SECONDS = 900 # 900 - >15 minutes = 15 * 60 SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True -
Celery's pytest fixtures (celery_worker and celery_app) does not work
I'm trying to write a Celery(v. 4.2.1) integration test for my Django(v. 2.2.3) application. There is a bunch of outdated articles about this around, but non of them seem to use stuff from the latest celery testing documentation - https://docs.celeryproject.org/en/v4.2.1/userguide/testing.html#fixtures Seems like Celery comes with two fixtures for testing: celery_app and celery_worker which should allow to actually run worker in the background thread of your tests. As the doc's say I've added @pytest.fixture(scope='session') def celery_config(): return { 'broker_url': 'memory://', 'result_backend': 'rpc' } into my conftest.py I've wrapped my test function with @pytest.mark.celery_app @pytest.mark.celery_worker usually I wrap my celery tasks with from celery import shared_task @shared_task def blabla(...): pass but I've even tried to replace it with from myapp.celery import celery @celery.task def blabla(): pass What else... I run my celery task via apply_async providing eta argument. Tried tons of ways but the celery fixtures do not affect how things work and the task call goes to actual redis instance and is picked by a worker in a separate process (if I run it) and hence my assert_called fails along with my efforts to access the object which are in the testing database. -
Is it possible to initiate daily tasks using django-background-tasks when running using the same codebase scaled across multiple nodes(pods)?
The django extension is a great utility but I am concerned about scaleability. I have a django server running across three different nodes (pods). I have a task that has to run at a given time every day. This is triggered by the same codebase. Does this mean all 3 of my nodes are going to add the same daily task to the queue and it’ll be executed thrice then? -
Django: 'RegisterEmployeeView' object has no attribute 'object'
Am developing using django and i get AttributeError at /employee/register upon executing my runserver. this is the code in my views.py class RegisterEmployerView(CreateView): model = User form_class = EmployerRegistrationForm template_name = 'accounts/employer/register.html' success_url = '/' extra_context = { 'title': 'Register' } def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: return HttpResponseRedirect(self.get_success_url()) return super().dispatch(self.request, *args, **kwargs) def post(self, request, *args, **kwargs): form = self.form_class(data=request.POST) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password1") user.set_password(password) user.save() return redirect('accounts:login') else: return render(request, 'accounts/employer/register.html', {'form': form}) -
Unable to access instance variable by name in Django model
I am trying to save the value of a field in an instance variable on my Video model and then use this instance variable in a post_save signal receiver to see if the value of the field has changed. I am going off of this Stack Overflow answer: https://stackoverflow.com/a/36722021/ Here is my Video model: class Video(models.Model): approval = models.BooleanField(default=True) def __init__(self, *args, **kwargs): super(Video, self).__init__(*args, **kwargs) self.__original_approval = self.approval Here is my post_save signal receiver: @receiver(post_save, sender=Video) def handle_video_save(sender, **kwargs): video = kwargs.get('instance') previous_approval = video.__original_approval # check if value has changed... This is the error I'm getting: AttributeError: 'Video' object has no attribute '__original_approval' While debugging, I have found that the instance variable can be accessed this way in my post_save signal receiver: previous_approval = video._Video__original_approval So, using video._Video__original_approval works, but I'm wondering why am I unable to access the instance variable, as I've seen in other answers on Stack Overflow, with video.__original_approval? I'm using Django 1.11.20 and Python 3.6.6. -
'NoneType' object is not iterable in Django project
I am getting "'NoneType' object is not iterable" error while I try to run my django app using " python manage.py runserver ip:port" whereas the same error does not occur if I use " python manage.py runserver 0.0.0.0:8000". I really need to get this work using my ip address. Link to the error page. What am I doing wrong? This is how my settings.py looks like: """ Django settings for SimStudent project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #ALLOWED_HOSTS = ['0.0.0.0', '10.153.1.51', '127.0.0.1'] ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'channels', 'chat', 'django_tables2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'SimStudent' ] 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 = 'SimStudent.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Django object query filter with multiple conditions
I'm trying to filter my model of travels by applying date and place condition but I can't have it in one query. schematic model class Travel(models.Model): code = models.CharField(max_length=10) company = models.ForeignKey('Company', on_delete=models.CASCADE) bus = models.ForeignKey('Bus', models.SET_NULL, blank=True, null=True,) class Stop(models.Model): travel = models.ForeignKey('Travel', on_delete=models.CASCADE) terminal = models.ForeignKey('Terminal', on_delete=models.CASCADE) arrival_datetime = models.DateTimeField() stay_duration = models.TimeField(default='00:30:00') order = models.IntegerField(verbose_name="Stop order", default=0) # Represent the order in which the bus will pass the stops class Terminal(models.Model): name = models.CharField(max_length=200) address = models.CharField(blank=True, max_length=200) city = models.ForeignKey('city', on_delete=models.CASCADE) class City(models.Model): name = models.CharField(max_length=100) This query should show the available travels depending from the origin and destination and date input by a personn. A travel can have many stops(including origin and destination) related to a terminal. To find out the order of this stops , the field order contains for each stop of a travel a number greater than the ones before. So one condition is to have the couple of {departure;origine} that has the right order. So at result, I should have a list of travels corresponding only to my origin, destination and date. -
Django CASCADE and post_delete interaction
I have the following model: class A(): foriegn_id1 = models.CharField # ref to a database not managed by django foriegn_id2 = models.CharField class B(): a = models.OneToOneField(A, on_delete=models.CASCADE) So I want A to be deleted as well when B is deleted: @receiver(post_delete, sender=B) def post_delete_b(sender, instance, *args, **kwargs): if instance.a: instance.a.delete() And on the deletion of A, I want to delete the objects from the unmanaged databases: @receiver(post_delete, sender=A) def post_delete_b(sender, instance, *args, **kwargs): if instance.foriegn_id1: delete_foriegn_obj_1(instance.foriegn_id1) if instance.foriegn_id2: delete_foriegn_obj_2(instance.foriegn_id2) Now, if I delete object B, it works fine. But if I delete obj A, then obj B is deleted by cascade, and then it emits a post_delete signal, which triggers the deletion of A again. Django knows how to manage that on his end, so it works fine until it reaches delete_foriegn_obj, which is then called twice and returns a failure on the second attempt. I thought about validating that the object exists in delete_foriegn_obj, but it adds 3 more calls to the DB. So the question is: is there a way to know during post_delete_b that object a has been deleted? Both instance.a and A.objects.get(id=instance.a.id) return the object (I guess Django caches the DB update until it finishes … -
Difference between auto_now_add and timezone.now as default value
What is the difference between auto_now_add and timezone.now (as default value) for models in Django? Example: create_date = models.DateTimeField(auto_now_add=True) and create_date = models.DateTimeField(default=timezone.now) ? -
How to change React frontend and Django backend to load as one Heroku application
I've built a React frontend in the style of this tutorial: https://codeburst.io/react-image-upload-with-kittens-cc96430eaece (source code here) This is connected to a Django backend (already had experience with Django, so don't have an example tutorial there). Running the frontend and backend locally works fine. Now I want to deploy it as one application to Heroku, so I followed this tutorial about how to do this: https://www.youtube.com/watch?v=r0ECufCyyyw (source code here) I configured the Django application exactly like in the video tutorial. The application builds successfully but the page is empty. I think it might be because I didn't use routers in the React application, but I don't know what exactly it's supposed to do so that the code in App.js gets called. Any suggestions greatly appreciated - I'm not sure where to start and I've found so many ways to write a React app I'm having trouble separating important differences from the inessential. -
how to get column names from a Django object list
I'm trying to generate some tables based on Django models to make them modifiable and alter the database, and since i have more than 200 tables i'm trying to generate them automatically instead of hardcoding each one. in this example i'm trying to get the table columns in django template so i can generate the table with for loops only. here is my views.py class bclist(ListView): template_name = "table2.html" queryset = BaseCase.objects.all() and here is my template <table border="1px"> <tr> <th>Base Case Name</th> <th>version</th> <th>default</th> </tr> {% for instance in object_list %} <tr> <td>{{ instance.base_case_name }}</td> <td>{{ instance.version }}</td> <td>{{ instance.default }}</td> <td><a href='/{{ instance.pk }}/update' >edit</a></td> <td><a href='/{{ instance.pk }}/delete' >delete</a></td> </tr>{% endfor %} </table> my models.py class BaseCase(models.Model): base_case_name = models.CharField(primary_key=True, max_length=255) version = models.TextField(blank=True, null=True) default = models.IntegerField(blank=True, null=True) -
Using google-search package in Django
Iam trying to make the google-search package work in my Vagrant virtualenv, which runs my Django app. When the package is installed directly in the machine the methods in the package are listed properly when i list them using dir command: FDLMC1716:python prasannab$ python3.6 Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import googlesearch >>> dir(googlesearch) ['BeautifulSoup', 'LWPCookieJar', 'Request', 'USER_AGENT', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'cookie_jar', 'filter_result', 'get_page', 'get_random_user_agent', 'gzip', 'hits', 'home_folder', 'install_folder', 'is_bs4', 'lucky', 'math', 'ngd', 'os', 'parse_qs', 'quote_plus', 'random', 'search', 'search_apps', 'search_books', 'search_images', 'search_news', 'search_shop', 'search_videos', 'sys', 'time', 'url_home', 'url_next_page', 'url_next_page_num', 'url_search', 'url_search_num', 'urlopen', 'urlparse', 'user_agents_file', 'user_agents_list'] >>> I installed the same package in virtualenv all the methods in the package are not listed when i list them using dir command: (success) vagrant@ubuntu-xenial:/vagrant/src/success_project$ python3 Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import googlesearch >>> dir(googlesearch) ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__'] >>> Any thoughts on why this is happening ? -
Django models: where should consistency/integrity of databases stay?
Here again, I’m trying to understand Django philosophy for databases. When dealing about consistency in databases, I understand (or understood?) that it refers to constraints, cascades, triggers, etc. at database level, hence a solid database diagram is (or was) very important. But I don’t feel that with Django, it seems that its philosophy is to bring all that consistency to every app in a Django project, and to leave database with relations only. Because when migrating from models to database, not all rules defined in models are taken to database, example: validators. For a moment, let's accept that all business rules are defined in models only. I could (hardly) accept that if it was not because while I was using the database API, no rule (defined in models) applied on every record saved into database, then danger alarms sounded. Here the dilemma: If consistency and/or business rules were defined at database level, why would I need define rules in models again? is it not redundant? If consistency and/or business rules were defined in models, is the database not exposed to concurrency and data integrity problems? In PHP, you interact with database through connectors, consistency/integrity of database is managed by itself. … -
Runtime error when trying to run a Django app
I'm trying to run a django project I worked on a while ago. Most of what I did I've forgotten. I get a run time error when launching the project. I only just imported these files over to my computer. I'm wondering if i'm missing any dependencies? It's been a very long time since I've programmed in django or python. Any help you can offer would be greatly appreciated. C:\Users\Shadow\Desktop\django_project>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named … -
Using models at a project level
I know that this question has been posted a few times in different variations but I'm not satisfied with the answers I found so I will explain you my problem, which I think will be easily solved by someone used to Django. So, I'm a beginner with Django and my problem is that I'm building a food delivery website and I have lots of models such as User, Meal, Order, ... that will be used in all the applications of my project. But, from my very little experience with Django, I understand that the models are defined at an app level, not at a project level. How can I deal with that ? I tried defining some models in an app and importing them in the other apps but I doesn't work : for example, I defined my Client model in the registering app, and my Order model in the ordering app. But when I write "from registering.models import Client" in the Order.models file in order to have a foreign key between Order and Client I have an error saying that it can't find a model Client in the ordering app. I believe there is some way to define the … -
Django migrating foreign keys django.db.utils.OperationalError: (1005, "Can't create table 'asp052mysqlpy.#sql-6ac_56' (errno: 150)") error
I'm trying to migrate a simple foreign key relation for a model in Django, but this results in a very strange and unsolvable error. Error: python manage.py migrate team Operations to perform: Apply all migrations: team Running migrations: Applying team.0001_initial... OK Applying team.0002_auto_20191127_1643...Traceback (most recent call last): File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute return self.cursor.execute(query, args) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\cursors.py", line 255, in execute self.errorhandler(self, exc, value) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\cursors.py", line 252, in execute res = self._query(query) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\cursors.py", line 378, in _query db.query(q) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\connections.py", line 280, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1005, "Can't create table 'asp052mysqlpy.#sql-6ac_56' (errno: 150)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\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 … -
Datetimepicker in django changing date format from DD/MM/YYYY to MM/DD/YYYY when the forms comes pre-filled
when i want to update a Date in any form, the datepicker is changing from DD/MM/YYYY format to MM/DD/YYYY. When I print the date in the template is in the correct format, but in the Datetimepicker it change. When the date becomes invalid eg: 27/11/2019 to 11/27/2019,the datepicker shows nothing. Here is the code where i configure the datetimepicker for the forms: def __init__(self, *args, **kwargs): super(BaseModelForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): attrs = field.widget.attrs if isinstance(field.widget, forms.widgets.DateInput): attrs['class'] = 'datetimepicker-input form-control' attrs['data-format'] = 'DD/MM/YYYY' attrs['data-toggle'] = 'datetimepicker' attrs['autocomplete'] = 'off' What could be? -
How can I handle multiple forms in generic view?
I want to handle 3 different forms in one UpdateView and I have method post where I choose which form will be in form_class. First 2 of them are depending on if checkbox is selected. Third form is seperated. class MyUpdateView(UpdateView): model = MyModel form_class = Form1 def post(self, *args, **kwargs): is_cyclic = self.request.POST.get('is_cyclic', None) if 'form1' in self.request.POST and not is_cyclic: self.form_class = Form1 elif 'form1' in self.request.POST and is_cyclic: self.form_class = CyclicForm1 elif 'form2' in self.request.POST: self.form_class = Form2 return super().post(*args, **kwargs) In template: <form id="form1" method="post" class="container" action=""> <input type="checkbox" name="is_cyclic" id="cyclic_switch" checked> ... <button type="submit" name="update_form1" value="form1">Save</button> </form> <form name="form2" id="form2-id" method="post" action=""> ... <button form="form2-id" type="submit" name="update_form2" value="form2">Save changes</button> </form> When I'm submitting Form2, I get Form1. How can I fix that? -
List names of required fields in Django Rest Framework serializer (and ignore parent fields)
What I'm trying to do is get a list of all the fields in a serializer which: Do not contain required=False as a parameter. Do not come from the parent serializer. For example, if I have serializers like: class ParentSerializer(serializers.Serializer): parent_field = serializers.IntegerField class ChildSerializer(ParentSerializer): child_field_required = serializers.IntegerField child_field_not_required = serializers.IntegerField(required=False) I'd like the resulting output to be: ['child_field_required'] I've figured out I can get an ordered list of the declared fields like: self.get_serializer().get_fields() >> OrderedDict([ ('parent_field', IntegerField()), ('child_field_required', IntegerField()), ('child_field_not_required', IntegerField(required=False)), ]) But I haven't been able to move past this step. -
Django - ERR_TOO_MANY_REDIRECTS
I have an accounts app with a UserProfile Model in it, that looks like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE) def get_absolute_url(self): return reverse('profiles:help', kwargs={'pk': self.pk}) accounts / urls.py url(r'^(?P<pk>\d+)/help/$', HelpToggle.as_view(),name="help"), accounts / views.py class HelpToggle(RedirectView): def get_redirect_url(self, pk, *args, **kwargs): url_ = obj.get_absolute_url() return url_ django_project / urls.py url(r'^accounts/',include(('accounts.urls','profiles'),namespace='profiles')), but when I go to /accounts/1/help I get a ERR_TOO_MANY_REDIRECTS Error. Thank you for any suggestion -
django.db.utils.IntegrityError while writing APITestCase for my views?
Here I am writing test cases for my views but the test is failing with the following error. django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint DETAIL: Failing row contains (31, permission_name_1, null, perms1). I am writing my own Role model since I needed to change the default ManyToMany relation of Group and User model . class CreateRoleTest(APITestCase): def setUp(self): self.user = User.objects.create_user(username='username',password='passwprd@321',email='email@gmail.com') self.permission = Permission.objects.create(name='permission_name',codename='perms') self.client = APIClient() def test_create(self): url = reverse('roles:create_role') data = {'user':self.user,'permissions':[self.permission.pk],'name':'role_name'} response = self.client.post(url,data,format='json') print(response.json()) return self.assertEqual(response.status_code,status.HTTP_201_CREATED) class UpdateDeleteRoleTest(APITestCase): def setUp(self) -> None: self.client = APIClient() self.user = User.objects.create_user(username='username1', password='passwprd@3211', email='email@gmail.com1') self.permission = Permission.objects.create(name='permission_name_1', codename='perms1') self.role = Role.objects.create(name='role1',user=self.user,permissions=[self.permission.pk]) def test_update(self): data = {'user':self.user,'permissions':[self.permission.pk],'name':'role_name2'} url = reverse('roles:update_role',kwargs={'pk':self.role.pk}) response = self.client.put(url,data,format='json') print(response.json()) return self.assertEqual(response.status_code,status.HTTP_200_OK) models.py class Role(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=255) permissions = models.ManyToManyField(Permission) created = models.DateTimeField(auto_now_add=True) views.py class CreateRole(CreateAPIView): serializer_class = RoleSerializer queryset = Role.objects.all() class UpdateRole(UpdateAPIView): serializer_class = RoleSerializer queryset = Role.objects.all() def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs)