Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run extra script before start Django server
I'm developing a Django app and the app heavily depends on a few environment variables. The problem is that the app is being developed by multiple developers and I want to make sure that each and every time a new developer git clone the app and set up the dev environment, his machine has all the required env variable before he could run python manage.py runserver. The check can be done by python and print out some warnings. Where should I insert this script? Thank you! -
Django - deterministic=True requires SQLite 3.8.3 or higher upon running python manage.py runserver
I am running a linux red hat environment from AWS. I have followed every instruction for upgrading sqlite3 to the "latest" version. I am running python 3.9.2 (and have recompiled it with LD_RUN_PATH=/usr/local/lib ./configure) and django version 4. I have set up a virtual environment to install and run django. I have changed the activate script to include export LD_LIBRARY_PATH="/usr/local/lib" Upon running python manage.py runserver, I get the error django.db.utils.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher. I have opened the file /home/ec2-user/django/django/db/backends/sqlite3/base.py (where the error occurs) and right after the line with the error have include a print statement: print("**************************\n" + str(Database.sqlite_version) + "\n" + str(Database.sqlite_version_info) + "\n**************************") which retruns: ************************** 3.28.0 (3, 28, 0) ************************** ************************** 3.28.0 (3, 28, 0) ************************** Please let me know what additional information is needed. I have searched up and down the stack and can't find the right solution to pop this one off. Thank you in advance! -
Django - Can I create a Serializer without connecting to a model?
From the book, I do this to create a Serializers class Serielizer_RecalculateDeliveryPromise(serializers.ModelSerializer): service_type = serializers.CharField(max_length = 10, write_only= True, required= True ) package_type = serializers.CharField(max_length = 68, write_only= True, required= True ) origin_handover_point = serializers.CharField(max_length = 68, write_only= True, required= True ) destination_handover_point = serializers.CharField(max_length = 68, write_only= True,required= True ) class Meta: model = Input_RecalculateDeliveryPromise fields = ['service_type', 'package_type', 'origin_handover_point', 'destination_handover_point'] class Input_RecalculateDeliveryPromise(models.Model): service_type = models.CharField(max_length = 10, db_index = True) package_type = models.CharField(max_length = 68, db_index = True) origin_handover_point = models.CharField(max_length = 68, db_index = True) destination_handover_point = models.CharField(max_length = 68, db_index = True) REQUIRED_FIELDS = ['service_type', 'package_type', 'origin_hp','destination_hp'] My personal purpose of Serializer is simply to check the input only. Therefore, I wonder if there is anyway that I could create a Serializer only without connecting to any model since it lengthen my code a lot. -
Script does not find Heroku env vars
I am trying to host a small webserver on heroku. I have set an env variable PRODUCTION = True on heroku. However, it does not seem to be found in my script. Locally, I use python-dotenv with an untracked .env file that does not exist in git #settings.py dotenv.load_dotenv() if os.getenv('PRODUCTION'): print("env found: prod") DJANGO_HOST = 'production' DEBUG = False elif os.getenv('DEVELOPMENT'): print("env found: dev") DJANGO_HOST = 'development' DEBUG = True else: print("could not find the right environment. Script will now exit for safety") exit() The heroku worker always executes the else statement here. -
Dramatiq Workers vs Lambda
I have a django app, which uses dramatiq workers to perform a task(updating database etc). I am thinking of shifting this tasks to lambda(and call lambda instead of assigning task to dramatiq). Will that be fine ? or Are there any drawbacks ? -
How to customize django-materializecss-form for DateTimeField in django?
I am trying to build a form using django-materializecss-form in django project. It works fine if I use DateField() for any model field instead of DateTimeField(). When I used DateTimeField(), the label and input is overlapping each other and datepicker is not showing/visible.I added these lines in settings.py file but still it is not working. from django.conf.global_settings import DATETIME_INPUT_FORMATS # ISO 8601 datetime format to accept html5 datetime input values DATETIME_INPUT_FORMATS += ["%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M"] models.py: class Preference(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) bio = models.TextField() songs = models.ManyToManyField(Song, related_name='songs') created_date = models.DateField() submit_date = models.DateTimeField(null=True,blank=True) active = models.BooleanField(default=True) def __str__(self): return f"{self.user.username}-{self.active}" main.html: <form method="POST"> {% csrf_token %} {{ form|materializecss }} <br> <button type="submit" class="waves-effect waves light btn-large" name="button">Submit</button> </form> <script> $(document).ready(function(){ // Initialize materialize data picker $('.datepicker').datepicker({'format': 'yyyy-mm-dd'}); $('select').formSelect(); }); // </script> Can anybody suggests how to customize this for DateTimeField to work properly? -
simple django channels app not running with daphne
I’m trying to get django channels running with daphne but I always end up with this x8/backback/mysite » daphne mysite.asgi:application 1 ↵ Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/daphne/cli.py", line 170, in entrypoint cls().run(sys.argv[1:]) File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/daphne/cli.py", line 232, in run application = import_by_path(args.application) File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/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 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./mysite/asgi.py", line 11, in <module> from channels.auth import AuthMiddlewareStack File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/channels/auth.py", line 12, in <module> from django.contrib.auth.models import AnonymousUser File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Users/me/.local/share/virtualenvs/backback-jdouan2y/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either … -
django.db.utils.ProgrammingError: relation "company_company" does not exist when running makemigrations
I have a Django app but when I try to run makemigrations get an error: File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "company_company" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "company_company" ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\management\_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\management\_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\utils\functional.py", line 48, in _get_ res = instance._dict_[self.name] = self.func(instance) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\utils\functional.py", line 48, in _get_ res = instance._dict_[self.name] = self.func(instance) File "C:\Users\EDUARDO\Desktop\ProyectoSoft\smarthbatch\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\EDUARDO\AppData\Local\Programs\Python\Python37\lib\importlib\_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File … -
Multiple Bootstap touchspon or bootstrap-input-spinner
I am using the input spinner example from below: https://shaack.com/projekte/bootstrap-input-spinner/ I need to have multiple spinners for every product. Do I need a separate function for detecting value/change for every instance of the spinner since the function operates on the id of the spinner. $inputNet.on("change", function (event) { $inputGross.val($inputNet.val() * 1.19) }) $inputGross.on("change", function (event) { $inputNet.val($inputGross.val() / 1.19) }) Do I need to dynamically generate the JavaScript function as well for every input-select? -
How do I manipulate string in HTML?
The situation is that I'm getting the time series data from django's sqlite. Originally, the date format is like ( Dec. 14. 2020. 2 p.m. ). And I converted this format to (2020, 12, 14, 2). Using this code below So right now, dataConverted1 = [new Date(2020, 12, 14, 2)] TO simply put, is there any way that I can get an output exactly like dataConverted1 = [new Date('2020', '12', '14', '2')] Thank you for your time, -
Django: How to update second_form_class with UpdateView?
I have two models one is a CustomUser and the other one is the Profile for that user. I also created the forms for each model so I can use them in the UpdateView as form_class and second_form_class. Currently, my UpdateView updates the first form but not the second one. I would like for the update view to update both forms. Please point me in the right direction. models.py def my_slugify_function(content): return content[:content.find("@")].replace('.','').lower() class CustomUser(AbstractUser): first_name = models.CharField(max_length=150, default="Darth") last_name = models.CharField(max_length=150, default="Vader") email = models.CharField(max_length=150, default="darth.vader@deathstar.com", null=True, blank=True) slug = AutoSlugField(populate_from=['email'], slugify_function=my_slugify_function, unique=True) def get_absolute_url(self): return reverse('profile', kwargs={'slug': self.slug}) class Profile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) summary = RichTextUploadingField(default="Enter something awesome about yourself.") phone = PhoneField(blank=True, help_text='Contact phone number') zipcode = models.CharField(max_length=255, default='17055') location = models.CharField(max_length=300, null=True, blank=True, default=zipcode_data(zipcode)) forms.py class CustomUserForm(ModelForm): class Meta: model = CustomUser fields = ['first_name', 'last_name', 'email',] class ProfileForm(ModelForm): class Meta: model = Profile fields = ['summary', 'location', 'minimun_salary', 'employment_type', 'work_authorization', 'relocate', 'travel', 'relocate', 'phone' ] views.py class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = CustomUser form_class = CustomUserForm second_form_class = ProfileForm template_name = 'profile/profile_edit.html' success_url = "home.html" def get_context_data(self, **kwargs): context = super(ProfileUpdateView, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class(self.request.GET, instance=self.object) if 'form2' not in context: … -
Is it possible to create a filtering matching system with Django?
1. Convert multiple pdf files containing conditional content into json files and save them in Django db (a > 10, b > 25, c = 15} 2. Create an input form to enter the information of a specific person a: 11 b: 20 c: 15 (*b item not satisfied) I would like to create a system that compares the input data with the input data based on the json file (condition) stored in the db, and outputs the name of the json file? if the condition is satisfied. It looks like a recommendation system, but in the end it seems to be a filtering system using multiquery. I think there is a shopping mall page with a similar function. When buying sneakers on the shopping page, Click on the white color to see only the white sneakers, If you select 280mm among the filtered items I want to implement it so that only sneakers with 280mm can be seen. TT I'm looking for a similar example, but it doesn't come out Are there any similar examples or detailed reference materials? TT -
Django: How to get the most similar record to multi filter query
I have a database of consumer products and I need to filter based on their specs. These queries can be filtering upwards of 10 varying types of fields. This often leads to no exact matches. When there are no exact matches, I would like to return the most similar products. I figured the easiest way to do this would be to annotate a "count" for each column that does match a filter. Then order by products with the greatest "count". Is there a way to do this? Or is there some other way to get similar matches with Django? For example if I have the following query: Laptop.objects.filter(brand='Dell', ram=8, price__lte=1000, screen_size=13.3) If the queryset is empty i'd like to return the laptop with the most matching fields of those 4 filters. -
Create a custom list of fields inside of form in Django
Hi guys I hope you can help me with this, I'm making a dynamic form that displays some checkboxes for each day of the week that are in a range, e.g if I select from february 22 to february 26 (Monday to friday), my form will display checkboxes only for those days. Now what I want is to create a list of fields to render in my template, instead of rendering one by one. I'm making something like this, this is a simplified version: class CustomForm(forms.ModelForm): field1 = forms.BooleanField(required=False) field2 = forms.BooleanField(required=False) check_day_2 = forms.BooleanField(required=False) check_day_1 = forms.BooleanField(required=False) check_day_2 = forms.BooleanField(required=False) check_day_3 = forms.BooleanField(required=False) check_day_4 = forms.BooleanField(required=False) check_day_5 = forms.BooleanField(required=False) check_day_6 = forms.BooleanField(required=False) check_day_7 = forms.BooleanField(required=False) check_days_fieldsname = ['check_day_1', 'check_day_2', 'check_day_3', 'check_day_4', 'check_day_5', 'check_day_6', 'check_day_7'] def __init__(self, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) self.check_fields = [] for fieldname in self.check_days_fieldsname: if fieldname in ['check_day_1', 'check_day_2'] self.fields[fieldname].initial = True self.check_fields.append(self.fields[fieldname]) Then when I render on my template like this: {{form.field1}} <!-- shows correctly --> {{form.field2}} <!-- shows correctly --> <!-- loops but shows <django.forms.fields.BooleanField object at 0x00000222E4BA5340> --> {% if form.check_fields %} {% for check in form.check_fields %} {% if not check.is_hidden %} {{ check }} {% endif %} {% endfor %} … -
Can I access the request object in a console error?
I am not very familiar with Django but have to make some changes to how it logs for a work project. I am wanting to add information from the request object to the logs. # in a view I can log by the follow import logging MODULE_LOGGER = logging.getLogger(__name__) class IndexPage(): def get(self, request, *args, **kwargs): MODULE_LOGGER.warning("log me!") # code... return self.render_to_response(context) This then gets logged out by this class: import json from fluent import handler class JsonFormatter(handler.FluentRecordFormatter): def format(self, record): data = super(JsonFormatter, self).format(record) return json.dumps(data) And we have the following logger settings (which I don't really understand) LOGGING = { "version": 1, "disable_existing_loggers": True, "root": {"level": "WARNING", "handlers": ["sentry", "json_console"]}, "formatters": { "console": {"datefmt": syslog_date_fmt, "format": syslog_msg_format}, "json_fmt": { "()": "out_project.logs.JsonFormatter", "format": { "level": "%(levelname)s", "hostname": "%(hostname)s", "name": "%(name)s", "where": "%(module)s.%(funcName)s", "stack_trace": "%(exc_text)s", }, }, }, "filters": { "require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}, "file_logging": {"": ""}, }, "handlers": { "null": { "level": "DEBUG", "class": "logging.NullHandler", }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "console", }, "sentry": { "level": "WARNING", "class": "raven.contrib.django.raven_compat.handlers.SentryHandler", }, "json_console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "json_fmt", }, }, "loggers": { "raven": { "level": "INFO", "handlers": ["json_console"], "propagate": False, }, "sentry.errors": { "level": "INFO", "handlers": ["json_console"], "propagate": … -
How do I make a function based create view in django
I am trying to make a function based create view in django. This is my code in the views.py file. def video_upload_view(request): form_class = VideoUploadForm form = VideoUploadForm(request.POST) if request.method == 'POST': if form.is_valid(): form.creator = request.user form.save() return reverse(home_page) return render(request, "video_upload.html", {"form": form }) This is my html file {% extends 'base.html' %} {% block title %}Upload{% endblock %} {% block content %} <br> <form method="post"> {% csrf_token %} {{ form.as_p }} <button class='btn btn-secondary'>Upload</button> </form> {% endblock %} But when I click upload the form refreshes and I don't get redirected neither anything uploads. Thanks. -
RetrieveAPIView Django Rest framework, return custom response when lookup_field detail does not exists in database
I am new to Django rest framework. I have a model and serializer. Trying to retrieve data using RetrieveAPIView using a lookup_field. I want to return custom response when lookup_filed data does not exits in database. Below is my view class GetData(RetrieveAPIView): serializer_class = DataSerializer lookup_field='id' action = "retrieve" def get_queryset(self): user = self.kwargs['id'] Data.objects.all() This is my response: { "detail": "Not found." } -
Package installation error in Django channels
I am having the error shown below when I type the installation command of channels: python -m pip install -U channels running build_ext building 'twisted.test.raiser' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Bu ild Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ERROR: Failed building wheel for twisted Running setup.py clean for twisted Failed to build twisted Installing collected packages: twisted, daphne, channels Running setup.py install for twisted ... error -
Django template. Best way for integer iteration
I want to display in a html as many tables as there are loops in a tournament object. I need to iterate by value in field loop_count of Tournament model (the numbers themselves in the list are not needed). I didn't find a way on the Internet, so I came up with it myself. With property, is this the best way for do it? Tournament model: class Tournament(models.Model): name = models.CharField("Title",max_length=50,unique=True) loop_count = models.PositiveSmallIntegerField("Count of loop") @property def loop_count_list(self): return range(self.loop_count) Html: {% for loop in tournament.loop_count_list %} <div class="home-champ"...> {% endfor %> And if I need the numbers themselves in the list, I can do the following: (i know about forloop.counter) Html: {% for loop in tournament.loop_count_list %} <b>Index: {{ loop }}</b> <div class="home-champ"...> {% endfor %> -
Posting and reading metadata with D jango rest framework json api
I'm using Django rest framework json api and I'm trying to post some meta data in my JSON:API POST request. let user = { data: { type: "User", attributes: { type: "individual", status: "active" }, relationships: { individual: { data: { type: "Individual", id: applicant.id } } }, meta: { message: vm.createApplicantAccountMessage } // <------ This is the meta info } }; JsonApiService.create('users', user); But I cant figure out how to read it inside my viewset perform_create function. class UserViewSet(BaseViewSet): queryset = User.objects.none() serializer_class = UserSerializer filterset_class = UserFilterSet def perform_create(self, serializer): # TODO: Find out how to read what is inside the meta message here Any help appreciated! -
Python, Django: Is there a way to edit multiple datasets in one template
Good evening, I would like to know if there's a practical or even best way to edit multiple - but variable - datasets inside one single template in django? Here's an example that might explain my question/problem: The user creates an object and defines a changing amount of subobjects... class Object(models.Model): name = models.CharField(max_length=50, null=False, blank=False) sub_objects = models.IntegerField(default=1, validators=[MaxValueValidator(12), MinValueValidator(1)]) date_created = models.DateField(auto_now_add=True) The subobjects will be created in the background, the names after a certain pattern (Objectname_A1, Objectname_A2, Objectname_A3, etc.) but with empty additional data. This additional data is unknown to the user while creating the object and has to be filled later on... class Subobject(models.Model): parent = models.ForeignKey(Object, null=False, blank=False, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=False, blank=False) additional_data_a = models... additional_data_b = models... additional_data_c = models... additional_data_d = models... date_created = models.DateField(auto_now_add=True) Now: Often the user has the information for multiple subjobjects and of course I could let him/her jump into each dataset separately and fill out the missing data...but isn't there a better/more efficient way? Is there - and if there are multiple ways, which is the best - a way to show the user all subobjects to one object in a single template and let him/her … -
"Got KeyError when attempting to get a value for field `fk_idbrand` on serializer
I'm currently building a django app and I'm serializing my views, but when applying the serializer to the model is experiencing an error that I've been unable to fix: models.py class vehicles_brand(models.Model): pk_idbrand= models.AutoField(db_column='PK_IdBrand', primary_key=True) # Field name made lowercase. fk_idcountry= models.ForeignKey(locations_country, on_delete= models.CASCADE, db_column='FK_IdLocationCountry', related_name='Country') name = models.CharField(max_length=20, default=None, null=True) class Meta: db_table = 'vehicles_brand' verbose_name_plural = "Vehicle Brands" def __str__(self): return self.name class vehicles_model(models.Model): pk_idmodel = models.AutoField(db_column='PK_IdModel', primary_key=True) # Field name made lowercase. name = models.CharField(max_length=20, default=None) fk_idbrand= models.ForeignKey(vehicles_brand, on_delete= models.CASCADE, db_column='FK_IdVehicleBrand', related_name='Brand') class Meta: db_table = 'vehicles_model' verbose_name_plural = "Vehicle Models" serializers.py class brandSerializer(serializers.ModelSerializer): class Meta: model = vehicles_brand fields = '__all__' class modelSerializer(serializers.ModelSerializer): brand = brandSerializer(source="FK_IdVehicleBrand", many=True, read_only=True) class Meta: model = vehicles_model fields = '__all__' output: "Got KeyError when attempting to get a value for field `fk_idbrand` on serializer `modelSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'fk_idbrand'." I've checked my models and the serializers but for me everything seems to be ok, thanks in advance for any hint or help. -
No module 'Django' found. Trying to deploy a django app to Azure App Services. Requirements.txt is not being installed by Oryx
Trying to deploy django app to azure app services. The project attempts to launch but fails because it's dependencies aren't being installed on build. I used zip deploy to deploy the project, and I have SCM_DO_BUILD_DURING_DEPLOYMENT=True, it still isn't installing the requirements.txt file. This is the error message from the azure log stream; enter image description here These are the app folder contents of my project. enter image description here Any Suggestions? Please let me know if you have any suggestions, im out of ideas. -
how do I group results based on categories?
I want to create a data visualization API where I need to use the results of ASerializer by their given tag in order to categorize each object into categories based on their associated tag if the object contains two tags, then it should be displayed in both . e.g current output { "count":117, "next":"http://localhost:8002/api/v1/demo/list/?page=2", "previous":null, "results":[ { "_id": "T1189", "title": "promise", "tag": [ "Demo", "Demo2" ], "queries": [], } ] } desired format [ { "Demo": [ { "_id": "T1189", "title": "promise", "tag": [ "Demo", "Demo2" ], "queries": [], } ], "Demo2": [ { "_id": "T1189", "title": "promise", "tag": [ "Demo", "Demo2" ], "queries": [], } ], } ] code # serializers class TagSerializer(serializers.ModelSerializer): def to_representation(self, value): print(value) return value.name class Meta: model = Tag fields = ('name',) class ASerializer(serializers.ModelSerializer): queries = QueriesSerializer(source='modelb_set', many=True) tag = TagSerializer(many=True) class Meta: model = ModelA fields = ('_id','title', 'tag','queries',) class QueriesSerializer(serializers.ModelSerializer): class Meta: model = ModelB fields = '__all__' #viewsets class BooksViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = ModelA.objects.all() serializer_class = ASerializer -
How to capture a blank slug value in a django url pattern?
I know I can do this with re_path, but is there a way to make a slug optional in a URL? Something like: path("issues/<int:pk>/<optional-slug:slug>/") I'm working on upgrading to Django 2.0, and trying to remove as many of my old-style, regex-based url patterns as possible.