Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to make the transition from one post to another and back
There is a model and posts attached to it. I can not figure out how to make the transition from one post to the next and back. I read many articles, but I did not find a suitable one for myself. Here is my code. How can this be done? Where did I make a mistake and how can I fix it? http://127.0.0.1:8000/seasons/season-1/episode-2 NoReverseMatch at /seasons/season-1/episode-2 NoReverseMatch at Reverse for 'episode-detail' with arguments '('', 'episode-1')' not found. 1 pattern(s) tried: ['seasons/(?P<seasonpost_slug>[-a-zA-Z0-9_]+)/(?P<episodepost_slug>[-a-zA-Z0-9_]+)\Z'] Error during template rendering previous return render(request, 'content/episode.html', { … Local vars current_episode <episode: episode-2> episodepost <QuerySet [<episode: episode-2>]> episodepost_slug 'episode-2' next_episode <episode: episode-3> previous_episode <episode: episode-1> request <WSGIRequest: GET '/seasons/season-1/episode-2'> seasonpost_slug 'season-1' class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) Views def ContentHome(request): homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/home.html',{ 'season_menu':season_menu, 'home':homepages, 'season':seasonpages}) def ContentSeasons(request): seasonspages=seasons.objects.all() homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/seasons.html',{ 'season_menu':season_menu, 'home':homepages, 'seasons':seasonspages, 'season':seasonpages}) def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) … -
has_perm method gives False even if user has pemission
I added permission <Permission: blog | post | Can add post> to a user vía shell. It worked because in admin site it is added. Nevertheless when I run below methods in a shell it shows no permission was added. user2.get_user_permissions() -> set() user2.has_perm('blog.add_post') -> False -
How to change the id in django template of a ModelMultipleChoiceField form
i have a django form with ModelMultipleChoiceField <div class="form-group"> {{ form.contracts|as_crispy_field }} </div> For example, i have 4 contract instances in django. In django template the ids for the contracts are rendered: id=id_contracts_0 id=id_contracts_1 id=id_contracts_2 id=id_contracts_3 Now i want to set the checkbox to true if criteria is True. In template iam getting a dictionary {"id", 67} from a calendar. What is want? I want to change the id of the contracts in template, for exameple i want to change the id= id_contracts_3 to the value of the dictionary so, id=id_contracts_67 This has to be done in the template, so jquery of javascript. -
Validation errors when trying to unlink a related model in Django admin inline?
In my Django project I have the following models: TreatUser, Customer and Stakeholder: from django.db import models class UserType(models.Model): name = models.CharField(max_length=20) class Meta: app_label = 'users' def __str__(self): return self.name def __repr__(self): return self.name class TreatUser(AbstractUser): # remove the username from our model username = None email = models.EmailField(unique=True) user_type = models.ForeignKey( UserType, on_delete=models.CASCADE, related_name='users', ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = TreatUserManager() class Meta: app_label = 'users' def __str__(self): return self.email def __repr__(self): return self.email class Stakeholder(models.Model): stakeholder_id = models.CharField(max_length=50, unique=True) user = models.OneToOneField( TreatUser, on_delete=models.CASCADE, ) class Meta: app_label = 'users' def __str__(self): return self.user.email def __repr__(self): return self.user.email class Customer(models.Model): user = models.OneToOneField( TreatUser, on_delete=models.CASCADE, ) stakeholder = models.ForeignKey( Stakeholder, on_delete=models.SET_NULL, related_name='customers', null=True, blank=True, ) class Meta: app_label = 'users' def __str__(self): return self.user.email def __repr__(self): return self.user.email I have an apparently a super-easy scenario for my models workflow: Stakeholder and Customer should be linked to only one TreatUser; Multiple Customers can be linked to the same Stakeholder; I've created the admin models for the above as follows: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from users.models import TreatUser, UserType, Stakeholder, Customer @admin.register(TreatUser) class TreatUserAdmin(UserAdmin): list_display = ('email', 'user_type', 'is_staff', 'is_active',) list_filter = … -
How to retrieve data from an SQL database stored in Azure with a Django WebApp (both in the same Azure resource group)?
I am trying to develop a WebApp for my company where the users can visualize data that is stored in an SQL SERVER database in Azure using a Django webapp. I have been using pyodbc in the past to send the queries and retrieve the required data but was wondering if there was a better way like adding a REST API to the SQL DB or directly setting the DB as part of the Django databases. Both the Django WebApp and the SQL DB are in the same Azure resource group. Thanks for your help. -
Cannot use 'git push' on pythonanywhere fatal: Authentication failed for 'https://github.com/yashtank09/mystie.git/'
After using this command. git push I having error like this in my pythonanywhere console: remote: Support for password authentication was removed on August 13, 2021. remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication. fatal: Authentication failed for 'https://github.com/yashtank09/mystie.git/' -
Get response from PayPal buttton in django
I have integrated PayPal buttons into my project. I am sharing my code here for PayPal Buttons. <script src="https://www.paypal.com/sdk/js?client-id=MyClientID&currency=USD" data-sdk-integration-source="button-factory"></script> <script> function initPayPalButton() { paypal .Buttons({ style: { shape: "rect", color: "blue", layout: "horizontal", label: "buynow", }, createOrder: function (data, actions) { return actions.order.create({ purchase_units: [{amount: {currency_code: "USD", value: totalAmount}}], }); }, onApprove: function (data, actions) { return actions.order.capture().then(function (orderData) { // Full available details console.log("Capture result", orderData, JSON.stringify(orderData, null, 2)); // Show a success message within this page, e.g. const element = document.getElementById("paypal-button-container"); element.innerHTML = ""; element.innerHTML = "<h3>Thank you for your payment!</h3>"; // Or go to another URL: actions.redirect('thank_you.html'); }); }, onError: function (err) { console.log(err); }, }) .render("#paypal-button-container"); } initPayPalButton(); </script> <div class="paypalButton-mainDiv"> <div id="smart-button-container"> <div style="text-align: center"> <div id="paypal-button-container"></div> </div> </div> </div> But I am not able to get the response back from this code after Payment. I need to get the response and want to store it in my database. -
Django Reverse for '...' with arguments '('', '...')' not found. 1 pattern(s) tried:
Help is needed. I have tried many solutions, but nothing works. Always one mistake. Please help me solve the problem. http://127.0.0.1:8000/seasons/season-1/episode-2 NoReverseMatch at Reverse for 'episode-detail' with arguments '('', 'episode-1')' not found. 1 pattern(s) tried: ['seasons/(?P<seasonpost_slug>[-a-zA-Z0-9_]+)/(?P<episodepost_slug>[-a-zA-Z0-9_]+)\Z'] Error during template rendering previous return render(request, 'content/episode.html', { … Local vars current_episode <episode: episode-2> episodepost <QuerySet [<episode: episode-2>]> episodepost_slug 'episode-2' next_episode <episode: episode-3> previous_episode <episode: episode-1> request <WSGIRequest: GET '/seasons/season-1/episode-2'> seasonpost_slug 'season-1' class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) Views def ContentHome(request): homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/home.html',{ 'season_menu':season_menu, 'home':homepages, 'season':seasonpages}) def ContentSeasons(request): seasonspages=seasons.objects.all() homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/seasons.html',{ 'season_menu':season_menu, 'home':homepages, 'seasons':seasonspages, 'season':seasonpages}) def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'home':homepages, 'seasons':seasonspages, 'season':seasonpages, 'season_menu':season_menu, 'episode': episodepost,}) def ContentEpisode(request, seasonpost_slug, episodepost_slug): episodepost = episode.objects.filter(slug=episodepost_slug, cat__slug=seasonpost_slug) current_episode = get_object_or_404(episodepost, slug=episodepost_slug, cat__slug=seasonpost_slug) previous_episode = episode.objects.filter(cat__slug=seasonpost_slug, pk__lt=current_episode.pk).first() next_episode = episode.objects.filter(cat__slug=seasonpost_slug, pk__gt=current_episode.pk).first() return render(request, 'content/episode.html', { 'episode': episodepost, 'current_episode': current_episode, 'previous_episode': previous_episode, 'next_episode': next_episode, }) path('', views.ContentHome, … -
Django Test - Not working in GitHub actions
I have 2 Django tests that are working perfectly fine locally but it fails on GitHub actions, this is the code: Models class Empresa(models.Model): name = models.CharField(max_length=120, verbose_name='Razon Social') cuit = models.CharField(max_length=11, validators=[MinLengthValidator(11)]) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.user: user = get_current_user() if user and not user.pk: user = None if not self.pk: self.user = user self.user = user return super().save(force_insert, force_update, using, update_fields) def toJSON(self): item = model_to_dict(self) return item And I try to test: Creation successfully of Empresa -> It works ok Error on creation because of a long name -> It works locally but not on GitHub actions Error on creation because of a long cuit-> It works locally but not on GitHub actions This is the test: class EmpresaTesting(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username='testuser', password='12345') self.user.save() def test_create_empresa_ok(self): this_empresa = Empresa.objects.create(name='Empresa 1', cuit='30999999991', user=self.user) self.assertTrue(isinstance(this_empresa, Empresa)) self.assertEqual(str(this_empresa), 'Empresa 1') def test_create_empresa_long_name(self): long_name = "a" * 121 with self.assertRaisesMessage(DataError, "Data too long for column 'name' at row 1"): Empresa.objects.create(name=long_name, cuit='30999999991', user=self.user) def test_create_empresa_long_cuit(self): with self.assertRaisesMessage(DataError, "Data too long for column 'cuit' at row 1"): Empresa.objects.create(name="Empresa … -
how to insert additional model without losing data stored on mysql
My django app has two model, for example model_A and model_B, and this app could run well on docker. The docker compose is following version: '3.8' services: app: build: ...... volumes: ..... db: image:mysql5.7 volume: ....... nginx: image:.... volumes: volume_mysql: ....... After running the app for a while, I want to add a model, for example model_C on the app, exchanging app container to new one containing model_C. docker-compose stop docker rm app docker rmi app docker-compose up -d --build And makemigrations/migrate process also work without any error message docker exec app python manage.py makemigrations docker exec app python manage.py migrate On the other hand, I did not update the volume_mysql, because volume_mysql contained a lot of important data (I was reluctant to remove the volume, which resulted in loose all data) When I tried accessing model_c (on admin page), however, error_message 1146, "Table 'race_record.result_model_C' doesn't exist" was displayed. I guess it seem to be because volume_mysql is old, having yet to conntain ‘model_c’, although migrate process was done well. So, how to add model_c without losing date stored on mysql -
Add an item with multiple variations to basket in Django
I have a views.py and contexts.py that adds a product with a particular flavour to the basket on my Django site. I have copied this logic from a course I'm on. I now want to be able to have multiple variations on products and add them to my basket. For instance a strength as well as a flavour. Here is my add_product view: def add_to_basket(request, item_id): """ Add a quantity of the specified product to the shopping basket """ product = get_object_or_404(Product, pk=item_id) quantity = int(request.POST.get('quantity')) redirect_url = request.POST.get('redirect_url') flavour = None if 'product_flavour' in request.POST: flavour = request.POST['product_flavour'] strength = None if 'product_strength' in request.POST: strength = request.POST['product_strength'] basket = request.session.get('basket', {}) if flavour: if item_id in list(basket.keys()): if flavour in basket[item_id]['items_by_flavour'].keys(): basket[item_id]['items_by_flavour'][flavour] += quantity messages.success(request, f'Updated {product.name} flavour {flavour.upper()} quantity to {basket[item_id]["items_by_flavour"][flavour]}') else: basket[item_id]['items_by_flavour'][flavour] = quantity messages.success(request, f'Added {product.name} flavour {flavour.upper()} to your basket') else: basket[item_id] = {'items_by_flavour': {flavour: quantity}} messages.success(request, f'Added {product.name} flavour {flavour.upper()} to your basket') else: if item_id in list(basket.keys()): basket[item_id] += quantity messages.success(request, f'Updated {product.name} quantity to {basket[item_id]}') else: basket[item_id] = quantity messages.success(request, f'Added {product.name} to your basket') request.session['basket'] = basket return redirect(redirect_url) Here is my contexts.py that gets back the contents of the … -
How i can upload multiple images in django?
I can't figure out how to upload more than one image in django. models.py : def get_upload_path(self, filename): if isinstance(self, UserProfile): return f'members/{self.user.username}/avatars/{filename}' elif isinstance(self, Apartment): return f'members/{self.author.username}/apartment_pics/{filename}' else: return None class Apartment(models.Model): #---fields---# images = models.ManyToManyField('Image', blank=True) class Image(models.Model): image = models.ImageField(upload_to=get_upload_path) def __str__(self): return self.image.name also the forms.py class ApartmentForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta: model = Apartment fields = ('image',) views.py class ApartmentCreateView(CreateView): model = Apartment form_class = ApartmentForm template_name = 'post_a_room.html' success_url = reverse_lazy('home') def form_valid(self, form): form.instance.author = self.request.user response = super().form_valid(form) for image in self.request.FILES.getlist('images'): Image.objects.create(image=image, apartment=self.object) return response and html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="id_images">Images</label> <input type="file" name="images" id="id_images" class="multifilefield form-control" multiple> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> this method allows me to select more files but it crashes when i hit submit, i get an error : expected str, bytes or os.PathLike object, not NoneType -
How to connect databricks delta tables from Django application
I am new to Django framework, in my project I have requirement that I have to connect to databricks delta tables and perform CRUD operation on it. If we can connect it. I request you to list down the steps please.Thanks. -
Efficient way to continuously consume messages from Redis Streams while being connected to Websockets through Django Channels
I have written a Django application to receive updates of long running tasks. I am using Redis as a channel layer for web-sockets and also making use of Redis Streams to store the updates of the tasks that are currently running. I have spawned a thread from connect method of WebSocket Consumer to run an infinite loop to continuously check for updates from Redis Consumer. This seems to be a hackish solution for what I am trying to achieve i.e. to remain connected to the websocket and also simultaneously receive updates from Redis Streams. This is my code for Websocket Consumer. As you can see, I am running an infinite loop to check for any new messages in the stream through Redis Consumer. import json from threading import Thread from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from django.utils import timezone from redis import ConnectionPool, Redis from redis_streams.consumer import Consumer class ProgressStateConsumer(WebsocketConsumer): def __init__(self): self.task_id = self.task_group_name = None connection_pool = ConnectionPool( host="localhost", port=6379, db=0, decode_responses=True, ) self.redis_connection = Redis(connection_pool=connection_pool) self.messages = [] super().__init__() def connect(self): task_id = self.scope["url_route"]["kwargs"]["task_id"] self.task_id = task_id self.stream = f"task:{self.task_id}" self.task_group_name = ( f"task-{self.task_id}-{round(timezone.now().timestamp())}" ) async_to_sync(self.channel_layer.group_add)( self.task_group_name, self.channel_name ) thread = Thread(target=self.send_status) thread.start() self.accept() def … -
How can I get index of list in django template
I have 3 list item1,item2,item3 views.py context={'item0': region.objects.all(), 'item1': [1,2,3,4,5,6,7,8,9,10], 'item2': ['one', 'two','three','four', 'five'], 'item3': ['six', 'seven','eight','nine','ten'], 'item4': "test", 'item5': 5, 'item6': range(5), } return render(request, 'btscreate.html', context ) I tried get in template 1) {% for num in item1 %} <td> {{ num }} </td> # this work <td> {{ how can I get values item2 and item3 ? }} </td> {% endfor %} {% for num in item6 %} <td> {{ item2.0 }} </td> # that work <td> {{ item2.num }} </td> # but that doesn't work {% endfor %} how can I get values item2 and item3 ? -
django-channels - group send does not call the function defined in "type"
I have this Consumer: class TableConsumer(AsyncWebsocketConsumer): async def connect(self): self.table_name = f'table_test' self.channel_name = f'channel_test' await self.accept() await self.channel_layer.group_add( self.table_name, self.channel_name ) await self.manage_new_game_video() async def manage_new_game_video(self): await self.channel_layer.group_send( self.table_name, {"type": "chat_message", "message": "message"} ) # Receive message from room group async def chat_message(self, event): print("test") message = event["message"] # Send message to WebSocket await self.send(text_data=json.dumps({"message": message})) for some reason, the print statement is never executed and I don't understand why. Why can that happen? Thanks. -
Django Could not parse the remainder: ',' from 'previous
Help is needed. I have tried many solutions, but nothing works. Always one mistake. Please help me solve the problem. TemplateSyntaxError Could not parse the remainder: ',' from 'previous_episode.seasonpost.slug,' previous return render(request, 'content/episode.html', { … Local vars current_episode <episode: episode-2> episodepost <QuerySet [<episode: episode-2>]> episodepost_slug 'episode-2' next_episode <episode: episode-3> previous_episode <episode: episode-1> request <WSGIRequest: GET '/seasons/season-1/episode-2'> seasonpost_slug 'season-1' Models class home(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug class seasons(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) Views def ContentHome(request): homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/home.html',{ 'season_menu':season_menu, 'home':homepages, 'season':seasonpages}) def ContentSeasons(request): seasonspages=seasons.objects.all() homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/seasons.html',{ 'season_menu':season_menu, 'home':homepages, 'seasons':seasonspages, 'season':seasonpages}) def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'home':homepages, 'seasons':seasonspages, 'season':seasonpages, 'season_menu':season_menu, 'episode': episodepost,}) def ContentEpisode(request, seasonpost_slug, episodepost_slug): episodepost = episode.objects.filter(slug=episodepost_slug, cat__slug=seasonpost_slug) current_episode = get_object_or_404(episodepost, slug=episodepost_slug, cat__slug=seasonpost_slug) previous_episode = episode.objects.filter(cat__slug=seasonpost_slug, pk__lt=current_episode.pk).first() next_episode = episode.objects.filter(cat__slug=seasonpost_slug, … -
How to re-deploy Django changes in linux
My application is up and running on my server. I'm using linux Nginx and Gunicorn. I'm logging in to the server using ssh with private key. My question is how do I re-deploy updated version of the application? My first attempt was cloning the project from my git repository into a directory on my server. Cloning it again doesn't seem like a good option. -
The row in table 'owl_course' with primary key '1' has an invalid foreign key
The total error is raise IntegrityError( django.db.utils.IntegrityError: The row in table 'owl_course' with primary key '1' has an invalid foreign key: owl_course.subject_id contains a value 'math' that does not have a corresponding value in owl_subject.id. I have a model Course: class Course(models.Model): id = models.CharField(max_length=7, primary_key=True) name = models.CharField(max_length=16, default="") teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True) students = models.ManyToManyField(Student) staff = models.ForeignKey(Staff, on_delete=models.SET_NULL, null=True) startDate = models.DateTimeField(blank=True, null = True) endDate = models.DateTimeField(blank=True, null = True) student_number = models.IntegerField(_("student_number"), blank=True, default=0) subject= models.CharField(max_length=14, default = "") Originally, the attribute subject is just a Charfield. But later I changed it into a foregin key. school =models.ForeignKey(School, on_delete = models.SET_NULL, null=True); And then I run migration and migrate. But the stupid error msg pop out. And error can't be fixed even I change fiedl back to Charfield. Why django orm works so stupid? How can I address this? -
Django: Is it a good idea to have two caches on one memcached instance?
I would like to have two caches with different timeouts on one memcached instance in my django 3 instance: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'CACHE_KEY_PREFIX': 'default_cache', 'TIMEOUT': 300, }, 'custom': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'CACHE_KEY_PREFIX': 'custom_cache', 'TIMEOUT': 3600 * 24, }, } I did not find an example which does this, so I`m not sure if something could go wrong with this. What do you think? Could there e.g. be a problem with django["cachename"].clear() command? -
proper way to import django base settings in production settings
I have seen alot of articles and videos about the best practices when it comes to managing django settings file. And almost of them talks about having a base settings base_settings.py and then environment settings, like development_settings.py, production_settings.py etc. usually in the dev and prod settings the base setting is imported into it like from project.settings.base import * I have also read that import * is a bad practice, so the question is WHAT IS THE RIGHT WAY TO IMPORT THE SETTINGS WITHOUT MESSING UP THE NAMESPACE. One of the warnings I get when running my test with pytest is the namespace warning, which I presume come from the * import see warning below when I run pytest ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804 C:\Users\seven\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804: DeprecationWarning: Deprecated call to `pkg_resources.declare_namespace('ruamel')`. Implementing implicit namespace packages (as specified in PEP 420) is preferred to `pkg_resources.declare_namespace`. See https://setuptools.pypa.io/en/latest/references/keywords.html#keyword-namespace-packages declare_namespace(pkg) ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804 ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804 C:\Users\seven\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804: DeprecationWarning: Deprecated call to `pkg_resources.declare_namespace('zope')`. Implementing implicit namespace packages (as specified in PEP 420) is preferred to `pkg_resources.declare_namespace`. See https://setuptools.pypa.io/en/latest/references/keywords.html#keyword-namespace-packages declare_namespace(pkg) ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\coreapi\codecs\download.py:5 C:\Users\seven\Miniconda3\envs\salary\Lib\site-packages\coreapi\codecs\download.py:5: DeprecationWarning: 'cgi' is deprecated and slated for removal in Python 3.13 import cgi -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html I don't exactly know what is raising these warnings but it goes away when I remove the … -
django strawberry query choice field values
I am using strawberry graphql for my project. I have a form field where I need to show options from my choice fields. I have a model like class Product(models.Model): REQUIREMENT_CHOICES = ( ("N", "New"), ("O", "Old"), ("M", "Maintained"), ) requirement = models.CharField( max_length=50, choices=REQUIREMENT_CHOICES, blank=True, ) Here in my graphql query how can I query REQUIREMENT_CHOICES without without making custom query to handle this. django-graphene would give options query easily. How could I do this in strawberry ? -
setting up Celery with RabbitMQ
I'm trying to set up Celery (5.2.7) with RabbitMQ (3.8.19) (Django 4.1.5) As a result, the task appears in the “celery” queue with the “Unacked” status, and after 30 minutes it goes into the “Ready” status with a message. "amqp.exceptions.PreconditionFailed: (0, 0): (406) PRECONDITION_FAILED - delivery acknowledgement on channel 1 timed out. Timeout value used: 1800000 ms. This timeout value can be configured, see consumers doc guide to learn more" When calling the method directly (without .delay), everything works correctly. I have no idea what is configured incorrectly running celery: $ celery -A mylocal worker -l info -------------- celery@DEV2 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-1 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: mylocal:0x18205ade830 - ** ---------- .> transport: amqp://<RMQLogin>:**@<RMQ_HOST>:<RMQ_PORT>/<RMQ_VIRTUAL_HOST> - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 12 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . myapp.tasks.send_spam_email Project structure: mylocal | -mylocal | - init.py - celery.py - settings.py -myapp | - templates | - myapp | - celery.html - admin.py - forms.py - models.py - … -
How to fix pg_dump: error: server version: 14.2; pg_dump version: 13.9 (Debian 13.9-0+deb11u1), but my db service can't down version
I use dbbackup. When I call python manage.py dbbackup I have error: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/utils.py", line 118, in wrapper func(*args, **kwargs) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/management/commands/dbbackup.py", line 61, in handle self._save_new_backup(database) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/management/commands/dbbackup.py", line 74, in _save_new_backup outputfile = self.connector.create_dump() File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/base.py", line 78, in create_dump dump = self._create_dump() File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/postgresql.py", line 38, in _create_dump stdout, stderr = self.run_command(cmd, env=self.dump_env) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/postgresql.py", line 21, in run_command return super(PgDumpConnector, self).run_command(*args, **kwargs) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/base.py", line 150, in run_command raise exceptions.CommandConnectorError( dbbackup.db.exceptions.CommandConnectorError: Error running: pg_dump --host=db --port=5432 --username=postgres --no-password --clean postgres pg_dump: error: server version: 14.2; pg_dump version: 13.9 (Debian 13.9-0+deb11u1) pg_dump: error: aborting because of server version mismatch I understand that: my service use postgres 14.2 and my client use postgres 13. But I can't downgrade my service version, and my client just install version 13.9 (it is hightest) -
How do I embed a QR scanner pop-out upon clicking the QR camera icon?
I am trying to get a UI dialog window to display a QR code scanner upon clicking on the icon button for that corresponding row. Currently, when I click on the icon, nothing happens. I am unsure of how to display the QR scanner in the form of a dialog box. I am relatively new to element-ui and would greatly appreciate any inputs. {% block mainbody %} {% verbatim %} <div id="app2" class="container"> <div class="emr-table"> <el-table ref="multipleTable" :data="list" stripe style="width: 50%" @row-click="handle" @selection-change="handleSelectionChange"> <el-table-column prop="id" label="Index"> </el-table-column> <el-table-column prop="order_id" label="Order ID"> </el-table-column> <el-table-column prop="ward_number" label="Ward No."> </el-table-column> <el-table-column prop="qr" label="QR"> <template slot-scope="scope"> <el-button size="mini" type="warning" icon="el-icon-camera" circle @click="launchQR(scope.row)"> </el-button> </template> </el-table-column> </el-table> </div> </div> {% endverbatim %} <script> new Vue({ el: '#app2', data() { return { list: [] } }, mounted() { this.getemrList() }, methods: { getemrList() { // Obtain EMR list axios.post(ToDJ('emrList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, // Success notification NotifySuc(str) { this.$message({ message: str, type: 'success' }) }, // Error notification NotifyFail(str) { this.$message({ message: str, type: 'warning' }) } } }) </script> {% endblock %}