Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use regex in django.db.models.query
I am trying to get values from django.db.models.query, but I wanna use something like latest_stichtag_values.values("buchung__" + any character), example of it in normal python regex would be like r"^[buchung__]\w*", which matches buchung__ buchung__fdsaf buchung__ddd But not asss_buchung__ aaaa So, my question is how can use it in latest_stichtag_values.values("buchung__" + any character) thank you in advance -
after parent signup, parent should be able to create two child and the child should be unique to parent's account in django rest framework?
views.py class ChildCreateAPIView(ListCreateAPIView): serializer_class = ChildListSerializer permission_class = (IsAuthenticated,) def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) # ---> getting the data from serializers class if serializer.is_valid(raise_exception = True): # queryset = Child.objects.create(full_name=full_name, username=username, pin=pin, confirm_pin=confirm_pin) full_name = serializer.validated_data['full_name'] # full_name2 = serializer.validated_data['full_name2'] username = serializer.validated_data['username'] # username2 = serializer.validated_data['username2'] pin = serializer.validated_data['pin'] # pin2 = serializer.validated_data['pin2'] print(pin) # print(pin2) # child = Child.objects.create(username=username, full_name=full_name, pin=pin) guardian = Child.objects.create(username=username,full_name=full_name, pin=pin) # guardian = Child.objects.get(id = Guardian.id) guardian.save() # Guardian= Child.objects.get(guardian=request.user.id) # Guardian = Guardian.objects.get(id=Child.guardian_id.id) # child2 = Child.objects.create(username=username2,full_name=full_name2, pin=pin2) # child.is_verified = True # child.save() # Guardian.add(child) # guardian_id = kwargs.get('guardian_id') # Guardian = Guardian.objects.get(id=guardian_id) # Guardian.add(child) return Response(serializer.data) def get_queryset(self): return Guardian.objects.all() -
Merge three json result into one json
I have these three json file: First: [ { "amount": 100, "id": 1 } ] Second: [ { "new_id": 0, "id": 1, "date": 01/01/2023 } ] Third: [ { "new_id": 0, "start_date": 01/01/2024 } ] I want to merge these three json response together, the ideal result should be: Final: [ { "amount": 100, "new_id": 0, "id": 1, "date": 01/01/2023 "start_date": 01/01/2024 } ] I tried the method of update and update the first and second using a dict(hashmap). Is there a way to do this all together? by depending on two field "id" and "new_id"? merged = {} with open('File1.json') as f: for line in f: jsonified = json.loads(line) merged[jsonified['id']] = jsonified with open('File2.json') as f: for line in f: jsonified = json.loads(line) merged[jsonified['id']].update(jsonified) -
Alert Popup if a value is being removed from already selected values in django admin many to many field
In django admin on change; if a value is being selected for removal from Many to many field, I want to validate if or not that value is eligible for removing and alert user if it cannot be removed else allow user to perform the operation. How do I pass the value or values that are selected for removal on many to many field filtered horizontal widget for example If I want to remove rahulverma from chosen tags and move to available tags, I want to run a javascript call and check if he can be removed from the chosen tags. -
celery doesn't run task at all / periodicly
this function i was using under management/commands and it was working but i'd like to use it to update feeds periodically. like every 15 mins or so. celery.py from celery import Celery import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") app = Celery('mysite', broker='redis://', backend='rpc://', include=['mysite.tasks'], timezone='UTC') if __name__ == '__main__': app.start() tasks.py from .celery import app from news.models import Feed, Article import feedparser from datetime import datetime, timezone @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(60.0, handle.s(), name='update feeds every 60 seconds') @app.task def handle(self, *args, **kwargs): feeds = Feed.objects.all() for feed in feeds: new_list = feedparser.parse(feed.url) for entry in new_list.entries: start = datetime.now(timezone.utc) end = datetime(*(entry.published_parsed[0:6])).replace(tzinfo=timezone.utc) if (start - end).days < 2 and not Article.objects.filter(url=entry.link).exists(): article = Article() article.title = entry.title article.url = entry.link article.description = entry.description dateString = end.strftime('%Y-%m-%d %H:%M:%S %z') article.publication_date = dateString article.save() else: pass i run celery -A mysite worker -l INFO and there is [tasks] . mysite.tasks.handle i tried also celery -A mysite beat no errors but i don't see any effect on my site -
Django Form, make readonly field
I'm trying to create a Form with Django and i'm aiming to have a readonly field, without success. The field should contain a code that is calculated in the view but i need to show it to the user. This is the Model: class Customer(models.Model): name = models.CharField(max_length = 250) note = models.CharField(max_length=500,blank=True,null=True) code = models.IntegerField(null=True,blank=True,unique=True) This is the Form: class NewCustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['name', 'code', 'note'] That should be pretty easy but i'm facing a lot of problems. What I've already tryed: Field.disabled = True (the documentation don't explaine where should i put this attribute so maybe i'm getting something wrong) self.fields['code'].widget.attrs['readonly'] = True in __init __ self.fields['code'].widget.attrs['disabled'] = True in __init __ In all of three method the field remain editable by the user -
Relation "django_celery_beat_periodictask" does not exist after dockerizing celery_beat
I have a Django app with Nginx, Gunicorn, PostgreSQL and Celery that I've been dockerizing. When trying to add celery_beat in my docker-compose.yml, I get a django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist even though the migrations have been ran successfully, and on the admin panel I can see all the celery beat stuff displayed. However celery_beat doesn't start because of this error, but I have no idea where it could be coming from. Here is my docker-compose.yml: version: '3.8' services: rabbitmq3: container_name: rabbitmq image: rabbitmq:3-alpine ports: - 5672:5672 postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password - POSTGRES_DB=db ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: container_name: django_gunicorn volumes: - static:/app/static - media:/app/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" depends_on: - postgres nginx: container_name: nginx build: ./nginx volumes: - .:/code - static:/static ports: - "80:80" depends_on: - django_gunicorn celery: container_name: celery volumes: - media:/app/media build: context: . command: celery -A main worker -P eventlet -c 100 -l INFO env_file: - env restart: always depends_on: - rabbitmq3 - postgres - django_gunicorn celery_beat: container_name: celery_beat … -
Received unregistered task of type 'vubon'. - Getting unregistered error even when all the tasks are shown when starting celery. Why?
The command used to run celery which gives me the output shown in the image.As you can see in the image it says key error vubon. And I don't have any task named "vubon". What maybe the issue is it import structure or something else??? celery -A patronpay worker -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler -
Django DRF Django-filters how to provide a default value if filter argument was not provided?
So in this example from the documentation of django-filters, how would I set a default value for max_price if max_price was not provided as filter option with the API call? class ProductFilter(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr='gte') max_price = filters.NumberFilter(field_name="price", lookup_expr='lte') class Meta: model = Product fields = ['category', 'in_stock'] class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = ProductFilter -
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~~~~!!!(>_<)