Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is StatReloader while running Django?
I've just created new Python 3.7 virtualenv with Django 2.2 And each runserver it prints: Watching for file changes with StatReloader I could not find any info in Django's docs etc. Is it related specially to Django somehow? Does it go with Django? What it does? Why is it printed in red in PyCharm? Should I be careful about something? Could it be disabled? Big thx -
Is it possible to have a model field set to subtract sum of values from many table
I'm creating a crypto-currency app. I have a table called Transaction, which can have 0 or many sales stored on Sale Table. Is it possible to set up a field on the Transaction model "coins_remaining" that will be equal to (amount - sum(amount_sold) from sale table). Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) Sale table below class Sale(models.Model): amount_sold = models.IntegerField() total_price_sold = models.DecimalField(max_digits=8, decimal_places=2) date_sold = models.DateTimeField(default=timezone.now) note = models.TextField(default="") transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin_sold = self.total_price_sold / self.amount_sold super(Sale, self).save(*args, **kwargs) -
Django: create an admin section gathering info from multiple models
I've been asked to add in the admin site of a Django project a new section that will gather information from several models (as it were a Database view) but I'm not allowed to change or add tables/views in the db. Checking similar questions custom page for Django admin in SO, I've ended up trying to create a "fake" model that won't be managed by Django and adding custom urls in get_urls method. Let code explain itself: core/admin.py class ConfigurationOverview(Model): aa = ForeignKey(ModelA, on_delete=DO_NOTHING) bb = ForeignKey(ModelB, on_delete=DO_NOTHING) cc = ForeignKey(ModelC, on_delete=DO_NOTHING) class Meta: # Django won't consider this model managed = False # link to the index page at /admin verbose_name = 'Configuration overview' app_label = 'core' @staticmethod def all(): # gather info from ModelA, ModelB, ModelC and create a collection of ConfigurationOverviews return [] @register(ConfigurationOverview) class ConfigurationOverviewAdmin(ModelAdmin): def get_urls(self): urls = super(ConfigurationOverviewAdmin, self).get_urls() my_urls = [ url( r'^$', # /admin/core/configurationoverview/ self.admin_site.admin_view(self.list_view), name='core_configurationoverview_list' ) ] return my_urls + urls def list_view(self, request): context = { 'configuration_overviews': ConfigurationOverview.all(), } return render(request, "admin/core/configurationoverview/change_list.html", context) templates/admin/core/configurationoverview/change_list.html {% extends "admin/change_list.html" %} {% block content %} AAAA {% endblock %} But when accesing /admin/core/configurationoverview/ I'm getting NoReverseMatch at /admin/core/configurationoverview/ Reverse for 'app_list' with keyword … -
override update function in serializer
I am trying to override the update method in my serialize in order to update the field 'status' which is a column in my database. I found here on StackOverflow this code, that will supposedly do the job for me: def update(self, instance, validated_data): fields=instance._meta.fields exclude=[] for field in fields: field=field.name.split('.')[-1] #to get coulmn name if field in exclude: continue exec("instance.%s = validated_data.get(field, instance.%s)"%(field,field)) instance.save() return instance But I just do not understand what this line of code does? exec("instance.%s = validated_data.get(field, instance.%s)"%(field,field)) I would appreciate some help, please. -
Django makemigration gives ImproperlyConfigured: mysqlclient exception
I have sysem default python 2.7.5 on Centos7 linux. In my virtual environment i have python 3.6.3 I installed django 2.2 I get below error while i try to makemigrations : django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. But i installed 1.3.13 successfully : (lor_venv) [lor@centos-s-genel-1 lor]$ pip install "mysqlclient==1.3.13" Requirement already satisfied: mysqlclient==1.3.13 in /home/lor/lor_venv/lib/python3.6/site-packages (1.3.13) (lor_venv) [lor@centos-s-genel-1 lor]$ It still throws this error although i installed 1.3.13 mysqlclient The logs are below : (lor_venv) [lor@centos-s-genel-1 lor]$ pip install "mysqlclient==1.3.13" Requirement already satisfied: mysqlclient==1.3.13 in /home/lor/lor_venv/lib/python3.6/site-packages (1.3.13) (lor_venv) [lor@centos-s-genel-1 lor]$ (lor_venv) [lor@centos-s-genel-1 lor]$ (lor_venv) [lor@centos-s-genel-1 lor]$ python manage.py makemigrations 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 "/home/lor/lor_venv/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/lor/lor_venv/lib64/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/lor/lor_venv/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/lor/lor_venv/lib64/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/lor/lor_venv/lib64/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/opt/rh/rh-python36/root/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", … -
Django CreateView visually indicate required fields without custom template
I am using Django CreateView without a custom template. There are a few fields that are not required for my form. So in my model, blank is set to true. So validation is fine. However, I want to visually indicate to the user which fields are required or not, before the try to submit. Adding an asterisk in the verbose name seems silly because that carries over to admin view and the placeholders. class MainForm(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) summary = models.CharField(max_length=63, verbose_name='Brief Description') volume = models.IntegerField(blank=True) frequency = models.ForeignKey(Frequency, blank=True) ... class RequestForm(forms.ModelForm): ... class Meta: model = models.Request fields = ['company_name', 'mailing_address', 'summary', 'owner_area', 'business_case', 'data_classification', 'data_volume', 'frequency', 'requested_on_behalf_of'] ... I would really like the standard red asterisk, but anything will do really. Without creating a custom template. Is this possible? -
Django: How to apply default value even though null is set explicitly
I have a django application that receives a JSON Document and persists it. The issue is that the JSON may contain keys set to null. In this case django does not use the default value but tries to set it to None, which fails due to the model definition. JSON Document: { "meta": { "type": "Transaction", "version": "1" }, "id": "***************************", "date": "2019-03-25", "purpose": "Lorem ipsum dolor sit amet, consectetur", -> "additional_purpose": null, "amount": "12.34", "currency": "USD" } Model class Transaction(models.Model): id = models.CharField(max_length=100, primary_key=True) account = models.ForeignKey(Account, on_delete=models.CASCADE) created_at = models.DateTimeField(default=django.utils.timezone.now) date = models.DateField() purpose = models.TextField() -> additional_purpose = models.TextField(blank=True, default='') amount = models.FloatField() currency = models.CharField(max_length=3) class Meta: get_latest_by = '-id' ordering = ['-date', '-id'] This yields the following exception: django.db.utils.IntegrityError: NOT NULL constraint failed: transaction.additional_purpose Not sure how to deal with this situation. Can I apply the default value even when the value is set to null explictly? -
cannot import name 'generics' from 'rest_framework'
I'm learning to build rest API with django REST Framework and keep getting this import error: cannot import name 'generics' from 'rest_framework'. I'm using django 2.2, python 3.7.2, django rest framework 3.9.2 Thanks -
How to make a search engine by address? - country - region - city - street
I want to do a search engine in which the address is given. The search field has an autocomplete function and you can choose from the suggested addresses. (just like when you enter the address in google maps) You can also choose from the location tree without typing. Example: I choose from the suggested list in the "State" search engine. - "Country" <---- - Province - Province <---- I choose this province - Province - Province - Province effect: "Country" <---- - Province - Province - City <----- I choose this city - City - City - City - Province - Province - Province effect: <Search> <input> City name </ input> <select> + 10km, + 25km, + 50km </ select> </ Search> How do you do this? I know how to write it in javascript to make such a sliding search engine with autocomplete. But where should I get the data for this search engine? featured in succession: - State - Province - City - Streets I'm currently doing this search engine: dieseshaus.hubertsuder.pl HELP -
Importing packages with ReactJs added to a website
I'm not able to import the axios package using ReactJs integrated to my website. It looks like it's only possible when you create a new react app as in my case I dont have a package file only a package-lock one. What's my problem here and what are my options? I have a django back-end. -
Django serializer.data contains non existant value
Context I have an API endpoint that is used for devices to perform a check-in. When a device is not known: A new CustomerDevice instance is created A new DeviceStatus instance is created related to the newly created CustomerDevice API response: { "customer_device_uuid": "646aaff6-debf-4281-bd7f-064dd6dc8ab8", "device_group": { "group_uuid": "ebd0990b-aeb5-46a4-9fad-82237a5a5118", "device_group_name": "Default", "color": "4286f4", "is_default": true } } When a device is known: A new DeviceStatus instance is created related to the device that made the request. API response: { "customer_device_uuid": "fbbdf1d1-766d-40a9-961f-2c5a5cb3db6e" } The problem The problem is the API response when a known device performs a check-in. The returned customer_device_uuid does not exist in the database and seems like a randomly generated uuid. I want the API response for a known device to be the same as the API response for an unknown device. serializer.data contains the random uuid untill the else statement. From there serializer.data contains the data I need in my response. I tried to call self.perform_create in the if block. This results in serializer.data having the correct data for the response. However, this creates a new CustomerDevice and related DeviceStatus for every check-in no matter if the device is known or unknown. My views.py: class DeviceCheckinViewSet(viewsets.ModelViewSet): serializer_class = … -
Form not saving
How can I save django form without validating. I have a simple form. Like i have a dropdown option if a user select a figi it brings a different field from the model payment and if a user select bank teller it brings a different field from the model payment. So I wanna save them. But its not saving when I use form.is_valid() and it still shows me code post 200 but its not in my database and when I remove form.is_valid(), it throws valueError:validation error. class payments(models.Model): Amount=models.IntegerField(default=00000) figiID=models.CharField(default='F-00000',max_length=10,required=False) Bank_Teller=models.ImageField(upload_to='media/',required=False) html <select id='modePayment'> <option value='test1'>Figi</option> <option value='test2'>Bank Teller</option> </select><br><br> <div class="test1 pricebox"> <form method="post"> {% csrf_token %} <h6>Amount:{{pDetail.Amount}}</h6> <h6>Figi-ID{{pDetail.figiID}}</h6> <button style="background:#4CAF50;color:white;width:150px;height:40px;" value="submit" >Invest</button> </form> </div> <div class="test2 pricebox"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <h6>Amount:{{pDetail.Amount}}</h6> <h6>Bank Teller{{pDetail.Bank_Teller}}</h6> <button style="background:#4CAF50;color:white;width:150px;height:40px;" value="submit" >Invest</button> </form> </div> views.py def dashboard(request): if request.user.is_authenticated: allDocs = Registration.objects.all() pDetail=payment_form() if request.method=='POST': pDetail=payment_form(request.POST,request.FILES) if pDetail.is_valid(): pDetail=pDetail.save() context={'doc':allDocs,'pDetail':pDetail,'iDetail':investment} return render(request,'dashboard.html',context) else: return redirect('Tan:login') -
Test user login in Django
I am using django-otp. Here is the .html here is my urls.py path('user_login/', LoginView.as_view(template_name="user_login.html", authentication_form=SimpleOTPAuthenticationForm, redirect_authenticated_user=True), name='user_login') Here is my .html <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Login</button> {% endbuttons %} </form> Here is my forms.py from django_otp.forms import OTPAuthenticationForm from django import forms class SimpleOTPAuthenticationForm(OTPAuthenticationForm): otp_device = forms.CharField(required=False, widget=forms.HiddenInput) otp_challenge = forms.CharField(required=False, widget=forms.HiddenInput) The models.py file is from django.contrib.auth.models import AbstractUser class ProjectUser(AbstractUser): def __str__(self): return self.username Here is the current test I have for username and password class FormTest(TestCase): def setUp(self): self.credentials = { 'username': 'testuser', 'password': 'secret'} ProjectUser.objects.create_user(**self.credentials) def test_user_password_otp_true(self): response = self.client.post('/user_login/', self.credentials, follow=True) self.assertTrue(response.context['user'].is_active) How can I change the test to include the correct OTP ? -
Retrieve integer from django model field and add it to dictionary if it meets criteria
I'm having trouble getting the code right for this project that I am working on... Basically I have a function with some variables defined: def mealSelect(): calorielimit = Profile.objects.get(pk=user_id).bmr breakfast = Breakfast.objects.all() lunch = Lunch.objects.all() dinner = Dinner.objects.all() snack = Snack.objects.all() breakfastcals = Breakfast.objects.value_list('calories') lunchcals = Lunch.objects.value_list('calories') dinnercals = Dinner.objects.value_list('calories') snackcals = Snack.objects.value_list('calories') todayscals = {} What I am trying to do is: Retrieve a random object for each meal (breakfast, lunch, dinner and snack) If the random objects combined are less than the calorielimit append them to a dictionary with the keys Meal 1, Meal 2, Meal 3, Meal 4 If the random objects combined exceed the calorielimit, continue until a combination is found that does not exceed the calorie limit Return the qualifying dictionary Or if there's a better way to achieve a set of 4 objects below the calorie limit, the concept above is the way I tried and I just couldn't figure out how to make it work so I'm guessing there's probably an easier, more elegant way to get 1 model from each model that when combined are below the calorielimit. Any help is very much appreciated! -
How do I check the validation of several forms in a list?
For a personnal project, I have a view that regroups several froms. For a spacial reason a had to make a list and in that list I added some forms depending on the data in my DB. So my question is : how can I check the validation a those forms that are present in the list. Here is my view : def confirmation_view(request, id ,*args, **kwargs): tournament = Tournament.objects.get(pk=id) sport = tournament.sport rule = Rule.objects.get(tournament=tournament) categories = Category.objects.filter(tournament=tournament) form_tournament = TournamentCreationForm(request.POST or None, instance=tournament) form_sport = SportEditForm(request.POST or None, instance=sport) form_rule = RuleForm(request.POST or None, instance=rule) enum = 1 tab_form_category = [] for category in categories: form_category = CategoryForm(request.POST or None, instance=category) tab_form_category.insert(enum, form_category) enum = enum + 1 if form_tournament.is_valid() and form_sport.is_valid() and form_rule.is_valid(): return redirect('tournament') context = { 'form_tournament': form_tournament, 'form_sport': form_sport, 'form_rule': form_rule, 'tab_form_category': tab_form_category } return render(request, 'confirmation.html', context) I speak about "tab_form_category". I don't have enough experience in Python and Django to deduce the solution by my self. -
serialise a list by staying in another serialiser
This is my output that should look like { "status": 1, "errors": "", "results": [ { "car_type": "sedan", "is_active": true, "variable": { ["tata","hyundai"] } } ] } And my model is, class CarType(CommonBase): car_type = models.TextField(null=True, blank=True) is_active = models.BooleanField(default=True) company = models.ManyToManyField('Company', null=True, blank=True) class Company(CommonBase): company_name = models.TextField(null=True, blank=True) country = models.TextField(null=True, blank=True) how i should write my serialiser for a get API to return all car type with is_active = True -
Django WSGI won't load when adding new middleware
Whenever I try to add a new middleware in settings.py, I get a django.core.exceptions.ImproperlyConfigured: WSGI application 'test.wsgi.application' could not be loaded; Error importing module. What's causing this? -
Requested runtime (Python 3.7.2) is not available for this stack (heroku-18)
django (2.0) I am trying to upload my django app to heroku but i couldn't because it says requested runtime(python 3.7.2) is not available. Counting objects: 100% (1725/1725), done. Delta compression using up to 4 threads Compressing objects: 100% (1721/1721), done. Writing objects: 100% (1725/1725), 9.34 MiB | 21.00 KiB/s, done. Total 1725 (delta 93), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python 3.7.2) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mubashartech. remote: To https://git.heroku.com/mubashartech.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/mubashartech.git' -
How to create a form defined in the database in django?
I have the following big problem and need your help. I need a big form with different field types. The fields of this form should be completely flexible without touching the source code. By this I mean that the number of fields and the individual field type, choices, and field name are immediately changeable. To do this, I had the idea of saving each form field as one entry in a database table, which can be changed online. But i don't know how to create the form from the data of the database table. Thank you for your answers -
Is it possible to get an object in __init__ of ModelSerializer?
I have a ModelSerializer, that gets a list of data. I want to get the serialized object inside my init. Is it possible to do so for every object of the queryset that a passed into the Modelserializer? class CommentSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user = self.context.get('user') class Meta: model = Comment fields = ('id', 'created', 'json_content', 'html_content', 'user_image', 'username', 'username_slug',) class View(ApiView): def get(self, request): comment_list = Comments.objects.all() serializer = CommentSerializer(comment_list, many=True, context={'user': request.user}) -
django testing: access complete source code of email in mail.outbox
I have setup some tests, that check email functionality of my app. After emails are sent in tests, they land in mail.outbox, where I can check for example the subject, headers oder body, like so for example: subject = mail.outbox[0].subject. Now, I wonder if I can somehow access the complete message source code of one of these? Specificaly, this would be needed for testing my CID inlined images approach. -
How to use generate_series on dates and filter specific weekday in a Query?
I have a model Plan that is stored with a date range using DateFields start and end and the integer value effort. The effort is to be interpreted per day. The model cannot be changed. I want to query all Plan objects with their days between (and including) the start and end dates, but filtered for a specific weekday. I have the following code querying for all dates with their respective Plan objects. qs=Plan.objects.annotate(date=Func(F('start'), F('end'), Value('1 day'), function='generate_series')).order_by('date','worker','project').all().values() If I try to use the .filter(date__weekday=7) I get an error: qs=Plan.objects.annotate(date=Func(F('start'), F('end'), Value('1 day'), function='generate_series')).filter(date__week_day=7).order_by('date','worker','project').all().values() NotSupportedError: set-returning functions are not allowed in WHERE LINE 1: ...eporting_project"."key") WHERE EXTRACT('dow' FROM generate_s... I would expect the same QuerySet as with the first query, but only showing Saturdays. Thanks for any help! -
i need help for django framwork
File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 453, in save 'created' if self.instance._state.adding else 'changed', ValueError: The Article could not be created because the data didn't validate. from blog.models import Article,Categorie from blog.forms import ArticleForm data={'titre':"loubia",'auteur':"tako",'contenu':"huile sos tomate onion...",'categorie':Categorie.objects.all()[0].id} form=ArticleForm(data) form.save() Traceback (most recent call last): File "", line 1, in File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 453, in save 'created' if self.instance._state.adding else 'changed', ValueError: The Article could not be created because the data didn't validate. Article.objects.all() , , ]> -
How can i use prefect_related on related_name
I have a Product model.This model have a categories ManyToMany field. Also i have a ProductPhoto model and this model have a product FK field.And this field have a related_name product_photos. My query like this. Product.objects.prefetch_related('categories', 'product_photos') Categories is run perfect with innerjoin. But product_photos does not work. Every each row call the sql again because of get the photos.Like SELECT ••• FROM "core_productphoto" WHERE ("core_productphoto"."product_id" = 1729) -
Moving Procfile to project root directory crashes Django application
I am trying to deploy my Django project with Heroku, and I know my Procfile is in the wrong location. But, when I move it to the correct directory, the app can't start. I initially made the Procfile in my app directory instead of my project root directory, and when I try to move the Procfile to the root directory, I get a ModuleNotFoundError from wsgi.py regarding my settings file (I am using a settings folder to separate development and production settings files, so I made it a module, just FYI). This is my Procfile: web: gunicorn my_site.my_site.wsgi --log-file - Here is my wsgi file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_site.settings.production_settings') application = get_wsgi_application() Here is the error I get when I try to run heroku locally: ModuleNotFoundError: No module named 'my_site.settings' If I add another directory level to the to the location of my settings file (in wsgi.py): 'my_site.my_site.settings.production_settings' I then get a new error about an app not being found in my INSTALLED_APPS in my settings. It seems that me changing the location of my Procfile somehow messes up all the directory extensions in my project, which doesn't make any sense. If I keep the Procfile …