Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store balances on goods in the sections of the goods and dates in Django?
I'm new in django. There is a task to write an application for the movement of residues in the warehouse. The application must be able to receive data in the context of a product or goods in the context of a date or a date interval, or on a specific date. Theoretically, I understand the structure of the model: Product model Model Document (Income / Expense Document) Model DocumentRow (Tabular part of the document) Transactions model (intermediate table for storing balances; balances for each month should be recorded here). For paragraph 4, you need to record balances by month and product. To keep the data in this table up to date, I need to recalculate all balances after this date when writing the DocumentRow on a specific date. Example: 10/01/2018 Arrival 10 10/15/2018 Arrival 20 12.12.2018 Consumption 10 Entries in the Transactions table (Month, Start Balance, End Balance) 10/01/2018 0 10 10/01/2018 10 30 12/01/2018 30 20 I donβt know whether it is possible to implement this on django, in fact I need an analog of a turnover balance sheet, I need your opinion or a new look at this problem -
Django ORM - query depending on through table
here is my data model: class User(Model): name = models.CharField(max_length=255) teams = models.ManyToManyField(Team, through=UserTeam, related_name='users') class Team(Model): name = models.CharField(max_length=255) class UserTeam(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) is_special = models.BooleanField(default=True) When i query for all users, i get a result like this (json result in rest api: { 'name': 'user-1', 'teams': [ { 'name': 'team-1', }, { 'name': 'team-2', } ] } What i want to achieve is, i want to get only the the teams where the is_special flag is set to true for the user and team. e.g. When a user is in two teams and one team has is_special flag set to false, then this team should be excluded from the result above... Thats why i included in my user serializer: teams = TeamSerializer(read_only=True, many=True) def get_teams(self, obj): teams = Team.objects.filter( userteam__user=self.context['request'].user, userteam__is_special=True ) serializer = UserSerializer(instance=teams, many=True) return serializer.data But i still get the same result... any ideas or suggestions? thanks! -
Adding content to django navbar
Im stuck my django blog project. I create a standart blog but i have a problem now. When i add in navbar some categorys in all post i see this post index page. But when i go another page (like contact form) navbar post links are disappear. let me explain; i create three article and i add this articles in "Music" category after then i use this code in my navbar; {% for category in category %} {% if category.name == 'Music' %} {% for article in category.get_article %} <li class="nav-item" > <a class="nav-link" title="{{ article.title }}" href="{% url 'article:detail' slug=article.slug %}"> <p> {{ article.title }}</p></a></li> {% endfor %} {% endif %} {% endfor %} So I want to do here is to bring the titles of the articles in the music category to the menu. I'm not sure if this is the right method but it works on the index page. After this if i go contact page this links are disappear. (Also Contact form is a separate app https://github.com/maru/django-contact-form-recaptcha.) same time, I use another method but these links are also disappear; {% for article in articles %} {% if article.slug == 'about_us' %} <a href="{% url 'article:detail' slug=article.slug β¦ -
Export Inline ForeignKey entries from parent model using import-export in Django admin
So I'm trying to use import-export to export inline entries from the parent model in Django's admin. I don't want to have to register the inline model with Django, but rather using the import-export's resources module, export directly from the parent model's list view in Django's admin. I couldn't find any way to do this in any of the Stack Overflow posts, and some of the other resources I googled. I tried using the ForeignKeyWidget and fields module to allow me to do this, but when I export, no data is populated. Here are my models: class OrderEntry(models.Model): order = models.ForeignKey(Order, related_name="order_entries", on_delete=models.PROTECT) inventory = models.ForeignKey(Inventory, related_name="order_entries") quantity = models.PositiveSmallIntegerField(default=1) subtotal = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class Order(models.Model): user = models.ForeignKey(User, related_name="orders") and my admin (I only have quantity as I was testing if it would populate first): class OrderEntryResource(resources.ModelResource): quantity = fields.Field(column_name="Quantity", attribute="orderentry", widget=ForeignKeyWidget(OrderEntry, field='quantity')) class Meta: model = OrderEntry fields = ('order', 'inventory', 'quantity', 'subtotal',) class OrderAdmin(ImportExportModelAdmin): resource_class = OrderEntryResource admin.site.register(Order, OrderAdmin) If at all possible, I'd like to include foreignkey fields for the User model also. Thanks so much! -
django.db.utils.InternalError: (1054, "Unknown column 'qd_project_assist.id' in 'field list'")
class QdProjectAssist(models.Model): project_id = models.ForeignKey('QdProject', on_delete=models.CASCADE) assist_id = models.ForeignKey('QdAssist', on_delete=models.CASCADE) sort = models.PositiveIntegerField('ζεΊ', blank=True, null=True) add_time = models.PositiveIntegerField() uptime = models.DateTimeField( auto_now=True) class Meta: managed = False db_table = 'project_assist' unique_together = ('project_id', 'assist_id') I export the table with two primary keys from mysql. Reporting errors in the course of use: django.db.utils.InternalError: (1054, "Unknown column 'qd_project_assist.id' in 'field list'") -
Django 1.11 new middleware and decorator_from_middleware_with_args
I've been looking to send a middleware class a parameter (name), but the documentation is really contradictory When I try to add *args, **kwargs or a named argument to init I get this message: TypeError: init() got an unexpected keyword argument Head over to the manual and it says: Django initializes your middleware with only the get_response argument, so you canβt define init() as requiring any other arguments. Then I find a method called decorator_from_middleware_with_args and the docs say decorator_from_middleware_with_args(middleware_class)[source]ΒΆ Like decorator_from_middleware, but returns a function that accepts the arguments to be passed to the middleware_class. For example, the cache_page() decorator is created from the CacheMiddleware like this: cache_page = decorator_from_middleware_with_args(CacheMiddleware) @cache_page(3600) def my_view(request): pass But how can this be possible if the init of middleware can't accept arguments? Anyone know how to get this working in Django 1.11? -
Formset_factory tutorial
I really need your help, please. how not to reenter the customer? a customer can buy one or more items Here I've done enter image description here It'do like this in views.py: class VenteFormView(View): VenteFormSet = formset_factory(VenteForm) template_name = "venteH.html" def get(self, request): return render(request, self.template_name, {'form': self.VenteFormSet()}) def post(self, request): vente_formset = self.VenteFormSet(self.request.POST) if vente_formset.is_valid(): for agence in vente_formset: agence.save() return redirect('affiche_vente') else: return render(request, self.template_name, {'form': self.VenteFormSet()}) -
Docker Postgres + Django: Pytest fails
Since I moved to Docker Postgres, my tests via pytest fail. I now identified as the problem my database connection. How it works: When I use PostgreSQL 10 on my Mac it works smoothly. As database credentials in my settings.py I use: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'project', 'USER': 'MyName', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } } How it fails: Since I moved to Docker + Postgres, I have to use different credentials to connect to my Docker Postgres: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } As I want to use Docker rather than PostgreSQL, but still want to be able to test, I wonder if you have any solution for my problem? Here my console log output: https://pastebin.com/MZsccuGJ My Dockerfile # Pull base image FROM python:3 # Set environment varibles ENV PYTHONUNBUFFERED 1 # Set work directory RUN mkdir /code WORKDIR /code # Install dependencies RUN pip install --upgrade pip RUN pip install pipenv COPY ./Pipfile /code/Pipfile RUN pipenv install --deploy --system --skip-lock --dev # Define ENTRYPOINT COPY ./docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] # Copy project COPY . /code/ Docker-Compose version: '3' β¦ -
How to pass a dynamically created class to django-configurations instead of using DJANGO_CONFIGURATION
Motivation: We have a very complex config setup in our project. 2 layers of env files, 3 layers of docker-compose, 4+ layers of hierarchy and Mixins for the docker-configurations setup. To simplify things, we want to create our settings class during runtime based on env variables instead of writing a new class for every possible combination of Mixins. app_settings = type('DynamicSettings', mixin_classes, {}) #configuring django from django.conf import settings from django.core.management import execute_from_command_line settings.configure(default_settings=app_settings) execute_from_command_line(sys.argv) File "/home/pascalwhoop/.venv/msod/lib/python3.7/site-packages/configurations/importer.py", line 106, in validate raise ImproperlyConfigured(self.error_msg.format(self.modvar)) django.core.exceptions.ImproperlyConfigured: Configuration cannot be imported, environment variable DJANGO_SETTINGS_MODULE is undefined. Now unfortunately, I see no way in the documented API of django-configurations to pass a class instance instead of the aforementioned environment strings. How would we go about continuing to use the class hierarchy based approach while still allowing us to dynamically create the settings? -
django has add permission raising error on django contrib options.py with obj is missing from positional arg
django 2.1.3 throws execption File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/options.py", line 650, in get_model_perms 'add': self.has_add_permission(request), TypeError: has_add_permission() missing 1 required positional argument: 'obj' django 2.1.3 -
Django: Select From Subquery
I'm tring to use Django Query How to convert this SQL into ORM in Django SELECT * FROM ( SELECT Reciept_Id, Amount, SUM(Amount) OVER(ORDER BY Reciept_Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Total FROM bucket ) T WHERE T.Total <= 900; Thanks for helping -
how to get my api in more dynamic way with django-query
models.py from django.db import models class SeekerRegister(models.Model): seeker_name = models.CharField(max_length=32) seeker_email = models.CharField(max_length=32) class Social(models.Model): social_links = models.CharField(max_length=256) user = models.ForeignKey(access_models.SeekerRegister,on_delete=models.CASCADE,related_name='social',null=True,blank=True) my query: def custom_seeker_api(request): obj = list(SeekerRegister.objects.values('seeker_name','seeker_email', 'social__social_links','social__user', )) return JsonResponse(obj,safe=False) getting: [ { "id": 11, "seeker_name": "soubhagya", "seeker_email": "soubhagya.developer@gmail.com", "social__social_links": "facebook.com/soubhagya", "social__user": 11 }, { "id": 11, "seeker_name": "soubhagya", "seeker_email": "soubhagya.developer@gmail.com", "social__social_links": "twitter.com/soubhagya", "social__user": 11 }, { "id": 11, "seeker_name": "soubhagya", "seeker_email": "soubhagya.developer@gmail.com", "social__social_links": "linkedin.com/soubhagya", "social__user": 11 } ] expecting: [ { "id": 11, "seeker_name": "soubhagya", "seeker_email": "soubhagya.developer@gmail.com", "social": [ { "social_links":"linkedin.com/soubhagya", "user": 11 }, { "social_links":"twitter.com/soubhagya", "user": 11 }, { "social_links":"linkedin.com/soubhagya", "user": 11 } ] } ] when i am writing my query i am getting result in first way. means if one use shared multiple social details then it should display along with the same user only in a list here i am expecting my api in the second way with django-query please have a look into my code. -
How should I test that multiple functions were called in a loop?
How can I make sure that all handlers were called in a loop? The best I came up with is to mock fake_handler function and check that this function was called a certain number of times, but I think there might be a better solution. class MessageHandler: def __init__(self, handlers=None): self.handlers = handlers or [] def handle(self, event, body): for handler in self.handlers: handler(event, body) Tests: def fake_handler(*args, **kwargs): pass class TestMessageHandler(TestCase): @patch('tests.test_handlers.fake_handler') def test_handle(self, fake_handler_mock): messages = MessageHandler([fake_handler_mock, fake_handler_mock]) messages.handle(None, None) self.assertEqual(fake_handler_mock.call_count, 2) -
Django middleware process_template_response show middleware response and then view response
Is there a way that first I show my middleware process_template_response response by taking view context data and then show the original view response. I had defined a middleware, def process_template_response(self, request, response): return render(request, 'timepay/tnc.html', {}) And my view is, def view_func(request, product_id): ... ... return TemplateResponse(request, 'timepay/tnc.html', {}) -
django immediately refresh many image
I wrote a program crawling the images from google and classify them. Now it shows the images when crawling all pictures finished, but I want to change to immediately refresh the new images. I don't know how to do,I try the javascript to refresh html,but it cant work, here is my code,thanks for help. views.py templates.html javascript -
Python Django Elasticsearch DSL TransportError for Mapper of Different Types
I'm working on a project using Python(3.6), Django(2.1), ElasticSearch(5.1.1) and Elasticsearch-dsl(5.4.0) in which I need to implement search functionality. Here's what I have tried: From models.py: class searchdatamodel(models.Model): id = models.IntegerField(null=False, primary_key=True) company_name = models.TextField(blank=True, null=True) city = models.TextField(blank=True, null=True) state = models.TextField(blank=True, null=True) zip_codes = models.TextField(blank=True, null=True) street_address = models.TextField(blank=True, null=True) street_address_zip = models.TextField(blank=True, null=True) county = models.TextField(blank=True, null=True) phone_number = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) fax_number = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) web_address = models.TextField(blank=True, null=True) last_name = models.TextField(blank=True, null=True) first_name = models.TextField(blank=True, null=True) contact_title = models.TextField(blank=True, null=True) contact_gender = models.TextField(blank=True, null=True) actual_employee_size = models.IntegerField(blank=True, null=True) employee_size_range = models.TextField(blank=True, null=True) actual_sales_volume = models.IntegerField(blank=True, null=True) sales_volume_range = models.TextField(blank=True, null=True) primary_sic = models.IntegerField(blank=True, null=True) primary_sic_description = models.TextField(blank=True, null=True) secondary_sic_1 = models.IntegerField(blank=True, null=True) secondary_sic_description_1 = models.TextField(blank=True, null=True) secondary_sic_2 = models.IntegerField(blank=True, null=True) secondary_sic_description_2 = models.TextField(blank=True, null=True) credit_alpha_score = models.TextField(blank=True, null=True) credit_numeric_score = models.IntegerField(blank=True, null=True) headquarters_branch = models.TextField(blank=True, null=True) square_footage = models.TextField(blank=True, null=True) registry_date = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'searchdatamodel' # Implement indexing for SearchDataModel model def indexing(self): SearchDataIndex.init() obj = SearchDataIndex( id=self.id, company_name=self.company_name, city=self.city, state=self.state, zip_code=self.zip_codes, street_address=self.street_address, street_address_zip=self.street_address_zip, county=self.county, phone_number=self.phone_number, fax_number=self.fax_number, web_address=self.web_address, last_name=self.last_name, first_name=self.first_name, contact_title=self.contact_title, contact_gender=self.contact_gender, actual_employee_size=self.actual_employee_size, actual_sales_volume=self.actual_sales_volume, primary_sic=self.primary_sic, primary_sic_description=self.primary_sic_description, registry_date=self.registry_date ) obj.save() return obj.to_dict(include_meta=True) From serach.py: class SearchDataIndex(DocType): β¦ -
CORS policy blocking HTTP delete method
I have been working on this open source project for some time now and I encountered an issue where CORS policy is blocking the HTTP delete method whenever I make an axios call. Currently, I do not have access to the backend and when I checked the CORS configuration here (Django config file). All looks good to me. Can you maybe take a look at the config file and advise me where necessary. Below is a snippet of the CORS error I get. -
Set a django object property through a subquery
I have an object of type Foo with a ForeignKey to a Bar. Bar has a property called slug. I can do myfoo.bar = Bar.objetcts.get(slug='123') But this would add an extra query. Is it possible to have Django generate the assignment as a subquery within the update? I.e., generate SQL similar to: UPDATE myfoo SET bar_id = (select id from bar where slug = '123') -
How to integrate django rest framework with AWS SNS and APNS(IOS mobile app)?
I am working on a functionality where I have posts and users model, and every single post has a foreign key relation with users model, and a user can like a post of other user. I am working on only back-end APIs(DRF APIs), now I need to implement notification functionality when a user likes a post of other user, the post owner should get notified. I am working first time on DRF and AWS SNS, can someone suggest me the steps to implement the same. -
how to get all fields of related model in django instead of only id
models.py from django.db import models class SeekerRegister(models.Model): seeker_name = models.CharField(max_length=32) seeker_email = models.CharField(max_length=32) class Social(models.Model): social_links = models.CharField(max_length=256) user = models.ForeignKey(access_models.SeekerRegister,on_delete=models.CASCADE,related_name='social',null=True,blank=True) my query: >>>obj=list(SeekerRegister.objects.values('social')) >>>[{'social': 1}, {'social': 2}, {'social': 3}] expecting: [{'social_links': 'facebook.com','user':1}, {'social_links': 'twitter.com','user':2}, {'social_links': 'linkedin.com','user':3}] when i am writing the above query i am getting only id of social model. how can i get all fields both social_links and user instead. please have a look into my code. -
ubuntu16.04 Django1.11.15+Apache2.4+ptyhon2.7.12+mod_wsgi connection fail
<VirtualHost *:80> ServerName geo-lab <Directory "/bbgo/bbgo/bbgo"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/admin /bbgo/bbgoenv/lib/python2.7/site-packages/django/contrib/admin/static/admin/ <Directory "/bbgo/bbgoenv/lib/python2.7/site-packages/django/contrib/admin/static/admin/"> Require all granted </Directory> Alias /static/summernote /bbgo/bbgoenv/lib/python2.7/site-packages/django_summernote/static/summernote/ <Directory "/bbgo/bbgoenv/lib/python2.7/site-packages/django_summernote/static/summernote/"> Require all granted </Directory> Alias /static /bbgo/bbgo/static <Directory "/bbgo/bbgo/static"> Require all granted </Directory> Alias /upload /bbgo/bbgo/upload <Directory "/bbgo/bbgo/upload"> Require all granted </Directory> WSGIDaemonProcess bbgo python-home=/bbgo/bbgoenv python-path=/bbgo/bbgo WSGIProcessGroup bbgo WSGIScriptAlias / /bbgo/bbgo/bbgo/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> i USED http in my 000-default.conf . βββ LICENSE βββ README.md βββ VERSION βββ accounts β βββ __init__.py β βββ __init__.pyc β βββ admin.py β βββ admin.pyc β βββ apps.py β βββ forms.py β βββ forms.pyc β βββ migrations β β βββ 0001_initial.py β β βββ 0001_initial.pyc β β βββ 0002_auto_20180605_1409.py β β βββ 0002_auto_20180605_1409.pyc β β βββ 0003_profile_alarm_paper.py β β βββ 0003_profile_alarm_paper.pyc β β βββ __init__.py β β βββ __init__.pyc β βββ models.py β βββ models.pyc β βββ tests.py β βββ urls.py β βββ urls.pyc β βββ views.py β βββ views.pyc βββ aliases β βββ __init__.py β βββ __init__.pyc β βββ admin.py β βββ admin.pyc β βββ apps.py β βββ forms.py β βββ forms.pyc β βββ migrations β β βββ 0001_initial.py β β βββ 0001_initial.pyc β β βββ __init__.py β β βββ __init__.pyc β βββ β¦ -
Identify Django Rest Framework ModelSerializer ForeignKey with attribute other than pk
I feel like this is a super basic question but am having trouble finding the answer in the DRF docs. Let's say I have a models.py set up like so: #models.py class Person(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=20) class House(models.Model): name = models.CharField(max_length=20) owner = models.ForeignKey(Person) And I have a ModelSerializer set up like so: #serializers.py class House(serializers.ModelSerializer): class Meta: model = House fields = '__all__' What I want to do is to be able to POST new House objects but instead of having to supply the pk of the Person object, I want to be able to supply the name of the Person object. E.g. post = {'name': 'Blue House', 'owner': 'Timothy'} The actual models I'm using have several ForeignKey fields so I want to know the most canonical way of doing this. -
Best way to update my django model coming from an external api source?
I am getting my data through requesting an api source, then I put it in my django model. However, data update daily.. so how can I update these data without rendering it everytime? def index (request): session = requests.Session() df = session.get('https://api.coincap.io/v2/assets') response= df.json() coin = response['data'] final_result = coin.to_dict('records') for coin in final_result: obj, created = Coincap.objects.update_or_create( symbol = coin['symbol'], name = coin['name'], defaults = { 'price': coin['priceUsd'] }) return render(request, '/home.html/') Right now, I have to go to /home.html , if I want my data update. However, my goal is to later serialize it and make it REST api data, so I wouldn't touch django template anymore. Anyway for it to update internally once a day after i do manage.py runserver? -
Django: set_password isn't hashing passwords to create_user
I have created a form/view to register users, and I've used set_password in my model to set the password. But when I open the shell and retrieved the user objects, I found that the user password that was created using my registration form it isn't hashed. Shell >>> from account.models import User >>> users = User.objects.all() >>> users <QuerySet [<User: test1@email.com>, <User: test2@email.com>]> >>> users[1].password '12345678t' >>> users[0].password 'pbkdf2_sha256$100000$4x9wTDiwPr8O6vwEdIlW25ZsP9M+pbd5d2HsiXgtvEK5' My model: class UserManager(BaseUserManager): def _create_user(self, username, email, password, status, is_staff, is_superuser, **extra_fields): now = timezone.now() if not username: raise ValueError(_('The given username must be set')) email = self.normalize_email(email) user = self.model(username=username, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.status = status user.save(using=self._db) return user def create_user(self, username, email, password, **extra_fields): return self._create_user(username, email, make_password(password), 0, False, False, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): user=self._create_user(username, email, password, 1, True, True, **extra_fields) user.is_active=True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=15, unique=True, help_text=_('ObrigatΓ³rio. 15 caracteres ou menos. Letras, \ nΓΊmeros e @/./+/-/_'), validators=[validators.RegexValidator( re.compile('^[\w.@+-]+$'), _('Digite um username vΓ‘lido.'), _('invalid'))]) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) email = models.EmailField(_('email address'), max_length=255, unique=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this β¦ -
How to write joins in orm
class Test(models.Model): name = models.CharField(max_length=50) class TestDetails(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE) test = models.ForeignKey(Test,on_delete = models.CASCADE) mark = models.IntegerField(default=0) I create a TestDetails when a user signs up for a test. I need to get the list of tests that the user has not signed up.