Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-storages[azure]: NotImplementedError: This backend doesn't support absolute paths
I have Django application with celery task that I am trying to run on Azure using the code from below. The main goal is to read python, yaml and template files when running celery task. I am getting the following error: NotImplementedError: This backend doesn't support absolute paths. I am using django-filer and django-storages[azure] to handle my media files and I use Azure Storage to store all my files. My model looks like this: class Mymodel(models.Model): ... id_config_file = FilerFileField(null=True, blank=True, related_name="spider_config_file", on_delete=models.CASCADE) yaml_config_file = FilerFileField(null=True, blank=True, related_name="yaml_config_file", on_delete=models.CASCADE) template_file = FilerFileField(null=True, blank=True, related_name="template_file", on_delete=models.CASCADE) Below is my celery task: @shared_task(name="schedule_test") def schedule_test(id): id = Mymodel.objects.get(id=id) id_config_file = id.id_config_file.file yaml_config_file = id.yaml_config_file.file template_file = id.template_file.file id_config_file_path = os.path.join(MEDIA_URL, f"{id_config_file}") yaml_config_file_path = os.path.join(MEDIA_URL, f"{yaml_config_file}") template_file_path = os.path.join(MEDIA_URL, f"{template_file}") spec = importlib.util.spec_from_file_location("id", id_config_file_path) id_module = importlib.util.module_from_spec(spec) sys.modules["id"] = id_module spec.loader.exec_module(id_module) asyncio.run(id_module.run( yaml_config_path = yaml_config_file_path, input_file_path = template_file_path, task_id = schedule_test.request.id )) return f"[id: {id}]" My settings.py contains Azure Storage config variables: DEFAULT_FILE_STORAGE = 'azure.storage_production.AzureMediaStorage' AZURE_ACCOUNT_NAME = os.environ.get('AZURE_ACCOUNT_NAME') AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/media/' Here is what I tried to implement but with no success: id_config_file_path = os.path.join(MEDIA_URL, f"{id_config_file}") id_config_file_path = f"{MEDIA_URL}{id_config_file}" id_config_file_path = f"{MEDIA_URL}{id_config_file.path}" id_config_file_path = f"{MEDIA_URL}{id_config_file.url}" id_config_file_path = f"{MEDIA_URL}{id_config_file.file}" Question How … -
How to access "context" from http request between two django apps
So i'm fairly new to django, html, and javascript. In my first app, I have a button that when I click it, it invokes an $.ajax type "GET" function. In the script of the html template of app1, I have the following: $('#btn_to_app2').click(function () { if(Object.keys(name).length > 0){ $.ajax( { type:"GET", url:"to_app2", data:{ 'name': JSON.stringify(name), 'place': JSON.stringify(place), }, success: function (data) { if(data["noted"] == 1){ window.location.href = "http://" + window.location.host + "/app2/"; } } } ) } The accessed url refers to a view function (defined in the url.py and views.py files of the corresponding app1). def to_app2(request): if request.is_ajax() and request.method == 'GET': name = json.loads(request.GET['name']) request.session['name'] = name place = json.loads(request.GET['place']) request.session['place'] = place return JsonResponse({ 'noted': 1, }) The data obtained is send to the next app using a http request. In the views.py file of app2, I have the following bit of code: def app2(request): context = { 'name': request.session['name'], 'place': request.session['place'] } return render(request, 'app2.html', context) How can I now access the information contained in the "context" variable within the script of the html-file of app2? I have tried the let name = {{ name | safe }}; framework, with quotes and without, but that … -
Django, legacy PostgreSQL database, multiple primary keys
I suppose that question as old as it possibly could be, but I still have a hope that maybe someone has found some magical solution. Everything is simple, I have a database (postgresql) with small table as an example, with already existing field with Primary key: enter image description here My goal is to add an ID field as a second primary key. My Model looks like this: class CdcConn(models.Model): id = models.BigAutoField(primary_key=True) conn_type = models.CharField(max_length=128, blank=True, null=True) conn_name = models.CharField(max_length=128) class Meta: managed = True db_table = 'cdc_conn' After migration the result output is: django.db.utils.ProgrammingError: multiple primary keys for table "cdc_conn" are not allowed Tried many options, unique_together, constraints, some additional modules such as django-viewflow, and so on. The issue is about 15 years old, documentation says that composite pk are not allowed, but still, I can't believe that such powerful tool as Django just can't handle that simple operation. Any thoughts would be highly appreciated. -
deleting a user model that extends abstractuser
I am trying to delete a user object that belongs to a User class that extends AbstractUser. The extending class looks something like this: class User(AbstractUser): name = CharField("Name", blank=True, max_length=255) def __str__(self): return self.username When I try to delete a user like this: user = User.objects.get(pk=self.user_id) user.delete() The user object is not deleted (at least from checking the user table in the database). Other models that have on_delete=models.CASCADE to my custom user class are deleted as expected but the actual user object is NOT deleted. When I try user = User.objects.get(pk=self.user_id) user.delete() user.delete() # adding extra delete() i.e. an extra user.delete(), then the user object is deleted, but also raises an exception (which is not unexpected) User object can't be deleted because its id attribute is set to None. but the user object along with other objects with FK relationship to the User class are deleted (as expected). Sounds like the object was "deleted" the first time I called user.delete()? But I can still see the row in my user's table. Not sure if related but, I see that the type of User to delete is <class 'django.utils.functional.SimpleLazyObject'> not the User model class. So, I'm trying to delete a … -
How to display the raw value of my queryset
I have this function, to show my querysets: funcionarios_aniver = FuncionarioAux.objects.filter(FuncionarioDataNasc__gte=dia_um, FuncionarioDataNasc__lte=ultimo_dia) But it returns the querysets in an array, for example: <QuerySet [<FuncionarioAux: Alberto Santos>, <FuncionarioAux: Josney Arman>]> I would like it to return the raw values, like: Alberto Santos, Josney Arman I already tried using .get() at the end of the function, but I got the following error: funcionarios.models.FuncionarioAux.MultipleObjectsReturned: get() returned more than one FuncionarioAux -- it returned 2! what can i do to resolve? -
UsercreationForm to check if email exists in database django
I've created a usercreationform and try to check if username and email is already exist in database or not. Here It only check for email if it is exist or not but it cannot check for the username. Views.py from django.shortcuts import render,redirect from . forms import signupform from django.contrib import messages from django.contrib.auth import login,authenticate,logout from django.contrib.auth.models import User def signup_data(request): form = signupform(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(username=username).exists(): messages.error(request,'Username is already taken') return redirect('signup') elif User.objects.filter(email=email).exists(): messages.error(request,'Email is already taken') return redirect('signup') else: form.save() messages.success(request,'Account Is Created') return redirect('signup') return render(request,'login_module/signup.html',{'form':form, 'message': messages}) Forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class signupform(UserCreationForm): username= forms.CharField(max_length=10,widget=forms.TextInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(max_length=20,widget=forms.EmailInput(attrs={'class': 'form-control'})) password1 = forms.CharField(label="Password",widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(label="Confirm Password",widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username','first_name','last_name','email','password1','password2'] -
Is there a way to use get_F00_display in parallel with values() in Django views.py
What I want to do : Display the human readable value of a charfield with choices via get_F00_display or other in views.py and then in template. models.py class Leave(CommonFields): LEAVES_TYPES = [ ('10', _('Type 1')), ('20', _('Type 2')), ('30', _('Type 3')), ] owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) type = models.CharField(max_length=3, choices=LEAVES_TYPES, null=True, default="10") def __str__(self): return self.owner.first_name + " " + self.owner.last_name + " : du " + self.begin_date.strftime("%d-%m-%Y") + " au " + self.end_date.strftime("%d-%m-%Y") views.py def get_queryset(self): return Leave.objects.filter(is_active=True).values('type', 'begin_date','end_date','range','comment','status') leave_list.html <td>{{leave.type}}</td> BUT : I want to return {{leave.get_type_display}} and at the same time Leave.objects.filter(is_active=True).**values**(...) How to ? Is there a better way to achieve this ? -
How to prevent storage of celery chord counter objects in database
I am experiencing an issue where the django_celery_results_chordcounter table is filling up fast making me run out of server space. It was growing from a few MBs to over 99GB. I have tried resolving this by setting CELERY_RESULT_EXPIRE=60 hoping that the celery backend cleanup task will help me clean up the table every minute but that was not happening. I ran the task and by the time the table had grown to about 7GB, I truncated it on the psql shell. This is definitely not a solution but I had to do this so that the task can be successful without increasing server resources. Here are the celery tasks leading to this problem. Items can be hundreds of thousands to millions. Server specs: 16vCPUs, 64GiB memory @celery_app.task(ignore_result=True) def get_for_one(item_id): # an IO-bound task pass @celery_app.task(ignore_result=True) def get_for_many(parent_id): tasks = [ group( get_for_one.s(item.id) for item in Item.objects.filter( owner__isnull=True, parent_id=parent_id ).iterator() ) ] chord(tasks)(get_for_many_callback.si(parent_id)) celery==5.2.7 Django==4.1.1 django-celery-beat==2.4.0 django-celery-results==2.4.0 -
django project - how to combine two different types of databases (sqlite3 into mssql)
I took over an unfinished project from someone else and built a new user system based on Django authentication syste. It is when everything is done I found out that the system was connected to the default sqlite3 db while everything else was connected to mssql... setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'nlp_db': { 'ENGINE': 'mssql', 'HOST': 'DESKTOP', 'PORT': '1433', 'NAME': 'my_db', 'USER': 'guest', 'PASSWORD': 'password', 'OPTIONS': { 'driver': 'ODBC Driver 18 for SQL Server', }, }, } Anybody know how to combine the sqlite3 into the mssql? I have tried Django : Transfer data from Sqlite to another database and changed the setting.py to the codes below but got an error(seems not compatible) DATABASES = { 'default': { 'ENGINE': 'mssql', 'HOST': 'DESKTOP', 'PORT': '1433', 'NAME': 'my_db', 'USER': 'guest', 'PASSWORD': 'password', }, } Error Msg pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] Cannot insert the value NULL into column 'name', table 'my_db.dbo.django_content_type'; column does not allow nulls. INSERT fails. (515) my_db.dbo.django_content_type is a table already existed before in mssql db but empty. I don't know how to fix this or should I delete my_db.dbo.django_content_type? Anyone has any idea? Thanks in advance! -
Django: Count forloop.first only if a second if condition is met
I have the following (oversimplified example): {% for item in myitems %} {% if item == "orange" %} {% if forloop.first %} {{item}} {% endif %} {% endif %} {% endfor %} Let's say that my list myitems is ['apple','orange','watermelon']. The first loop will be item=apple so it won't print the item because it is not "orange". In the second loop now we have item=orange but it no longer fulfills if forloop.first` so it won't print the item. I want a forloop.first that print only if it fulfills getting inside the if orange condition. How can I achieve this? -
Django queryset to list of ids with integer values
I need to retrieve IDs from multiple queries and add them into a list. products = Product.objects.filter(category="Apple").values_list("product_id", flat=True) reviewed = Reviews.objects.filter(category="Apple").values_list("product_id", flat=True) selected_ids = [10,20,30] Then I tried all_products = selected_ids + products + reviewed This raised error as list cannot be added to queryset. so, I tried, all_product_ids = selected_ids + list(products) + list(reviewed) This works but, all_products has a mix of int and tuple values [10, 20, 30, (2,), (2,), (1,)] I need them to be [10, 20, 30, 2, 2, 1] -
celery 'function' object has no attribute 'delay' how to get return value after delay?
Hi I have a problem in getting async function return value. this is my views.py code def preprocess_log2(request,uuid): data = get_object_or_404(Adata, uuid=uuid) if request.method == "POST": result = log2_transform_task.delay(data.raw_path) test = result.get() data.mat_data = test data.save() return redirect("raptorlite:home") return render(request, 'raptorlite/detail.html',{"data":data}) this is my task code @shared_task def log2_transform_task(raw:str, out_dir = None) -> str: return out_name sorry for not uploading my source code but I checked result it work perfectly and it is my settings.py CELERY_BROKER_URL = 'redis://redis:6379/0' result_extended = True accept_content = ['application/json'] result_serializer = 'json' task_serializer = 'json' timezone = 'Asia/Seoul' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' enter image description here when I run code if not use result.get() it works well but I want to get return value so I followed celery docs however after using get to return value suddenly that error happended.. please help me.. I followed celery docs and I read about similar error case in here but I checked that function name do not duplicate -
Why my "friends_list" remains empty when my Django signal is triggered?
I am using a Django post_save signal to modify the Database content of Budget. In my response I get the friendsList filled with the user IDs, but when I use post_save signals and query and store it in friends_list I see that the list remains empty. My response: { "id": 5, "amount": 100, "budgetForSplitPay": 1, "friendsList": [ 2, 3 ] } My post_save signal code: @receiver(post_save, sender=SplitPayBudget) def post_save_splitpay_amount(sender, instance, created, **kwargs): Budget.objects.filter(user=instance.budgetForSplitPay.user).update(budgetofUser=F('budgetofUser') - instance.amount) friends_list = instance.friendsList.all() for friend in friends_list: Budget.objects.filter(user=friend.user).update(budgetofUser=F('budgetofUser') - instance.amount) My API call body which triggers this signal: { "budgetForSplitPay": "1", "amount": 100, "friendsList": [2, 3] } I want a solutions by which my friends_list should be initialised with [2, 3]. Thank You. I tried using friends_list = instance.friendsList.all() but the instance.friendsList.all() remains empty. -
Django create update form with pre filled data from database
Django create update form with pre filled data from database but custome html form i have attaced the vire, model and the html templet that i used insted of django form view.py i used this view for adding player def add_player (request): if request.method=='POST': Name=request.POST.get('Name') E_mail=request.POST.get('E_mail') Area_code = request.POST.get('Area_code', False) Phone_Number = request.POST.get('Phone_Number', False) Country = request.POST.get('Country', False) City = request.POST.get('City', False) State = request.POST.get('State', False) Zip_Code = request.POST.get('Zip_Code', False) Address = request.POST.get('Address', False) FIG_License_Number = request.POST.get('FIG_License_Number', False) Passport_Number = request.POST.get('Passport_Number', False) add_player= contact.objects.create(Name=Name,E_mail=E_mail,Area_code=Area_code, Phone_Number=Phone_Number, Country=Country, City=City, State=State, Zip_Code=Zip_Code, Address=Address, FIG_License_Number=FIG_License_Number, Passport_Number=Passport_Number) add_player.save() return redirect('/contact') else: pass return render(request, 'from/add_player.html') model.py class contact (models.Model): Name =models.CharField(max_length=200, null=False) E_mail =models.EmailField(max_length=200, null=True) Area_code =models.CharField(max_length=200, null=True) Phone_Number =models.CharField(max_length=200, null=True) Country =models.CharField(max_length=200, null= False) City =models.CharField(max_length=200, null= False) State =models.CharField(max_length=200, null= False) Zip_Code =models.CharField(max_length=200, null= False) Address =models.CharField(max_length=200, null= False) FIG_License_Number =models.CharField(max_length=200, null= False) Passport_Number =models.CharField(max_length=200, null= False) def __str__(self): return self.Name -
__init__() got multiple values for argument 'user'
I have a form, model and view and trying to show ModelChoiceField with filters I wrote an init in my forms.py but when im trying to submit my form on html page i got an error: "init() got multiple values for argument 'user' " forms.py class WorkLogForm(forms.ModelForm): worklog_date = forms.DateField(label='Дата', widget=forms.DateInput( attrs={'class': 'form-control', 'placeholder': 'Введите дату'})) author = forms.EmailField(label='Автор', widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email автора'})) contractor_counter = forms.ModelChoiceField(queryset=CounterParty.objects.none()) contractor_object = forms.ModelChoiceField(queryset=ObjectList.objects.none()) contractor_section = forms.ModelChoiceField(queryset=SectionList.objects.none()) description = forms.CharField(label='Описание', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Описание'})) def __init__(self, user, *args, **kwargs): super(WorkLogForm, self).__init__(*args, **kwargs) counter_queryset = CounterParty.objects.filter(counter_user=user) object_queryset = ObjectList.objects.filter( Q(customer_guid__in=counter_queryset) | Q(contractor_guid__in=counter_queryset)) section_queryset = SectionList.objects.filter(object__in=object_queryset) self.fields['contractor_counter'].queryset = counter_queryset self.fields['contractor_object'].queryset = object_queryset self.fields['contractor_section'].queryset = section_queryset class Meta: model = WorkLog fields = ( 'worklog_date', 'author', 'contractor_counter', 'contractor_object', 'contractor_section', 'description') views.py def create_work_log(request): if request.method == 'POST': form = WorkLogForm(request.POST, user=request.user) if form.is_valid(): form.author = request.user work_log = form.save() return render(request, 'common/home.html') else: form = WorkLogForm(user=request.user) return render(request, 'contractor/create_work_log.html', {'form': form}) -
Is there any ads network or Traffic attaining of my courses website usmanghias.com
CodewithUsman CodewithUsman I've started 26 courses on my website from whom 3 are accomplished one with proper certificate and YouTube channel Videos are attached. Features of Courses: Detailed Documentation Android Application(Mobile Responsive) GitHub Codes My YouTube (Explained) Videos along with Quizez Forum Posts to ask questions from community Extra Features: News Blogs Projects Shop I've all these features but my course website is not growing well please suggest me what should I do. I want to monitize my website as well but google is not accepting I want to get more monitizatoin networds and get more audience -
"detail": "Authentication credentials were not provided." to admin
I have my token for admin, the booking entries is allowed in Insomnia but would not be allowed DRF display. I am missing something please? Is there way to provide the token for it to be allowed? #view.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from rest_framework import viewsets from .models import Booking, Menu from .serializers import BookingSerializer, MenuSerializer, UserSerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication from rest_framework import generics from datetime import datetime from django.views.decorators.csrf import csrf_exempt from django.db.models import Sum from django.contrib import messages def home(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') class UserRegistrationView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class BookingViewSet(viewsets.ModelViewSet): queryset = Booking.objects.all() serializer_class = BookingSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] settings.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASS': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } -
Django Templates with Vue
I'm trying to integrate vue-components into django-templates. The basic setup did work, but I'm stacked with a component which needs an import itself. Here is the component (vue/dropdown.html): <div id="app"> <template> ... </template> </div> <script setup> import { computed, ref } from 'vue' import {CheckIcon, ChevronUpDownIcon} from '@heroicons/vue/20/solid' const query =ref('') const selectedPerson = ref(null) ... var app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { message: 'Hello Vue!', }, }); </script> So, the 2 imports: import {computed, ref} from Vue import {CheckIcon, ChevronUpDownIcon} from '@heroicons/vue/20/solid' are triggering the error in the browser's console: Cannot use import statement outside a module What is the proper way to use the imports? I'm calling the dropdown.html from base.html: <html lang="{{ LANGUAGE_CODE }}"> <head>...</head> <body> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> {% include 'vue/dropdown.html' %} </body> </html> -
Django form not sending data to admin
I have a form users can fill out to reserve a table at a restaurant. However when they submit the form no data gets sent to the admin side. I have watched some tutorials and read other posts on this site and nothing seems to fix it. I feel like it is something so small but i just cant figure it out. VIEWS.PY from django.shortcuts import render, get_object_or_404 from django.views import generic, View from .models import Book from .forms import BookForm from django.http import HttpResponseRedirect def Book(request): """ Renders the book page """ if request.user.is_authenticated: form = BookForm(request.POST or None) context = { "form": form, } else: return HttpResponseRedirect("accounts/login") book_form = BookForm(data=request.POST) if book_form.is_valid(): instance = book_form.save(commit=False) instance.save() else: book_form = BookForm() return render( request, "book.html", { "book_form": BookForm(), } ) MODELS.PY from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator from cloudinary.models import CloudinaryField class Book(models.Model): name = models.CharField(max_length=50) number_of_guests = models.PositiveIntegerField(validators=[MinValueValidator(1)]) date = models.DateTimeField() email = models.EmailField() requests = models.TextField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) approved = models.BooleanField(default=False) class Meta: ordering = ['date'] def __str__(self): return f"{self.date} for {self.name}" FORMS.PY from .models import Book from django import forms class BookForm(forms.ModelForm): class Meta: model = … -
Get multiple columns data from extra query in Django
I have two models as below: class Model1(models.model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) filename = models.CharField(max_length=255) class Model2(models.model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) filename = models.CharField(max_length=255) I would like to get the related model2 which have the same column value in filename as that of model1. My solution was to use either Subquery or Extra. The problem with Subquery is that it allows only one column to be queried but what I want is a dict object of all the columns of model2 related to model1. They do not have a foreignkey relation to use select_related. So I tried to use extra but again I am getting the multiple columns error. How can I solve this problem? My code is as below: model1_objs = Model1.objects.filter(id=given_id).extra( select={ "model2_obj": f"SELECT * FROM model2 WHERE filename = model1.filename AND id = '{model2_id}'" } ) This does not work. -
record user;s voice with js and post to django server
i want to record a voice from the user and post it to server side (django) the important thing is i don't want save voice with models , but i want to convert voice to text with python libraries for this, i use this plugin, but my the recorded voice is stored in blob format and in an audio tag. i can't send blob to server. I also used Recorder.js, but it is also saved as a blob -
Accessing/Working with rabbitmq Queue using python
I am trying to create an page to monitor RabbitMQ Queues in our application. I want to know how I can perform following operations. I am using Python and Django for the back-end. How to get the number of queues and read their data. How to Purge/Delete the tasks under queue. How to get size (count) of the queue. Thanks in Advance. -
How to pass a paragraph having multiple ( " ) and ( ' ) from a variable inside a string in django?
I want to pass a variable having a paragraph in which there are multiple uses of ( " ) and ( ' ). I am passing this variable inside another string which is an sql query in a django project. For example - variable1 = input() command = "insert into table 1 values{"{}"}".format(variable1); So in avbove code iif the user is entering some data with no ( " ) or ( ' ) it is working fine but when there is presence of these it just throws error. Ho can I get independent of these symbols inside my input data and pass it as a query ? I tried using raw input but when it comes to fetching data from a database and then passing that data containig multiple symbols of ( " ) and ( ' ) it just throws erre. What I want is that it just ignore all these symbols present in my variable . -
Problems with creating a type protocol for Django user class
I have a function that operates on users, but in one of the projects that uses it we don't use Django user. We have a dataclass that pretends to be a user. Problems started when I was trying to type this function. I couldn't use AbstractBaseUser as the user type, because that would obviously not work in this project with dataclass user. However, Python has a solution for such problems - protocols! I quickly created a user protocol containing all features I used in the function: class ManagerProtocol(Protocol): def get(self, **kwargs: Any) -> UserProtocol: ... class UserProtocol(Protocol): objects: ManagerProtocol class DoesNotExist(Exception): ... and adjusted our dataclass user to follow this protocol: class FakeManager: def get(self, **kwargs: Any) -> StaticUser: return StaticUser(user_id=kwargs.get('user_id', '')) @dataclass(frozen=True) class StaticUser: user_id: str is_authenticated: bool = True objects = FakeManager() class DoesNotExist(Exception): pass and then I ran mypy and got this: error: Argument 1 to "function" has incompatible type "StaticUser"; expected "UserProtocol" [arg-type] note: Following member(s) of "StaticUser" have conflicts: note: DoesNotExist: expected "Type[UserProtocol.DoesNotExist]", got "Type[StaticUser.DoesNotExist]" note: objects: expected "ManagerProtocol", got "FakeManager" I've read some articles on the web and the solution was clear - use properties instead of class members! class UserProtocol(Protocol): @property def objects(self) … -
Celery OperationalError [Errno 111] Connection refused
I have one important question that have been worrying me for 2 last days. I have django, postgres and rabbitmq containers in docker. I want to connect celery with rabbitmq but if I do it using django container (docker-compose exec web celery -A myshop worker -l info), it doesn`t connect at all. What only I have tried - nohow. I got the 111 error connection refused. Elif I do it straightforward (celery -A myshop worker -l info) it works and connects but as soon as the task is completing I got the same issue - error 111. Please help me. services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db rabbitmq: image: rabbitmq:3.11.8-management-alpine ports: - "5672:5672" - "15672:15672" volumes: - ./.docker/rabbitmq/data/:/var/lib/rabbitmq/ init.py from .celery import app as celery_app __all__ = ['celery_app'] celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def …