Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Summing sales over last 7 days, 30 days, 3 months, 1 year, for each day on a graph?
I am trying to get data from a model, from the last 7 days, 30 days, 3 months, 1 year (or x days), and sum a sales in the model for each day. I hope that makes sense. So, if I have something like: models.py from django.utils.timezone import now class Sales(models.Model): items_json = models.CharField(max_length=900) amount = models.IntegerField(default=0) name=models.CharField(max_length=100, default="") phone = models.CharField(max_length=100, default="") time=models.DateTimeField(default=now) def __str__(self): return self.name+ "-" + str(self.amount) + "rs" views.py def home(request): sales = Sales.objects.all() total_sales = sum(sales.values_list('amount', flat=True)) return render(request, 'home/home.html', {'total_sales': total_sales}) home.html <div class="panel-body"> <div class="canvas-wrapper"> <canvas id="myChart" width="400" height="200"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['June 8', 'June 9', 'June 10', 'June 11', 'June 12', 'June 13', 'June 14'], datasets: [{ label: 'Total Sales', data: [12, 19, 3, 5, 2, 3, 24], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(108, 123, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(108, 123, 64, … -
ModuleNotFoundError: No module named 'games.wsgi' when deploying Django app to heroku
I'm trying to deploy a Django app to heroku. I get an error of ModuleNotFoundError: No module named 'games.wsgi' where games is my project name. My Procfile created is web: gunicorn games.wsgi . I have installed gunicorn. My requirements.txt is asgiref==3.3.4 Django==3.2 gunicorn==20.1.0 pytz==2021.1 sqlparse==0.4.1 and pipfile also has [packages] gunicorn = "*" my wsgi file has os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'games.settings') my heroku logs show File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 551, in manage_workers 2021-06-14T10:51:35.947270+00:00 app[web.1]: self.spawn_workers() 2021-06-14T10:51:35.947294+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 623, in spawn_workers 2021-06-14T10:51:35.947812+00:00 app[web.1]: time.sleep(0.1 * random.random()) 2021-06-14T10:51:35.947840+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2021-06-14T10:51:35.948243+00:00 app[web.1]: self.reap_workers() 2021-06-14T10:51:35.948270+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2021-06-14T10:51:35.948797+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2021-06-14T10:51:35.949024+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-06-14T10:51:35.949049+00:00 app[web.1]: 2021-06-14T10:51:35.949050+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-06-14T10:51:35.949050+00:00 app[web.1]: 2021-06-14T10:51:35.949077+00:00 app[web.1]: Traceback (most recent call last): 2021-06-14T10:51:35.949147+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 8, in <module> 2021-06-14T10:51:35.949409+00:00 app[web.1]: sys.exit(run()) 2021-06-14T10:51:35.949438+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 67, in run 2021-06-14T10:51:35.949744+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2021-06-14T10:51:35.949767+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 231, in run 2021-06-14T10:51:35.950117+00:00 app[web.1]: super().run() 2021-06-14T10:51:35.950143+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 72, in run 2021-06-14T10:51:35.950381+00:00 app[web.1]: Arbiter(self).run() 2021-06-14T10:51:35.950404+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 229, in run 2021-06-14T10:51:35.950785+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2021-06-14T10:51:35.950813+00:00 app[web.1]: … -
Nested RelatedFactory from FactoryBoy not working
I am using FactoryBoy in Django for my tests. I have 3 models that need to create each other and I cannot create the third and last model. My models: class Tax(models.Model): item = models.ForeignKey('Item', on_delete=models.CASCADE, related_name='taxes') code = models.CharField(max_length=100) class Item(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE, related_name='items') name = models.CharField(max_length=250) class Invoice(models.Model): invoice_id = models.CharField(unique=True, max_length=100) My factories: class TaxFactory(DjangoModelFactory): code = Faker('word') class Meta: model = models.Tax class ItemFactory(DjangoModelFactory): name = Faker('word') taxes = RelatedFactory( TaxFactory, factory_related_name='item', ) class Meta: model = models.Item class InvoiceFactory(DjangoModelFactory): invoice_id = Faker('word') items = RelatedFactory( ItemFactory, factory_related_name='invoice', ) class Meta: model = models.Invoice I am trying to create an object of type InvoiceFactory and I am getting the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: invoices_tax.item_id Can someone help me? Thanks! -
Trouble understanding Django REST framework JWT Auth
I'm using JWT to authenticate API routes in my app. The problem is that in my use case the user might only log in once and should be able to use the app after that without logging in again. I've studied JWT and my first idea was to just set the JWT_VERIFY_EXPIRATION to False. If I understand correctly, this would disable the expiration of the tokens? But this sounds terrible from the security point of view. Even if I obtain a new token at some point, all the old tokens will be accepted also? My second idea was to log the user in once to get the original token and after that get the refresh token. After that I would refresh the token again and again before the previous token expires. Then I found out this from one of the tutorials: Refresh with tokens can be repeated (token1 -> token2 -> token3), but this chain of token stores the time that the original token (obtained with username/password credentials), as orig_iat. You can only keep refreshing tokens up to JWT_REFRESH_EXPIRATION_DELTA Now I'm confused, what is the orig_iat and how does it affect on refreshing the tokens? Is the JWT_REFRESH_EXPIRATION_DELTA some kind … -
'function' object has no attribute 'object' - I am facing this error while updating my form
Here, i am trying to add a product , update and delete. But, when i am trying to update the form , I am facing the following error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\mixins.py", line 125, in dispatch user_test_result = self.get_test_func()() File "C:\blink\myblink\affiliation\views.py", line 116, in test_func newproduct = self.get.object() Exception Type: AttributeError at /affiliation/affiliation/10003/update Exception Value: 'function' object has no attribute 'object' This is my UpdateView: where I am using Class-based views to update the data. I have not used class-based views to add a product or viewing a product. # update view for details class AffProductUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = AffProduct #model fields = ['product_title', 'uid', 'specification', 'sale_price', 'discount', 'img1', 'img2', 'promote_method', 'terms_conditions',] # fields / if you want to select all fields, use "__all__" #template_name = 'affproduct-update.html' # template for updating #success_url = "/blink_viewproduct.html" # redirect url def form_valid(self, form): form.instance.current_user = self.request.user return super().form_valid(form) def test_func(self): newproduct = self.get.object() if self.request.user == newproduct.current_user: return True … -
Differences in Django Queryset ordering
I have a question on how Django Queryset orders items. Background: I'm currently working on a Django project where users can create and edit tours via the Django Admin. A tour is composed of a variable amount of successive stations. Stations can be edited separately or via a stacked inline on the route's page. I'm using Django Rest Framework serializers to output these tours in json format through an API endpoint. Tours and stations are many-to-many related. There are currently two implementations: Based on Django 3.2, DRF 3.12.4 and the default SQLite database (for testing) Based on Django 2.2, DRF 3.12.4 and a MySQL database (actual development) Actual Problem: I mainly manage the tour's stations via the stacked inline. If I define a sequence of stations for a route in my test environment, this order is instantly reflected in the QuerySet and therefore in the API output. But this is not the case for the development environment. Even when the Django Admin shows that specific order, this is not reflected in the output. I assume that Django uses the creation timestamp for ordering here. While kind of randomly sorted stations may be surprising, it's not that useful... So, I'd like … -
Getting, "ValueError at /login/ The view account.views.login didn't return an HttpResponse object. It returned None instead." error
I created a custom user model by extending AbstractBaseUser: class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('Solapur', 'Solapur'), ('Latur', 'Latur'), ('Dhule', 'Dhule'), ('Akola', 'Akola'), ('Nashik', 'Nashik') ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default='Latur') designation=models.CharField(max_length=70) is_active=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username And my manager loos something like this: class FirstManager(BaseUserManager): use_in_migrations=True def create_user(self, username, email, first_name, last_name, location, designation, password, **extra_fields): if not username: raise ValueError('Username is required!') email=self.normalize_email(email) user=self.model(username=username, email=email, first_name=first_name, last_name=last_name, location=location, designation=designation, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, username, email, first_name, last_name, location, designation, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(username, email, first_name, last_name, location, designation, password, **extra_fields) The registration form in forms.py: class MyRegistrationForm(UserCreationForm): password2=forms.CharField(label='Confirm', widget=forms.PasswordInput) class Meta: model=MyRegistration fields=['username', 'first_name', 'last_name', 'email', 'location', 'designation'] The Signup view: def signup(request): if request.method=='POST': if request.POST.get('password1')==request.POST.get('password2'): try: user=MyRegistration.objects.get(username=request.POST.get('username')) return render (request, 'account/signup.html', {'error':'This username already exists!'}) except MyRegistration.DoesNotExist: user=MyRegistration.objects.create_user(first_name=request.POST.get('first_name'), last_name=request.POST.get('last_name'), username=request.POST.get('username'), email=request.POST.get('email'), location=request.POST.get('location'), designation=request.POST.get('designation'), password=request.POST.get('password1')) return HttpResponseRedirect('/success/') else: fm=MyRegistrationForm() return render(request, 'account/signup.html', {'form':fm}) def success(request): return render(request, 'account/success.html') The login view: def login(request): … -
How can I update my Django model using signals?
I am trying to update my 'Cart' model using django signals, the signal is going through the 'CartItem' model and gets the price and quantity, gets the updated total price and then tries to send it to the Cart model, but I'm not sure what I'm doing wrong?, I'm still fairly new to django, I've read through the docs but still stuck on this problem. The print statement inside my signals.py displays the cart total with the new updated_total instance price, so it shows it's doing something right, but this is not reflected in the database. I also would like to know how to keep adding to the total price, at the moment the cart.total resets and only shows the newly added instance price. signals.py @receiver(post_save, sender=CartItem) def add_cart_receiver(sender, created, instance, **kwargs): if created: cart = instance.items_cart print(cart) product_price = instance.item.price print(product_price) quantity = instance.quantity print(quantity) total = 0 updated_total = Decimal(product_price) * int(quantity) total += updated_total print(total) cart.total += total print(cart) cart.save() models.py class CartItem(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) items_cart = models.ForeignKey('Cart', blank=True, on_delete=models.CASCADE, null=True) quantity = models.IntegerField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return 'item:{} cart:{} quantity:{}'.format(self.item, self.items_cart, self.quantity) class Cart(models.Model): user = … -
DRF APIClient format='json' sends formdata instead of json (QueryDict instead if dict)
I'm testing a project that uses axios to communicate with backend. In tests, I use APIClient. The problem is that normally, in the view, request.data is dict whereas when the request is sent from testing class, it is QueryDict. To get dict when testing, I probably need to send JSON. I tried to set format='json' but it didn't help. Django still parses request to QueryDict. payload = { 'ids':[x.id for x in orders], 'status':Order.STATUS__PLACED, } response = self.client.post('/api/url/', payload, HTTP_AUTHORIZATION='Bearer ' + token, format='json') How can I make it work? EDIT: When debugging the view, I see that request.content_type is 'multipart/form-data; boundary=BoUnDaRyStRiNg' -
DRF Error: Cannot assign must be a instance
I'm working on an app that lets you track your expenses and I'm trying to create an 'balnace' object when the user registers, but when I try so I get an Error: Cannot assign "15": "Balance.user_id" must be a "Users" instance. Model class Balance(models.Model): balance = models.FloatField( verbose_name="Balance", blank=False, null=False) user_id = models.ForeignKey( 'expenseApi.Users', verbose_name="Usuario", blank=False, null=False, on_delete=models.PROTECT) def __str__(self): return '{}'.format(self.pk) serializer class RegisterSerializer(serializers.ModelSerializer): tokens = serializers.SerializerMethodField() email = serializers.EmailField(max_length=50) class Meta: model = Users fields= ['id', 'email', 'password', 'name', 'lastname', 'birthday', 'tokens'] extra_kwargs = { 'password': { 'write_only': True, }, } def get_tokens(self,user): refresh = RefreshToken.for_user(user) data = { 'refresh': str(refresh), 'access': str(refresh.access_token), } return data def create(self, request): email= Users.objects.filter(email=request['email']) if email: raise serializers.ValidationError({'detail': 'El email ya esta en uso'}) user = Users.objects.create_user(email=request['email'], password=request['password'], name=request['name'], lastname=request['lastname'], birthday=request['birthday']) user['balance'] = Balance.objects.create(balance=0,user_id=user.id) return user -
Connection refused with psql django and docker (cookiecutter-django)
My django app is failing to connect to the psql container with the standard connection refused error. I used django-cookiecutter which supplies the psql username and password automatically via environment variables and then this I gather is passed back into django with via a .env file that hosts a DATABASE_URL string. Error django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? When I set a breakpoint in django settings I can see that the DATABASE_URL seems to be converted appropriately into the standard db dict: {'NAME': 'hustlestat', 'USER': 'HjhPLEwuVjUIIKEHebPqNG<redacted>', 'PASSWORD': 'I43443fR42wRkUaaQ8mkd<redacted>', 'HOST': 'postgres', 'PORT': 5432, 'ENGINE': 'django.db.backends.postgresql'} When I exec into the psql container with psql hustlestat -U HjhPLEwuVjUIIKEHebPqN<redcated> I can connect to the db using that username. I'm not 100% on the password as it isn't asking me for one when I try to connect. Here is the docker compose which is generated automatically by cookie cutter: version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: hustlestat_local_django container_name: django depends_on: - postgres - mailhog volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: … -
How to send DateTimeField as Null or empty from serializer in django model?
I want to send a pre_order (DateTimeField) through my API. I created the model's name Order in y models.py class Order(models.Model): COOKING = 1 READY = 2 ONTHEWAY = 3 DELIVERED = 4 STATUS_CHOICES = ( (COOKING, "Cooking"), (READY, "Ready"), (ONTHEWAY, "On the way"), (DELIVERED, "Delivered"), ) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) chef = models.ForeignKey(Chef, on_delete=models.CASCADE) driver = models.ForeignKey(Driver, blank=True, null=True, on_delete=models.CASCADE) customer_street_address = models.CharField(max_length=500) customer_flat_number = models.CharField(max_length=500) phone = models.CharField(max_length=500) total = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) delivery_charge = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) service_charge = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) delivery_instructions = models.CharField(max_length=500, null=False, blank=True) status = models.IntegerField(choices=STATUS_CHOICES) created_at = models.DateTimeField(default=timezone.now) picked_at = models.DateTimeField(blank=True, null=True) coupon = models.ForeignKey(Coupon, related_name='order_coupon', to_field='code', blank=True, null=True, on_delete=models.SET_NULL) discount_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) pre_order = models.DateTimeField(null=True,blank=True) Where I set it as blank and null = True so it can be sent as empty* For this model, I created a serializer in my serializer class. serializer.py class OrderCreateSerializer(serializers.ModelSerializer): access_token = serializers.CharField(max_length=200, allow_blank=False, allow_null=False) chef_id = serializers.IntegerField() order_details = serializers.CharField() stripe_token = serializers.CharField() coupon=serializers.CharField(max_length=100, allow_blank=True) pre_order = serializers.DateTimeField(source='date_read', default=None, required=False) class Meta: model = Order fields = ( 'access_token', 'chef_id', 'stripe_token', 'delivery_charge', "service_charge", "customer_street_address", "customer_flat_number", "phone", 'order_details', 'delivery_instructions', 'coupon','pre_order') Now for endpoint use, I created an endpoint view … -
Change Django admin logo with django-adm-interface or by overiding base_site.html not working
I develop Django app with Docker and I want to customize Django admin I have tried 2 solutions: using django-admin-interface Overriding base_site.html as mentionned in Django documentation If I use django-admin-interface, it works well except for logo that is not uploaded because path is the good one: Not Found: /admin/login/admin-interface/logo/mereva_logo_8ksHnds.png if I connect to web docker container, images logos mereva_logo.png and mereva_logo_8ksHnds.png are presents in folder /usr/src/app/admin-interface/log If I try to override base_site.html, my logo is display but Django logo is also displayed project architetcure - app - admin-interface - logo - mereva_logo.png - mereva_logo_8ksHnds.png - favicon - static - images - mereva_logo.png - mereva_logo_8ksHnds.png - ... - templates - admin - base_site.html - layout - base.html - home.html docker-compose.yml version: '3.7' services: web: restart: always container_name: etl_web build: context: ./app dockerfile: Dockerfile.dev restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/usr/src/app ports: - 8000:8000 env_file: - ./.env.dev entrypoint: [ "/usr/src/app/entrypoint.dev.sh" ] depends_on: - redis healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/"] interval: 30s timeout: 10s retries: 50 redis: container_name: etl_redis image: "redis:alpine" celery: container_name: etl_celery build: context: ./app dockerfile: Dockerfile.dev command: celery -A core worker -l info volumes: - ./app:/usr/src/app env_file: - ./.env.dev depends_on: - web - redis celery-beat: … -
Django application hosted on IIS gives 500 internal server error as output without any error logs either on the django application or IIS logs
I have hosted a Django application on IIS server in Windows. I am able to process and get the expected output for most of the files. However, for few input excel files, the service is returning 500 internal server. I can see only the 500 error status in IIS logs (inetpub logging). The Django service is exiting without any error log. Any lead will be helpful! -
Django: Store Q query objects for repeatable search?
In my Django based web app users can perform a search; the query consists of several dynamically constructed complex Q objects. The user should be able to save her search to repeat it at some later point. For that I'd like to store the Q objects (I guess) in a database table. Is this good practice? How would you approach this? Thanks in advance. -
forgotten credentials (superuser and password) in Django project
Forgotten superuser name and password in Django project. What is the correct way to recover it specially the superuser name? Is it a good practice to create a new superuser to get to admin panel and recover the forgotten superuser name from there or there is another way to recover it in terminal? -
How to execute some code at last retry of a Celery task
I am using Django with Celery to run my background tasks. I have a task that can fail for some IO reasons: @shared_task(bind=True) def mytask(self, someargs): try: do_some_io_operation() except SomeException as e: self.retry(max_retries=5) # do some other stuff I want to execute some code only if the last retry fails and exit the function without raising an exception. Is it possible? -
How to save a table from Datatables to a database in Django?
I'm using Datatables to display tables in Django on the server side. After searching for a phrase, I have a button ready to save the current table after filtering to Excel. I would like the second button to create a new table in the database and save the same table to it as for Excel. I don't know how I can send AJAX data to Django and read it in views in such a way that I can query the database. -
How to show model images in Django?
I have such models.py file class Product(models.Model): CATEGORIES = { ('Computer', 'Комп\'ютер'), ('Smartphone', 'Смартфон') } photo = models.ImageField(upload_to='images/', blank=True) title = models.CharField(max_length=128, blank=False) description = models.CharField(max_length=5000, blank=False) price = models.PositiveIntegerField(blank=False) category = models.CharField(max_length=30, choices=CATEGORIES) count = models.PositiveIntegerField(blank=False) In settings.py i DON'T have media variables/dirs Also i try to show images in such way {% extends 'base.html' %} {% block title %}Каталог{% endblock %} {% block content %} {% for i in products %} <img src="{ static i.photo.url }"> {{i.title}} {% endfor %} {% endblock %} Result: I add my model objects in Django Admin -
multi step form and model inheritance in django
I have seen this approach in many web applications (e.g. when you subscribe for an insurance), but I can't find a good way to implement it in django. I have several classes in my model which inherit from a base class, and so they have several fields in common. In the create-view I want to use that inheritance, so first ask for the common fields and then ask for the specific fields, depending on the choices of the user. Naive example, suppose I want to fill a database of places class Place(Model): name = models.CharField(max_length=40) address = models.CharField(max_length=100) class Restaurant(Place): cuisine = models.CharField(max_length=40) website = models.CharField(max_length=40) class SportField(Place): sport = models.CharField(max_length=40) Now I would like to have a create view when there are the common fields (name and address) and then the possibility to choose the type of place (Restaurant / SportField). Once the kind of place is selected (or the user press a "Continue" button) new fields appear (I guess to make it simple the page need to reload) and the old one are still visible, already filled. I have seen this approach many time, so I am surprised there is no standard way, or some extensions already helping … -
Openstreetmap location share python/django
Can someone please tell me how can I share location from Openstreetmap. I took OSM as my base map and modified as needed but I need to share location with users so how can I do that? Thank you! -
Received task in django celery beat, but not executed
I'm using django with celery, celery beat, and redis to run periodic tasks. The problem I'm having is that tasks registered in celery are received but not executed. Also, the task stops in the middle even though I have not specified a stop setting. The environment is as follows. windows10 python = 3.7.9 PostgreSQL 13.3 Redis server v=3.0.504 sha=00000000:0 malloc=jemalloc-3.6.0 bits=64 build=a4f7a6e86f2d60b3 [requirements] celery==5.0.5 Django==3.2.4 django-celery-beat==2.2.0 django-celery-results==2.0.1 django-redis==5.0.0 redis==3.5.3 I built the environment by referring to the following site. https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html project | +-app | +-__init__.py | +-tasks.py | +-project | +-__init__.py | +-celery.py | +-settings.py | +-.env +-manage.py +-requirements.txt settings are configured as follows. settings.py INSTALLED_APPS = [ # Add your apps here to enable them . . . 'django_celery_results', 'django_celery_beat', . . ] # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases load_dotenv(find_dotenv()) DATABASES = { 'default': dj_database_url.config(conn_max_age=600), } CELERY_BROKER_URL = "redis://127.0.0.1:6379/1" CELERY_RESULT_BACKEND = "django-db" #CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/" DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' .env DATABASE_URL=postgres://postgres:pass@localhost/project celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') app = Celery('Project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related … -
How to update a boolean field through a checkbox Django
I have a boolean field on a form, that i can fill through a template. But then i want to update(modify) that boolean value, but I'm too inexperienced and don't know how. My model (it have a lot more fields, but I dont want to make it longer that it needs to be): class Orden(models.Model): elac = models.BooleanField(default=False) The fill template (this one works perfectly): <div class="card card-body"> <div class="form-group row"> <table class="table table-striped table-bordered table-sm" width=100%> <tr> <td class="text-center"> <h5>E.A.</h5> </td> </tr> <tr> <td class="text-center"> {{orden.elac}} </td> </tr> </table> </div> </div> The save view: def ordenfill(request, client_id): if request.method == 'POST': orden = ordenForm(request.POST) if orden.is_valid(): orden.instance.client_id = client_id init = orden.save() return redirect('ordenview', id=init.id) else: orden = ordenForm() client = Cliente.objects.get(id=client_id) context = { 'orden': orden, 'client': client, } return render(request, 'ordenfill.html', context) The update template (the one i dont know how to do) <div class="form-group row"> <div class="form-group row"> <label class="col-sm-2 col-form-label">0.8</label> <div class="col-sm-4"> <input type="checkbox" class="form-check-input" name="elac" value = "{{orden.elac}}"/> </div> </div> </div> And the update view: def ordenupd(request, id): orden = Orden.objects.get(id=id) context = { 'orden': orden, } return render(request, "ordenupd.html", context) Now, the issue I have right now is that I dont know how … -
Passing Model and Field Object from view to Django-tables2 Class - Not Rendering Table
i am new to python and django . here i try to Common Table class for most of my models to reuse . but i could not find rendering table in template table.py class Table(tables.Table): def __init__(self, *args, **kwargs): delurl = kwargs.pop("delurl") editurl = kwargs.pop("editurl") flist = kwargs.pop("flist") modelname = kwargs.pop("modelname") super(Table, self).__init__(*args, **kwargs) self.delurl = delurl self.editurl = editurl self.flist = flist self.modelname = modelname class Meta: model = self.modelname fields = self.flist template_name = 'django_tables2/bootstrap4.html' attrs = { 'class': 'table table-bordered table-striped', 'thead' : { 'class': 'head-dark' }, 'id':"bstable1" } views.py @login_required(login_url="/login/") def Group_list(request): delurl = 'group_delete' editurl ='group_edit' modelname = GroupCode flist = ( 'Group_code' , 'Group_name' , 'Class_code') table = Table(GroupCode.objects.all(),delurl = delurl , editurl=editurl , modelname = modelname , flist = flist) # prefix specified export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("YearTerm.{}".format(export_format)) page_template = 'SMS/table_list.html' context = { 'title': "Group Code List", 'add_url' : 'group_insert', 'table': table, } return render(request, page_template , context) -
Django rest - rearrange the nested structure
Does django-rest framework support rearrange of models structure? I'm using the following set of models: class Blog(models.Model): name = models.CharField(max_length=255) posts = models.ForeignKey( "posts.PostsSnapshot", on_delete=models.SET_NULL, null=True, blank=True ) class PostsSnapshot(models.Model): created_at = models.DateTimeField(auto_now_add=True) class Post(models.Model): snapshot = models.ForeignKey(PostsSnapshot, on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=255) content = models.TextField() And I'm relying on ModelSerializer to provide REST access to this data: class BlogSerializer(serializers.ModelSerializer): posts = PostsSerializer() class Meta: model = Blog fields = '__all__' depth = 2 class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['title', 'content'] class PostsSerializer(serializers.ModelSerializer): posts = PostsSerializer(many=True) class Meta: model = PostsSnapshot fields = ['created_at', 'posts'] depth = 2 And due to that, I've got "too" nested JSON response: "posts": { "created_at": "2021-06-13T11:53:29.345951Z", "posts": [ ... ] Is it possible to move the nested post data one level up? I'd like to replace the PostsSnapshotSerializer data with PostsSerializer data (but they have to be limited to this single snapshot).