Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django grouping is doing but the group name is the same for each group
When I get data by grouping, the name of the group remains the same. When I pull the group name from the query get error:"Cannot assign "'Torna 2'": "gercekzamanlıveri.isyeri" must be a "isyerleri" instance." seralizer.py class isyerleriserializer(serializers.ModelSerializer): class Meta: model = isyerleri fields = '__all__' class malzemelerserializer(serializers.ModelSerializer): class Meta: model = malzemeler fields = '__all__' class isyerimalzemebilgileriserializer(serializers.ModelSerializer): class Meta: model = isyerimalzemebilgileri fields = '__all__' class gercekzamanlıveriserializer(serializers.ModelSerializer): class Meta: model = gercekzamanlıveri fields = '__all__' class groupdatagercekzamanlıveriserializer(serializers.Serializer) id = serializers.IntegerField() isyeri = serializers.SlugRelatedField( read_only=False, queryset=isyerleri.objects.all(), slug_field='isyeri' ) brut_uretim_suresi = serializers.IntegerField() net_uretim_miktari = serializers.IntegerField() teorik_uretim_miktari = serializers.IntegerField() tee = serializers.IntegerField() toplam_ciro = serializers.IntegerField() toplam_maliyet = serializers.IntegerField() vt = serializers.IntegerField() views.py class groupdatagercekzamanliveriListView(ListAPIView): query2 = gercekzamanlıveri.objects.raw("""SELECT 1 as id, SUM(net_uretim_miktari) as net_uretim_miktari, SUM(teorik_uretim_miktari) as teorik_uretim_miktari, ROUND((SUM(net_uretim_miktari)/SUM(teorik_uretim_miktari)::float*100)) as tee, SUM (toplam_ciro) as toplam_ciro, SUM (toplam_maliyet) as toplam_maliyet, ((SUM(toplam_ciro)-SUM(toplam_maliyet))/SUM (toplam_maliyet)::float*ROUND((SUM(net_uretim_miktari)/SUM(teorik_uretim_miktari)::float*100))) as vt FROM (SELECT tee_gercekzamanlıveri.id,tee_isyerleri.isyeri as isyeri,tee_malzemeler.malzeme as malzeme,tee_gercekzamanlıveri.tarih,tee_gercekzamanlıveri.brut_uretim_suresi,tee_gercekzamanlıveri.net_uretim_miktari,tee_isyerimalzemebilgileri.net_islem_zamani,tee_isyerimalzemebilgileri.satis_fiyati,tee_isyerimalzemebilgileri.uretim_maliyeti,tee_gercekzamanlıveri.brut_uretim_suresi*60/tee_isyerimalzemebilgileri.net_islem_zamani) as teorik_uretim_miktari,ROUND((tee_gercekzamanlıveri.net_uretim_miktari/(tee_gercekzamanlıveri.brut_uretim_suresi*60/tee_isyerimalzemebilgileri.net_islem_zamani)::float)*100::float) as tee,tee_isyerimalzemebilgileri.satis_fiyati*tee_gercekzamanlıveri.net_uretim_miktari) as toplam_ciro, (tee_isyerimalzemebilgileri.uretim_maliyeti*tee_gercekzamanlıveri.net_uretim_miktari) as toplam_maliyet, ROUND((ROUND((tee_gercekzamanlıveri.net_uretim_miktari/(tee_gercekzamanlıveri.brut_uretim_suresi*60/tee_isyerimalzemebilgileri.net_islem_zamani)::float)*100::float))*(((tee_isyerimalzemebilgileri.satis_fiyati*tee_gercekzamanlıveri.net_uretim_miktari)-(tee_isyerimalzemebilgileri.uretim_maliyeti*tee_gercekzamanlıveri.net_uretim_miktari))/(tee_isyerimalzemebilgileri.uretim_maliyeti*tee_gercekzamanlıveri.net_uretim_miktari)::float)) as vt FROM tee_gercekzamanlıveri INNER JOIN tee_isyerleri ON tee_gercekzamanlıveri.isyeri_id= tee_isyerleri.id INNER JOIN tee_malzemeler ON tee_gercekzamanlıveri.malzeme_id= tee_malzemeler.id INNER JOIN tee_isyerimalzemebilgileri ON tee_isyerimalzemebilgileri.isyeri_id= tee_gercekzamanlıveri.isyeri_id AND tee_isyerimalzemebilgileri .malzeme_id = tee_gercekzamanlıveri.malzeme_id) as a GROUP BY isyeri """) queryset = query2 serializer_class = groupdatagercekzamanlıveriserializer Result for query "isyeri" is the … -
Does the Celery worker need Django if the "client" uses django-db for results backend?
I'm writing an application where Django receives task requests via HTTP, submits them to Celery, and then a remote worker executes them. The Celery "client" uses django-db for the results back end. However I do not wish to have the worker include Django. Is this likely to work, or does the worker need access to the results db / is there some other reason why this wouldn't work? -
how to set django path in environment variables?
Here is my django bin folder path, C:\Users\ELINE\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\django\bin I added this path to both system variables and user variables path variable. Also I created a new variable called 'django' in user variables and added this path. But when I type django in cmd(user directory) I get the following output, 'django' is not recognized as an internal or external command, operable program or batch file. My operating system is windows. -
Paginate Custom Json
I'm using DRF in my API's, and I got a situation, I create a view "APIView" and then I cant paginate it. I did before many custom pagination but in my case, I can't find the solution and takes from me many hours. So please anyone can help me, and guide me to the solution. BTW, I read DRF documentation and I found this and also I can't do that. I found: "Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response." here is my views.py code class MyInboxAPIView(APIView): queryset = Message.objects.all() permission_classes = [IsAuthenticated] pagination_class = CustomPagination def get(self, request): single_inbox = ChatRoom.objects.filter(Q(first_user=self.request.user) | Q(second_user=self.request.user)).distinct() single_inbox_count = single_inbox.count() my_teams = Team.objects.filter(players=self.request.user) team_inbox = TeamMessage.objects.filter(team__in=my_teams).order_by().values_list('team').distinct() team_inbox_count = team_inbox.count() my_inbox_teams = Team.objects.filter(pk__in=team_inbox) contact = [] teams = [] for i in single_inbox: if i.first_user == self.request.user: contact.append({"name": i.second_user.first_name + ' ' + i.second_user.last_name, "room_id": i.pk}) elif i.second_user == self.request.user: contact.append({"name": i.first_user.first_name + ' ' + i.first_user.last_name, "room_id": i.pk}) for i in my_inbox_teams: teams.append({"name": i.name, "team_id": i.pk}) my_inbox = {"inbox": {"single chat": [{'contact': contact}], "team chat": [{'team': … -
botocore.exceptions.ConnectionClosedError on zappa update dev
I used zappa for deploying a django app in aws lambda. The issue is I can no longer update my code using zappa update dev. It is throwing botocore.exceptions.ConnectionClosedError. This is the exception while running "zappa update dev" botocore.exceptions.ConnectionClosedError: Connection was closed before we received a valid response from endpoint URL: "https://bucket-name-***.s3.aws-region-***.amazonaws.com/" -
In Django which version is now stable in 2019?
I was using django 1.1 and python2.7 in my project. Now I will setup a new Django project from scratch. So i want to know if the above configuration is correct for my new project or I should use python3 and latest django version. If so then which Django,Python version will be good for new project? And I should get good support from django community. Thanks -
TypeError at /accounts/sign_up/ create() takes 1 positional argument but 2 were given
When I try to create a new user it will show me this error return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: create() takes 1 positional argument but 2 were given and this is my models class Notification(models.Model): title = models.CharField(max_length=250) message = models.TextField() viewed = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) def create_welcome_message(sender, **kwargs): if kwargs['created']: noti=Notification.objects.create(kwargs['instance'], title="Welcome Message", message="Thank you for singing up!") post_save.connect(create_welcome_message, sender=User) I've been missing for a long time. using this language. then help me with this error -
how i can filter model's field that is similar to inputted value?
im new in django . in my homework user will input a data (string) in template and i must filtering field with this data. but the problem is inputted data its just "similar" with field's value. so i can't use MyModel.objects.filter(name__contains=value) . i found documentation that a solution will be using MyModel.objects.filter(name__trigram_similar= value) but this queryset needed to install 'django.contrib.postgres' and i haven't permission to change "setting.py" part so unfortunately i can't use this solution . for more information you should know filed's value and inputted value will be at least 75% similar to each other and the length of them will be exactly equal. here is some models filed's value and inputted value : filed's value: inputted value: spring spting john jfhn hello pello Thanks in advance for any help. -
Adding a custom field to the default user model - if extending it, should I do migrations?
I've been trying to extend the user model with a XP field. After writing the code (which I think it is right) I decided to try it out. Unfortunately, I'm getting this error: ProgrammingError at /register/ relation "accounts_userprofile" does not exist LINE 1: INSERT INTO "accounts_userprofile" ("user_id", "xp") VALUES ... ^ I think this is happening because I extended the user model but I didn't run the migrations. Here's my code: views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User from django.contrib import auth from .models import UserProfile # Create your views here. def login(req): if req.method == 'POST': username = req.POST['username'] password = req.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(req, user) messages.success(req, 'Acum eşti logat') return redirect('dashboard') else: messages.error(req, 'Numele de utilizator sau parola sunt greşite') return redirect('login') return else: return render(req, "../templates/pagini/login.html") def register(req): if req.method == 'POST': first_name = req.POST['first_name'] last_name = req.POST['last_name'] username = req.POST['username'] email = req.POST['email'] password = req.POST['password'] password2 = req.POST['password2'] if password == password2: if User.objects.filter(username=username).exists(): messages.error(req, 'Numele de utilizator deja există') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(req, 'E-mailul este deja folosit') return redirect('register') else: user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user.UserProfile.xp … -
Issue with getting the content_type of an image when other fields are also present in the form
I have the following model form: class ImageModelForm(FilesForm): class Meta: model = Image fields = ['image', 'order_id'] class FilesForm(forms.ModelForm): def save(self, commit=True): obj = super().save(commit=False) for field, value in self.fields.items(): if isinstance(value, forms.FileField) and obj: obj.filename = truncate_filename(self.cleaned_data[field].name.lower()) obj.file_type = self.cleaned_data[field].content_type.lower() # commit is False usually in Admin - check to work also in Admin if commit: obj.save() return obj If I remove 'order_id' from form or do not change its working, otherwise I get: 'ImageFieldFile' object has no attribute 'content_type' -
Why do I need a loop over queryset before rendering
Is it really necessary to loop over my queryset before I can render it to a template. Like in this example: kits = Kit.objects.filter(user=request.user) kitslist = [] for kit in kits: kitslist.append([kit.number, kit.reminder, 'M' if not kit.gender else 'F') return render(request, 'index.j2.html', {'kits': kitslist}) Isn't there a method of filter after which I can directly do it like: kitslist = Kit.objects.filter(user=request.user) return render(request, 'index.j2.html', {'kits': kitslist}) Here I get the error: 'kitslist' is not iterable -
How to allow only authors of the entry to edit it in UpdateView logic
here is the problem: I have the Update View with overridden get_object method : class MyUpdateView(SuccessMessageMixin, LoginRequiredMixin, UpdateView): ...some code here... def get_object(self, queryset=None): obj = UpdateView.get_object(self, queryset=None) if not obj.author == self.request.user: redirect(reverse_lazy("app:url")) # or reverse instead , no difference return obj p.s. object.author tied via foreign key to a user model(self.request.user in our case) in this view I want to allow to edit entry only to a users who created this exact entry. I know how to do it via get_queryset or via UserPassesTestMixin but both methods raise errors . I need instead redirect user who is not an author back to the page where he came from or to a certain URL(parametrical) . In this case(code is bellow) it works fine, 404 appears , so that logic works. I tried it via web site: author able to edit entry, non - author would conjure 404 . # in this case it forks fine, 404 appears : def get_object(self, queryset=None): obj = UpdateView.get_object(self, queryset=None) if not obj.author == self.request.user: raise Http404 return obj But in first example redirect doesn't work for some reason. I have tried - get_querryset or UserPassesTestMixin, but it not what i need autor = … -
how to handle 2 field types to one model field?
I have one model field some of its values are fontawsome icons ,others are image files how to handle 2 types in one field? thanks in advance? <li class="list-inline-item"> <i class="fab fa-html5"></i> </li> <li class="list-inline-item"> <i class="fab fa-css3-alt"></i> </li> <li class="list-inline-item"> <i class="fab fa-js-square"></i> </li> <li class="list-inline-item"> <i class="fab fa-sass"></i> </li> <li class="list-inline-item"> <i class="fab fa-python"></i> </li> <li class="list-inline-item"> <img class="img-fluid img-profile mx-auto mb-2" src="{% static 'img/sql.png' %}"> </li> <li class="list-inline-item"> <img id="logo" src="{% static 'img/logo.png' %}"> </li> -
{ "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" }
I am using django-restframework, I use postman POST json data to my project but I got the error like tittle, I have set raw and application/json here is the code from postman. POST /account/post/reply/ HTTP/1.1 Host: localhost:8000 Content-Type: application/json Cache-Control: no-cache Postman-Token: a0c7bd93-631e-4c7a-8106-87f018eaf7da { "user": "michael", "userid": "1", "ihelpid": 6, "tittle": "6", "info": "6", "label": "3", "tel": "dxy970525", "picture1": null, "picture2": null } my code is really easy only like : from rest_framework.parsers import JSONParser,ParseError class ReplyViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ pagination_class=PageNumberPagination queryset = Forum_reply.objects.all() serializer_class = ReplySerializer #filter filter_backends = (DjangoFilterBackend, ) filter_fields = ['postID',] def create(self, request, *args, **kwargs): print(request.data) data = JSONParser().parse(request) return HttpResponse("ok") After I use viewsets,this error occur,I have print it on shell but it is no problem -
How to get timezone.today as default value in DateField
I would like to set my DateField's default value to today's date in UTC timezone. If I put datetime.now(timezone.utc).date(), it will be a fixed value that is called when the server restarts. If I put timezone.now, it will return datetime object, not day object. How can I get the today's date in UTC timezone? a function that is callable (without parentheses at the end) Because if I put timezone.now().date, wont it be called when the server is restarted only, not everytime the object is created/updated? Thanks -
Difference between React and django channels
What is the difference between django-channels and reactjs. I know react is java script framework django is python framework. But my main concern is when i am build a real time chatting application. Django-channel with webscoket is showing and saving messages into the database and if someone receives a message it is also loaded on to the screen, i don't need to reload the page for it. Same work react does i guess. So if i build a chatting application purely in django will there be any problem? Is it really necessary to make frontend in react or any other js framework? If there are more advantages of react over django-channels please do tell me. I have no idea what react or other framework does. What i know is django. If react is more advantageous i will try learning that but all this is confusing me when both are doing the same job why not continue with django. I don't know whether this question is appropriate or not. Thanks for replies. -
Batch Start PostgreSQL and Django when not already running
I want to create a batch script (I think batch is the best programming language to do that) that automatically detects if a django or postgresql-server is running and if yes then they should be stopped and restarted and if no they should be started. I am using pg_ctl status to find out if a server is running. @echo off ::chcp 437 chcp 1525 :start FOR /F "tokens=*" %%F IN ('pg_ctl -D "%ProgramFiles%\PostgreSQL\10\data" status') do SET result=%%F echo %result% if /I %result% == "pg_ctl: kein server läuft" ( goto start_server ) else ( goto restart_server ) :start_server echo "Server wird gestartet..." call pg_ctl -D "%ProgramFiles%\PostgreSQL\10\data" start call manage.py runserver :restart_server echo "Server läuft bereits, Stopp..." call pg_ctl -D "%ProgramFiles%\PostgreSQL\10\data" stop pkill -f runserver goto start_server goto start pause -
S3 throwing a 403 while reading with boto for public files
I'm using a Django application, where one of the models(Car) has a FileField(brochure). While reading the file with Car.objects.get(id=100).brochure.read(), boto is throwing a 403 saying: File "/usr/local/lib/python2.7/dist-packages/boto/s3/bucket.py", line 233, in _get_key_internal response.status, response.reason, '') S3ResponseError: S3ResponseError: 403 Forbidden While I am still able to view the file in the browser, and able to wget the file, I'm not sure where to look. The bucket's access control list for my user has all the permissions to read/write the bucket contents. Versions I'm using boto==2.43.0 and Django==1.8.13 PS: The codebase was working just fine until yesterday, and the last change that was made was a few months ago. Thanks for any leads. -
How to reference stored database images in template of Django?
I made a form in Django that enable users to write something in text boxes and upload images. The uploaded images will go to /media/ directory. Everything is fine save one thing. I can't display those images in my template. I tried following ways but it didn't work. this is views.py's snippet: class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True, blank=True) body = models.TextField() date = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField(default='default.png', blank=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) and this is my template, that I want to display respective images a user uploaded. <div class="articles"> <div class="article"> <h1>{{ object.title }}</h1> <img src="{% image object.thumbnail %}" alt=""> # didn't work <p>{{ object.body }}</p> </div> </div> Kindly help me solve this, thank you -
How to create a django superuser with foreign key for the first time
I have started a django project with extending User model from AbstractUser to my custom model which have foreign key relation with other model. When I try to create superuser with manage.py it does not create a superuser for testing giving me IntegrityError. Any help will be appreciated class TeacherModel(AbstractUser): middle_name = models.CharField(max_length=256) role = models.ForeignKey(RoleModel, on_delete=models.DO_NOTHING, null=True) -
why I cannot import models to a python script without using django.setup() first
According to this answer (Django script to access model objects without using manage.py shell) before I can use Django models in my standalone python script it is enough to point it to the project's settings file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") from my_app.models import MyModel This results in the error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. This however works just fine: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") import django django.setup() from my_app.models import MyModel I use Django 2.1.7 Is it required now to use django.setup() in each script where I use Django models? -
Can't grab information from POST form
I'm new to Django and web development in general. I am currently playing around with the forms, but I can't seem to get the POST form data. models.py class Car(models.Model): brand = models.CharField(max_length=20) transmission = models.CharField(max_length=20) number_plate = models.CharField(max_length=7) price = models.IntegerField() available = models.BooleanField(default=True) views.py def car_detail_view(request): form = BookCar() obj = Car.objects.get(number_plate="1JZ3OG") context = { 'obj': obj, 'form': form } return render(request, "car/car_detail.html", context) def book_car(request): form = BuyCar(request.POST) if form.is_valid(): instance = models.Car.objects.get(number_plate=request.POST.get('number_plate')) instance.available=False return redirect('../../') forms.py class BookCar(forms.ModelForm): class Meta: model = Car fields = [ 'brand', 'transmission', 'number_plate', 'price', 'available' ] car_detail.html {% block content %} <h1>{{ obj.brand }}</h1> <p>{{ obj.number_plate }}</p> <p>{{ obj.price }}</p> <p>{{ obj.available }}</p> <form class="form" action="." method="post">{% csrf_token %} <input type="hidden" value="{{obj.number_plate}}"> <input type="submit" value="Book"> </form> {% endblock %} Every time I clicked on the Book button in the form, the book_car isn't getting the POST from the form. I've checked tutorials but I can't fix it. -
Need User ID as Variable in Models without request
I have a function which auto add customer numbers, the problem is, that this is a multi-user system, I have to filter customer numbers for the logged in users, the function is not used in a view, so I cant use request.user.id in this situation. My Model function: def customer_no(): GotUserID = 1 #(Fixed right now should be replaced by logged in User) last_customer = Kunder.objects.filter(UserID=GotUserID).order_by('Kundenummer').last() if not last_customer: return '0001' customer_no = last_customer.Kundenummer customer_int = customer_no + 1 return customer_int and uses in another Model class: Kundenummer = models.IntegerField('Kundenummer', default=customer_no, unique=True) And uses in form: Kundenummer = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'input_app', 'readonly': 'True'}), label='Kundenummer', required=True, initial=customer_no()) -
Extending user models in Django saves password publicly
The password for newly created users is shown publicly on the admin console models. Why is that and how I do it correctly? Here is the models.py from django.contrib.auth.models import AbstractUser class ProjectUser(AbstractUser): def __str__(self): return self.username Here is the settings.py PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', ] AUTH_USER_MODEL = 'accounts_app.ProjectUser' Furthermore, I can still access the information using user.id instead of projectuser.id. Is that correct ? I thought that extending the user model will lead to accessing the information with the new class name ? -
IIS wfastcgi django request timeout after 100s, how to make it longer?
i got a django app to extract some data from very big tables. the users are ok with the long waiting time. but every time the users visit the url, it timeout after 100s. How to make it waiting longer? IIs seems to have no configuration for this.