Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error Errno 11001 getaddrinfo failed
Trying to send email using smtp on gmail but getting error 11001 getaddrinfo failed, not sure what I'm doing wrong here, searched stackoverflow and other sources but not able to resolve. her is my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.gmail.com’ EMAIL_HOST_USER = '******@gmail.com' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT = 465 mail function: def send_notification(dataframe): subject = 'That’s your subject' from_email = settings.EMAIL_HOST_USER to = '*******@gmail.com' text_content = 'That’s your plain text.' html_content = """\ <html> <head></head> <body> <p> Test email from django </p> </body> </html> """ message = EmailMultiAlternatives(subject, text_content, from_email, [to]) message.attach_alternative(html_content, "text/html") message.send() Error: for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed [26/Jul/2022 13:21:51] "GET / HTTP/1.1" 500 114527 -
How to ad changing value to variable
Hi i have problem with asigning some changing variable to other variable. This is my code: model.py class Team_of_4(models.Model): name = models.CharField(max_length=64) op1 = models.CharField(max_length=16, choices=ARMIES_CHOICE) op2 = models.CharField(max_length=16, choices=ARMIES_CHOICE) op3 = models.CharField(max_length=16, choices=ARMIES_CHOICE) op4 = models.CharField(max_length=16, choices=ARMIES_CHOICE) p11 = models.IntegerField(choices=PARING_SCORE_CHOICES) p12 = models.IntegerField(choices=PARING_SCORE_CHOICES) p13 = models.IntegerField(choices=PARING_SCORE_CHOICES) p14 = models.IntegerField(choices=PARING_SCORE_CHOICES) p21 = models.IntegerField(choices=PARING_SCORE_CHOICES) p22 = models.IntegerField(choices=PARING_SCORE_CHOICES) p23 = models.IntegerField(choices=PARING_SCORE_CHOICES) p24 = models.IntegerField(choices=PARING_SCORE_CHOICES) p31 = models.IntegerField(choices=PARING_SCORE_CHOICES) p32 = models.IntegerField(choices=PARING_SCORE_CHOICES) p33 = models.IntegerField(choices=PARING_SCORE_CHOICES) p34 = models.IntegerField(choices=PARING_SCORE_CHOICES) p41 = models.IntegerField(choices=PARING_SCORE_CHOICES) p42 = models.IntegerField(choices=PARING_SCORE_CHOICES) p43 = models.IntegerField(choices=PARING_SCORE_CHOICES) p44 = models.IntegerField(choices=PARING_SCORE_CHOICES) views.py class TParing4v4View(View): def get(self, request, id, par): tournament = Tournaments.objects.get(pk=id) player = Team_of_4.objects.get(pk=par) result = [] data_list = [] points = [] mp = [] teamA = [tournament.p1, tournament.p2, tournament.p3, tournament.p4] teamB = [player.op1, player.op2, player.op3, player.op4] for perm in permutations(teamA): result.append(list(zip(perm, teamB))) for pairing in result: score = [] total = 0 for i in pairing: for A in teamA: for B in teamB: if i == (A, B): x = teamA.index(A) + 1 y = teamB.index(B) + 1 j = player.pxy How can i add x and y value to j? i want to get something like this: j = player.p11 j = player.p12 . . . j = player.p44 -
How to show the DateTime table?
im making a webapp, im making a DateTime table, I have done this before but without any problem forms.py class DateInput(forms.DateInput): input_type = 'date' class HomeworkForm(forms.ModelForm): class Meta: model = Homework Widgets = {'due':DateInput(attrs={'type':'date'})} fields = ['subject','title','description','due','is_finished'] models.py class Homework(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) subject = models.CharField(max_length=50) title = models.CharField(max_length=100) description = models.TextField() due = models.DateTimeField() is_finished = models.BooleanField(default=False) views.py def homework(request): if request.method == 'POST': form = HomeworkForm(request.POST) if form.is_valid(): try: finished = request.POST['is_finished'] if finished == 'on': finished = True else: finished = False except: finished = False homework = Homework( user = request.user , subject = request.POST['subject'], title = request.POST['title'], description = request.POST['description'], due = request.POST['due'], is_finished = finished ) homework.save() messages.success(request,f'Homework Added from {request.user.username}!!') else: form = HomeworkForm() homework = Homework.objects.filter(user=request.user) if len(homework) == 0: homework_done = True else: homework_done = False context = { 'homeworks':homework, 'homeworks_done':homework_done, 'form':form, } return render(request,'dashboard/homework.html', context) Ive used many ways to show the DateTime table in 'due' , where i can choose date from something like a calendar but i still got nothing and when i input a date myself f.e(2020-2-1)i see an error telling that the date form is invalid -
Python add values to the same key
I have a list like lst = [{'x':{'a':10}},{'x':{'b':10}},{'x':{'c':10}},{'x':{'d':10}}, {'y':{'a':10}},{'y':{'b':10}},{'y':{'c':10}},{'y':{'d':10}}, {'z':{'a':10}},{'z':{'b':10}},{'z':{'c':10}},{'z':{'d':10}} ] But I want something like this lst = [{'x':{'a':10,'b':10,'c':10,'d':10}}, {'y'{'a':10,'b':10,'c':10,'d':10}}, ...] How can I achieve it?? -
Group by on filtering with the Django ORM
I need to check that is room in database But I think It need to group by with ChatRoom's pk ChatRoom.objects.filter(member__in=[request.user, target_user]).count() < 2 in this How can I do? Help me. Thank you! views.py if ChatRoom.objects.filter(member__in=[request.user, target_user]).count() < 2: room = ChatRoom.objects.create() room.member.add(request.user) room.member.add(target_user) models.py class ChatRoom(models.Model): id = ShortUUIDField(primary_key=True) member = models.ManyToManyField( settings.AUTH_USER_MODEL, through='ChatRoomMember' ) class Meta: managed = True db_table = 'chat_room' class ChatRoomMember(models.Model): room = models.ForeignKey( ChatRoom, on_delete=models.CASCADE, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class Meta: db_table = 'chat_room_member' class ChatMessage(models.Model): room = models.ForeignKey( ChatRoom, on_delete=models.CASCADE, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) message = models.CharField(max_length=255) created_at = models.DateTimeField(default=datetime.now) class Meta: managed = True db_table = 'chat_message' -
How to get json response where attributes are under another 'set attribute' (see example)?
I am new to Django APIs. I am designing a api where response will be like this after a post request: { "set_attributes": { "some attribute": "some value", "another attribute": "another value" }, } At present my response showing like this: { "some attribute": "some value", "another attribute": "another value" } Point to be noted I am using class based views and for forms I am using Django models. I did not render any html forms. -
How to auto load/ import model, serializer as per the conditional requirement in any view using Django
I am in need of an Auto Import for Custom Model and Serializer Accordingly as per the condition, in any view. Problem Case: Here I created two Classes(VIEWS) in Django one is specifically taking requests and another is the Base class that will control all the requests using the (get_data()) function and returns the valid data and response. SampleView.py: from .src.views.BaseRequestClass import BaseRequestClass class SampleView(APIView): def get(self, request): if request.query_params.get('page') and request.query_params.get('rows'): d = BaseRequestClass model = request.query_params.get('model') # Model name I am getting in Request data = d.get_data(model) return Response(data, status=status.HTTP_200_OK) BaseClass.py: class BaseRequestClass: def get_data(models): dictionary = {"stu": ['StudentModel', 'StudentSerializer']} if models =='stu': model = # here auto import of the model required as per above dictionary only if condition matched else no import will take place for this model serializer = # here auto import of the serializer required as per above dictionary only if condition matched else no import will take place for this model details = model.objects.all() serial = serializer(details, many=True).data return serial Where is the mistake or issue while writing this and what code can help me to import in it that i don't have to import all together, just as per condition only … -
Django: Atomic reads of multiple model fields
I have the following Django models and a simple function, which accesses the database: class Shape(models.Model): color = models.CharField() name = models.CharField() class Point(models.Model): x = models.FloatField() y = models.FloatField() shape = models.ForeignKey(Shape, on_delete=models.CASCADE, related_name="points") def some_access(id): shape = Shape.objects.get(pk=id) return shape.color, shape.name, list(shape.points.all()) My questions are: In fn some_access: Are the values of color, name and points read in the same sql transaction? If not, there could be a race condition(read shape, modify database entry from somewhere else, read points) If not how can I achieve that access to different attributes (on same model or on foreign key obj - e.g. x and y values of points) are read atomically? If transaction.atomic is used. Does that mean it locks the database and makes multiple accesses on the database and maybe causing a n+1 problem? The only thing I can think of for question 2 is wrapping everything in transaction.atomic. -
celery using amqp:// instead of redis
i used pip install celery[redis] in project settings: CELERY_BROKER_URL = "redis://127.0.0.1:6379" redis gives PONG answer but its still using amqp when i run celery -A news worker -l info -
How to pass value to a modelform_factory function from djnago templates
In my template, I have a loop to display each row in a table, each row has a couple of input fields from the formset function I created. I'm facing an issue where I want to pass an id for each row I'm looping in so that I can control the data inserted in my database, but the problem is how can I detect the id of each row I'm in, to insert each row separately? {% for products in products_info %} <tr> <td>{{issuance_formset.checked}}</td> <td><a href="#" class="open-modal" data-url="{% url 'shop:item_modal' products.id %}">{{products.item.name}}</a></td> <td>{{issuance_formset.factory}}</td> {% endfor %} what I want is to pass the products.id for each row from each loop iteration along with the form request. Is there a way to do that? -
How to implement logout functionality in django given that the admin selects the logout duration depending upon the options given via radio button
I have an HTML page with the 4 radio buttons to select the time of logout: So the admin can select after how many minutes he/she wants to log out of the Django application. Auto-logout options: 15mins 30mins 1hour never (radio button will be there) So how do we implement it? I am using the default login/logout template of django.allauth -
Front end service for non-cli interaction using python
I have one python project ,in which it contains many functions which will execute only in terminal of the vs code. My requirement is I want to add simple GUI/web/html interface(using django) to replace CLI with frontend. How this can be achieved? Any idea would be appreciated as I did not get any efficient solution on internet. Thanks -
Can Django website be ported as Flutter based mobile app without Django REST APIs?
We have a Django based website with PostgreSql database. We don't want to develop any REST APIs for the current website. So we would like to know whether it is possible to develop a mobile app using Flutter when our website doesn't have REST APIs? Best regards, rk -
DJANGO: forms dont show error to user (def post + ListView)
can you help me? I can't fix problem: my don't show error validation when I write not unique slug at form -> no error at form I think problem at use def post() or return redirect after validations form. I try many different solutions but nothing helps. Maybe you should use a non-standard way to report an error? models.py class ShortUrl(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Автор URL', null=True) url = models.CharField('Ссылка', max_length=200) slug = models.SlugField('Короткое имя ссылки', unique=True, max_length=20) def __str__(self): #return self.slug return f"Короткая ссылка: {self.user} >> {self.slug}" class Meta: verbose_name = 'Ссылка' verbose_name_plural = 'Ссылки forms.py class ShortURLForm(forms.ModelForm): slug = forms.SlugField( label='Название URL', required=True, widget=forms.TextInput(attrs={'placeholder': 'Укажите уникальный URL'}) ) url = forms.CharField( label='Ссылка', required=True, widget=forms.TextInput(attrs={'placeholder': 'Ссылка которую нужно сократить'}) ) class Meta: model = ShortUrl fields = ['user', 'url', 'slug'] widgets = {'user': forms.HiddenInput()} views.py class ShortURLPage(LoginRequiredMixin, ListView): model = ShortUrl template_name = 'main/shorts.html' context_object_name = 'shorts' def get_context_data(self, *, object_list=None, **kwargs): ctx = super(ShortURLPage, self).get_context_data(**kwargs) ctx['form'] = ShortURLForm() userurls = ShortUrl.objects.filter(user=self.request.user) ctx['shorts'] = userurls ctx['title'] = 'Добавление ссылок' return ctx def post(self, request, *args, **kwargs): post = request.POST.copy() post['user'] = request.user request.POST = post form = ShortURLForm(request.POST) if form.is_valid(): slug = form.cleaned_data['slug'] url … -
How to make a POST request and use the ID of the author?
I have this model Game and I have a working GET method and would like to create new Game objects in my database by using a POST request. I have Game like this: class Game(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255) ... I have a view like this: class GameDetail(APIView): def get_object(self, game_slug): try: return Game.objects.filter(slug=game_slug) except Game.DoesNotExist: raise Http404 def get(self, request, game_slug, format=None): game = self.get_object(game_slug).first() serializer = GameSerializer(game) return Response(serializer.data) def post(self, request, format=None): game_data = request.data game_data['owner'] = { 'username': 'admin', 'email': 'admin@example.com'} // just to test serializer = GameSerializer(data=game_data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) If I send the server a POST request with the following body: { "name": "Posted game", ... // ommiting owner field } It looks like the server thinks I want to create a new user, but I just want the game to be associated with the userId { "owner": { "username": [ "user with this username already exists." ] } } If instead I set the game_data['owner'] to the userID directly it complains that it's expecting a dictionary. How can I make it so that when I GET a game I see the owner … -
how to refresh django control without model
I'd like to refresh django control(without model) after updating. (created the userForm by forms.py) Is this method feasible? if possible, tell me how to write code. forms.py class test_Form(forms.Form): # userID user_id = forms.ChoiceField( label = "userID", widget= forms.Select(), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # userID-source sql_user_id = """ select distinct user_id , user_id as disp_user_id from hoge order by user_id """ df_user_id = db.dataframe(sql_user_regrole) // <- result in dataframe self.fields["user_id"].choices = tuple(df_user_id .itertuples(index=False , name = None)) views.py def view(request): return render(request, "test.html", {'form': test_Form()}) def Regist(request): // update process... return ??(what should I return to client) push btn_exe , input text regist to DB-table. and refresh userid(select box). test.html <script> $(document).on("click","#btn_exe",function(){ RegistExecute(); }); function RegistExecute() { var formData = $('#userForm').serialize(); var postData = { type : "POST", dataType : "text", data : formData, processData : false, contentType : false }; //exe $.ajax(URL, postData) .done(function(){ alert("data update finished."); // how to refresh control?? }); </script> <html> <body class=""> {% load static%} {{ form.media }} <form class="form-inline" id="userForm"> {{ form.user_id}} <input type="text" id= "add_user"/> {% csrf_token %} <button type="button" id="btn_exe" class="">ADD USER</button> </form> please help me~~~~!!!(>_<) -
Send a field from ListAPIView to Serializer in Django Rest Framework
I'm building a leaderboard view for a REST API I'm designing in DRF. I need a bit of help in reducing an inefficiency. views.py class LeaderboardAPIView(ListAPIView): serializer_class = UserSerializerLeaderboard permission_classes = (IsAuthenticated,) def get_queryset(self): queryset = User.objects.all() queryset = list(queryset) queryset.sort(key=operator.attrgetter("total_karma"), reverse=True) queryset = queryset[:10] return queryset serializers.py class UserSerializerLeaderboard(serializers.ModelSerializer): score = serializers.SerializerMethodField(read_only=True) place = serializers.SerializerMethodField(read_only=True) def get_score(self, obj): return obj.total_karma def get_place(self, obj): return "1" class Meta: model = User fields = ("score", "place") The get_place method currently returns a placeholder of 1. I'd like it to return the actual place the user is in, sorted by score. Now, I know I'm already calculating this in the queryset, so I don't want to repeat this inefficiently. How can I send the place of the user to the serializer directly, rather than repeating the calculation in the method? -
How to generate a list of request.POST in Django
I have the following code in views.py: def valores(request): global peso_unitario, preco_unitario peso_unitario=[] preco_unitario=[] N=a print('N='+str(N)) for i in range(N): peso_u = request.POST['peso_u'] preco_u = request.POST['preco_u'] if peso_u.isdigit() and preco_u.isdigit(): c = int(peso_u) d = int(preco_u) peso_unitario.append(c) preco_unitario.append(d) print(a) if i==N-1: return render(request, 'pacote.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) else: res = 'Apenas numero.' return render(request, 'pacote.html', {'res': res}) One step before, where we filled a text field with a number N. Now, I'd like to generate N text fields to be filled by the user, but I don't know how to do this. -
I want to create contact form with some validation in Django views.py file
I want to validation that if user fill contact form with number and again try with same number it will not allow to fill form till some days after they can fill form again with same number in Django. -
Python: 'NoneType' object is not subscriptable
Asking for some help on this one. def home(request): client = pymongo.MongoClient(settings.MONGO_SERVER) main_db = client[settings.MONGO_DATABASE] get_main_config = main_db.configurations.find_one({"name": "main_config"}) return render(request, 'dashboard/home.html', {"data": get_main_config["homepage_urls"]}) Traceback (most recent call last): render(request, 'dashboard/home.html', {"data": get_main_config["homepage_urls"]}) TypeError: 'NoneType' object is not subscriptable Why the error occured on that line? Thank you. -
Django session timeout handler
I have a function my_logout_handler() that needs to be called when a user logs out. I am calling the function in the logout function as below. def logout(request, login_url=None, **kwargs): // original code here my_logout_handler() It works perfect except that it is not called when user is logged out due to session timeout. Where should I put my code for it to get called on session timeout? -
django.core.exceptions.improperlyconfigured unknown parameters loader
Good day everyone! I'm tryna create affiliate marketing website, but have been having some errors lately this the kind of error i got when i run python manage.py runserver django.core.exceptions.improperlyconfigured unknown parameters loader -
Calculate the ForeignKey type Percentage (individual) Django ORM
I want to calculate the percentage of all car types using Django ORM, or group by all of the cars on the basis of their types, and calculate the percentage. I've multiple solutions but they are old-fashioned and itrative. I am going to use this query over the dashboard where already multiple queries calculating different analytics. I don't want to compromise on performance, that's why I prefer the single query. Here is the structure of my tables (written) on Django: class CarType: name = models.CharField(max_length=50) class Car: car_type = models.ForeignKey(CarType, on_delete=models.CASCADE) I have a utility function that has the following details: input => cars: (Queryset) of cars Django. output => list of all car_types (dictionaries) having percentage. [{'car_type': 'car01', 'percentage': 70, 'this_car_type_count': 20}, ...] What I've tried so far: cars.annotate( total=Count('pk') ).annotate( car_type_name=F('car_type__name') ).values( 'car_type_name' ).annotate( car_type_count=Count('car_type_name'), percentage=Cast(F('car_type_count') * 100.0 / F('total'), FloatField()), ) But, this solution is giving 100% on all car_types. I know this weird behavior is because of the values() I'm using, but I've kinda stuck it here. -
Unable to install this app without the developer's account , zoom OAuth2
Unable to install this app without the developer's account. Please contact the app developer to install. Edit on Web Portalenter image description here -
Create pages programaticallhy with Django and Wagtail
I managed to programatically create pages using Django Management Commands as shown here and here. How do I link those pages to other models like tags, categories and authors? Here is the model of the page I want to create: class BlogPage(Page): ## Fields I can create programatically date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) ## Fields I dont know what to do with tags = ClusterTaggableManager(through='BlogPageTag', blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) authors = ParentalManyToManyField('blog.BlogAuthor', blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None