Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'QuerySet' object has no attribute '_committed'
Wondering why I'm having a hard time to make this sharing function view work without keep hitting this error 'QuerySet' object has no attribute '_committed' somehow when i try to save shared object without adding the groupimage model everything seem to work perfectly fine until i add the image form and groupimage model then things starts to fall part, How do i make this to work? what are the possible best solution to saving share object with separate models in my case Post and GroupImage ? I have made a deep search on stack for a solution but somehow all seem not to fit a solution for my case! Would appreciate help and overviews thank you Here is my view that handle shared Post def share_post(request, pk): original_post = Post.objects.prefetch_related('groupimage_set').get(pk=pk) original_img = GroupImage.objects.filter(post=original_post) group = Group.objects.get(groups=original_post.group.id) form = ShareForm(request.POST, request.FILES) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, group = original_post.group, video = original_post.video, shared_on = datetime.now(), shared_user = request.user) new_post.save() form = GroupImageForm(request.POST, request.FILES) if form.is_valid(): new_image = GroupImage( post = original_post, group = group, image = original_img, ) new_image.save() return redirect('group:main',original_post.group.pk) else: form = ShareForm(request.POST, request.FILES) ctx = {'form':form, … -
python-django forms and models
i need to create a user registration form using django and also need to save datas (fist_name,last_name,username,password1,password2) in auth_user and age,idproof in UserProfile model ,how can i do that using a single django form in views. -
why site url isnt stable
upstream main_site { server 127.0.0.1:8000; } server { server_name domain.com; access_log off; error_log /var/log/nginx/main_site_error.log; location / { proxy_pass http://main_site; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot client_max_body_size 50M; } server { if ($host = domain.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name domain.com; listen 80; return 404; # managed by Certbot client_max_body_size 50M; } I used this configuration for the Negnix on server, but when I want to enter the site with Url (domain.com), sometimes it brings the default of GoDady site and sometimes it brings the site itself. I also used Docker-Compose to run the application. when i use my own ip:port its correct and somtimes got this message This site can’t be reached domain.com unexpectedly closed the connection. Your client does not have permission to get URL / from this server. What do you think I did wrong? -
how to check if a property exists in a foreign key model?
I have a model named Product class Product(models.Model): order = models.ForeignKey(Order, on_delete = models.CASCADE) quantity = models.ForeignKey(Quantity, on_delete = models.CASCADE) In both ForeignKey-s I have the same property named 'number'. I want to check if that property exists in Product model or in its ForeignKey-s models. What I am trying to do is: hasattr(Product, 'number') -
Build model saved 1kb file
Hello Programmers Hope you are doing well. Thanks in advance Problem: When I build my project, # build models for project with id project_id def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True project build successfully but saved 1 kb file. If there is already file exist having some size the model decrease the file file_size to 1kb fetch the models path for project with id project_id def fetch_model_path(project_id, make_dirs=False): # get directory path for project_id path = JaProjectManagement.objects.all().get( id=project_id).url # do necessary transformations path = path if path.find('://') == -1 else path.split('://')[1] path = str(project_id) + '_' + path.replace('.', '_').replace('/', '') path = os.path.join(MODEL_PATH, path) # make directories if asked if make_dirs: os.makedirs(path, exist_ok=True) return path Store model # dump model to path def store_model(path, model): with open(path, 'wb') as f: model_file = File(f) pickle.dump(path, model_file) -
command from compose not executed in entrypoint.sh
I have a Dockerfile for my python django project and then I have a docker-compose that I use to build and deploy my application. Currently, the compose file just have django app, nginx, and db server. The ENTRYPOINT arg in my app's Dockerfile is the entrypoint.sh script which runs some migrations and at the end I have the exec "$@" line which should be executing the Command passed via the docker-compose. But it seems that the command from the Dockerfile does not get executed or crashes. I can see from the output of docker ps -a --no-trunc that the command is indeed being passed as an arg to the ENTRYPOINT. I did try to move the command from the compose file to the entrypoint.sh, and the application starts just fine. But when it is being passed from the compose file, nothing happens. I also tried to echo "$@" in order to check what was being received, but that's empty as well. Here is my app's service in compose: version: '3' services: django_app: container_name: django_app build: context: . dockerfile: Dockerfile image: django_app:latest command: gunicorn app.wsgi:application --preload --bind 0.0.0.0:8000 --workers=4 -t 300 expose: - 8000 depends_on: - db env_file: - ./.env This … -
Not able to Login once user has been created in Django admin
I am able to create the user with permissions and groups. But I am not able to login with the created user in django admin.Creation of the user and permissions -
Why error handler is triggered when i'm trying send django file response?
I upload video file on my django server and saving it in my FileSystemStorage. After I get some frames of this video using python library(PIL) and saving them in fss too. Next i want to display those images on page, so i'm sending(as response) frames_number, fps, filename. def loop(request): if request.method == 'POST': # save video file in vile storage file = request.FILES['file'] fss = FileSystemStorage() fss.save(file.name, file) # set up class, for work with video vt = VideoTools(file.name) # save frames in media storage frames, fps = vt.get_frames() # return frames_number and fps return JsonResponse({ 'frames': frames, 'fps': fps, 'filename': file.name, }) return render(request, 'main/loop.html') In my frontend I count how many frames I need and make the corresponding number of POST requests, each of which give my one frame, but while receiving frame my error handler is trigged. Why? success: function(response) { let fps = response['fps'] let frames = response['frames'] let filename = response['filename'] let frames_needed = Math.round(frames / fps + 1) for(let i=0; i<=frames_needed; i+fps) { // making request let img = get_each_frame(0, filename) img.done(function(response) { console.log(response, 'get_frame_response') }) // getting this handler triggered img.fail(function(error) { console.log(error, 'get_frame_error') }) } }, function get_each_frame(frame_number, filename) { let request … -
How can I check if a foreign key has an attribute on its model?
I have a model named Product class Product(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) I am at Product views.py, how can I check if an attribute exist in the 'Order' model? What I'm trying to do is this -> hasattr(Product, "order__name") -
how to covert utc time fiekd into json?
I want to convert the following object into json but i'm unabe to do that because i'm getting the following error TypeError: can not serialize 'datetime.datetime' object on "create_time":notification_object.create_time.. i'm send back to server the following object by converting into json.. notification = { "id": notification_object.id, "sender": notification_object.sender, "receiver": notification_object.receiver, "message": notification_object.message, "create_time":notification_object.create_time, } I have tried to convert time into string but that is returning me 2021-12-27 10:11:46.395138+00:00 this time format. But i want 2021-12-27T10:16:20.611423Z time format. -
The 'image' attribute has no file associated with it in django
productscreate.html <form method="post"> {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image"></td> <br> </tr> <tr> <td><button type="submit" id="submit" data-bind="submit: mySubmit">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> var formData1 = new FormData(); $(document).on('click', '#submit',function(e){ e.preventDefault() var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description(), }; formData1.append('image', $('#image')[0].files[0]) $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData,formData1, cache: false, processData: false, enctype: 'multipart/form-data', contentType: false, success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> views.py class ProductsList(ListView): model = products context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = products fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = products.objects.all() context_object_name = 'products' model = products models.py class products(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=200) image = models.FileField(blank=True,null=True) def __str__(self): return self.title productsdetail.html <form> Title:- {{products.title }} <br><br> Description:- {{ products.description}}<br><br> Image :- <img src="{{products.image.url}}" alt="image"><br><br> <img src="/static/images/book.jpg"> <button><a href="/edit/{{ products.id}}">Edit</a></button> </form> Image is not displaying … -
How to select distinct coloumn values from mysql database in django?
I need to retrieve distinct value from query set and display it on a div. Here is my model.py: class Persons(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) address = models.CharField(max_length=100) dob = models.CharField(max_length=100) salary = models.IntegerField doj = models.DateField() class Meta: db_table = "test" Here is my view.py: def calender(request): years={} persons = Persons.objects.all() for person in persons: if person.doj.year not in years: years[person.firstname]=person.doj.year return render(request, "home.html", years) Here is my html : <div> {% for item in Persons %} <div class="numbers">{{ item.doj }}</div> {% endfor %} </div> My code is not working. Any help will be highly appreciated. Thank You! -
Django query as string array from checkboxes form
I would like to get multiple inputs from a checkboxes form something and then filter it out from my database. That would be something similar to: http://127.0.0.1:8000/data/?class_type=[class_C,class_M] However what I am receiving from the query is: http://127.0.0.1:8000/data/?class_type=class_C&class_type=class_M This is how it is coded, in .html: Data class <br> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_C" id="class_C" name="class_type"> <label class="form-check-label" for="class_C"> C </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_M" id="class_M" name="class_type"> <label class="form-check-label" for="class_M"> M </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_X" id="class_X" name="class_type"> <label class="form-check-label" for="class_X"> X </label> </div> In views.py: data_class = request.GET.get('class_type') [...] if data_class == "class_C": database = database.filter(class_l__contains = "C") elif data_class == "class_M": database = database.filter(class_l__contains = "M") elif data_class == "class_X": database = database.filter(class_l__contains = "X") Any help is pretty appreciated! Thank you! -
How create a link in templates with relational table in django app
I have question : my classes on models.py `class Actes(models.Model): acte_id = models.AutoField(primary_key=True) title = models.TextField() contenue = models.TextField() vector_column =SearchVectorField(null=True) # new field fullpath = models.CharField(max_length=255) date_atce_add = models.DateField(null=True, blank=True) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) type_acte = models.ManyToManyField(Type_acte, help_text='Select a genre for this acte') pdf = models.ForeignKey('PdfModel', on_delete=models.SET_NULL, null=True)` class PdfModel(models.Model): pdf_field = models.CharField(max_length=255) title_pdf = models.CharField(max_length=255) def __str__(self): return ', '.join(['pdf_field' + str(self.pdf_field), 'title_pdf=' + self.title_pdf]) def filename(self): return os.path.basename(self.file.name) def __str__(self): """String for representing the Model object.""" return f'{self.pdf_field}, {self.title_pdf}' class Meta: ordering = ['title_pdf'] my views on views.py class Dlpdf(View): model = Actes, PdfModel context_object_name ="dlpdf_context" template_name = "search_result.html" def Link_Title (request): if Actes.title : TextField == PdfModel.title_pdf return PdfModel.pdf_field title pdf , and title on actes have a same name in db (for example : title is 'moon' on actes title and 'moon" (title_pdf) in pdfmodel my template search_result.html i try this but i d'ont how to write it. <!-- <li>{{ quote.headline | safe }} - <b>By <i>{{ quote.name }}</i></b></li> --> <span class=""> <li class="list-group-item list-group-item-action list-group-item-secondary"><p class="">{{ actes.contenue | safe |striptags |truncatewords:200 | wordwrap:40 }}</p> {% with Actes PdfModel %} {%for pdf_field in dlpdf_context %} - nom du document <i>{{ actes.title }}</i> </li>ici le … -
(Django)please help me, I not sure is the post function is error
when i press the button to post something, it will return me to the main page, not stay in the forum page and show me what i just post. here is the view.py def forum(request): profile = Profile.objects.all() if request.method == "POST": user = request.user image = request.user.profile.image content = request.POST.get('content','') post = Post(user1=user, post_content=content, image=image) post.save() alert = True return render(request, "forum.html", {'alert':alert}) posts = Post.objects.filter().order_by('-timestamp') return render(request, "forum.html", {'posts':posts}) def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": user = request.user image = request.user.profile.image desc = request.POST.get('desc','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() alert = True return render(request, "discussion.html", {'alert':alert}) return render(request, "discussion.html", {'post':post, 'replies':replies}) -
Passing image link in Django Template from model/context
Does anyone know how to pass a dynamic data entry (from Model) into a img src? One that cannot be saved statically and accessed there in Django? A bit like this <div class="border-8 border-border p-10 w-auto ml-5 rounded-2xl text-base text-white bg-black h-full"> <p class="pb-2">User Profile</p> <img src="{{ Avatar }}"> {% for instance in UserProfile %} {% for field, value in instance.fields.items %} <p> {{ field }} : {{ value }} </p> {% endfor %} {% endfor %} </div> Avatar is just loaded in the context and is a JSON entry containing a URL -
Left Join: Set value to zero if there is no record in the right table
I have two tables called user and point that have a 1-N relationship with each other. Left table: user id name 1 John 2 Willem Right table: point user date score 1 2021/12/01 1 2021/12/02 2 2021/12/01 2 2021/12/03 How can I apply a Left Join that, like the output below, if it does not have a user in the right table according to date field, set score=0. Desired Output according to date: user date score 1 2021/12/01 5 1 2021/12/02 3 1 2021/12/03 0 <------ 2 2021/12/01 5 2 2021/12/02 0 <------- 2 2021/12/03 4 I did the following attempt but it only returns users that have a record in the point table. from django.db import connection cursor = connection.cursor() cursor.execute( '''SELECT users.id,users.username, point.sp FROM users LEFT JOIN point ON users.id = point.user_id WHERE point.date <= '{0}' and point.date >= '{1}';'''.format(sprint.end, sprint.start)) row = cursor.fetchall() -
I have an existing Django Webapp, how do I make a rest API to integrate the webapp with an android app?
I have an existing django webapp, I have two model classes in my models.py for different functionalities in my app. I have used django allauth for all of the login/logout/social sign ins. Note: I have not used django rest framework at all so far in creating my app. Now, I have to do the same for the android version of my webapp using Java. What exactly do I need to do right now to create the rest APIs and then connect them to the android app? please give some suggestions -
Change form based on attribute
class Client(models.Model): name = models.CharField(verbose_name='UID', max_length=80) type = models.CharField(verbose_name='Type', choices=BUSINESS_CHOICES, max_length=80, default='b-2') I have a model like above, what I want to do is based the type attribute need to change the form in update view. I tried the following way in views class ClientEditView(UpdateView): model = Client template_name = 'client_edit_form.html' success_url = reverse_lazy('xxxx') def get_form_class(self): if self.object.type == 'b-2': form_class = ClientEditForm elif self.object.type == 'b-3': form_class = ClientEditForm2 return super(ClientEditView, self).get_form_class() But it is throwing error. Using ModelFormMixin (base class of ClientEditView) without the 'fields' attribute is prohibited. -
How can I do unit testing for def checkout(request) method?
from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/checkout.html', context) -
how to add line break in django admin panel
if I enter a space there, then the text on the site will be glued. But I need a line break to be added there, how can I do this? image -
PyODBC get return value of a stored procedure
I have this code calling stored procedure. with connections["mssql_database"].cursor() as cursor: try: cursor.execute("EXEC [dbVyroba].[dbo].[UlozitCinnost] %s, %s, %s, %s, %s, %s, %s, %s, %s", \ [id_pracoviste, osobni_cislo, id_cinnost, id_klient, pocet, program, cas_od, cas_do, idod]) query = "EXEC [dbVyroba].[dbo].[UlozitCinnost] @idpracoviste=%s, @OsobniCislo=%s, @IDcinnost=%s, @idklient=%s ,@pocet=%s, @program=%s, @CasOd=%s, @CasDO=%s, @IdOd=%s" ret = cursor.execute(query , (id_pracoviste, osobni_cislo, id_cinnost, id_klient, pocet, program, cas_od, cas_do, idod)).fetchall() print ("return value of stored procedure: ", ret) except Exception as e: print( str(e)) It prints [(datetime.datetime(2021, 12, 1, 7, 55, 39), )] How can I get a return value of a stored procedure? -
Nullable one to one vs foreign key in django
History: I have three models, 1.Users 2.Student 3.Institution. At the beginning a user can be either a student or institution, once a user register as student then need to fill their profile (Student Model). Now the Student model is an OneToOne bonded with Users. this is how the old system works. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Problem: Now my new requirement is that "Institution" can add any number of new students under them. Which means they can add new students under their portal For this problem i found two approach, Approach 1: In Student model - make the one to One Field as null=True, blank=True and then add a extra field like institution and then keep track for the students added by institution or Approach 2: In Student Model - make one to one into an Foreign field so that any one can hold the student. Which is the correct approach ? Please help -
Custom S3Boto3Storage with django-storages
I developed a Django app that I'm using VM's disk for saving and serving media and static files but in one of my models, I want to save my files in a FileField connected to my MinIO object storage. I set up the settings like this in the settings.py AWS_ACCESS_KEY_ID = '###' AWS_SECRET_ACCESS_KEY = '###' AWS_S3_ENDPOINT_URL = '###' and in my model I used S3Storage like this: class CustomStorageBucket(S3Boto3Storage): bucket_name = "files" class Document(BaseModel): document_file = models.ImageField(storage=CustomStorageBucket(),upload_to='documents') with these codes, I can save my files into the storage but the URLs in the admin panel do not works properly because it points to the media files URL something like this : http://localhost:8000/media/documents/file.jpg but I want it to be like this ( presigned URL) : https://object-storage.app/files/documents/file.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXX&X-Amz-Date=XXX&X-Amz-Expires=432000&X-Amz-SignedHeaders=host&X-Amz-Signature=XXX -
Is there a way to automatically update a webpage using Django?
I am trying to create a countdown timer into a webpage using Django. I made the requisite time calculations in the view for the template, and passed them in as context to the template, and displayed it using the context. However, the timer only updates as I refresh the webpage. Is there any way I can have the timer auto-update? View Function for template: def home(request): #Time Calculations Performed Here time_dict={'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds} context={'participants':participants, 'time':time_dict} return render(request, 'base/home.html', context) Template Section Where Timer is Displayed: <hr> <h3>Countdown Timer</h3> <div><h5> Days: {{time.days}}, Hours: {{time.hours}}, Minutes: {{time.minutes}}, Seconds: {{time.seconds}} <h5></div> <hr>