Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
invalid literal for int() with base 10: 'create_property'
I'm getting this error while using one of my django views. I have 2 models; Owner and Property. An owner can have many properties. The models are as below: class Owner(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) trading_name = models.CharField(max_length=100) phone = models.CharField(max_length=50) email = models.EmailField(unique=True) address = models.CharField(max_length=200) def __str__(self): return self.trading_name class Property(models.Model): STYLE_CHOICES = [('Apart','Apartment'), ('Bung','Bungalow'), ('Mans','Mansionnete'), ('Comm','Commercial'), ] name = models.CharField(max_length=100) owner = models.ForeignKey(Owner, on_delete=models.CASCADE) style = models.CharField(max_length=100, choices=STYLE_CHOICES) bedrooms = models.IntegerField() bathrooms = models.IntegerField() parking = models.BooleanField(default=True) sqft = models.IntegerField() address = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) def __str__(self): return self.name My views are: def CreatePropertyView(request): if request.method == "POST": form = PropertyForm(request.POST) print(request.POST) if form.is_valid(): property = form.save(commit=False) property.save() return redirect(reverse('properties')) return render(request, 'property_agency/property_form.html', {'form': PropertyForm(request.POST or None)}) def PropertyListView(request): properties = Property.objects.all() context = { 'properties': properties } return render(request, 'property_agency/property_list.html', context=context) def PropertyDetailView(request, property_id, *args, **kwargs): property = Property.objects.get(pk=property_id) units = PropertyUnit.objects.filter(property=property) context = { 'property': property, 'units': units } return render(request, 'property_agency/property_detail.html', context=context) The PropertyListView with url 'properties' is working just fine. Also PropertyDetailView is working fine, however when i go to 'properties/create_property' it blows out. The stack trace highlights the line: property = Property.objects.get(pk=property_id) of my PropertyDetailView … -
How to use list indices in Django Template.?
I have a list named counts obtained from a SQL query. I want to pass the list into the Django template. {% for count_x in counts %} <td>{{ count_x.times_used }}</td> {% endfor %} This is what usually we all do(count_x.times_used gives me a number which I display in html page.).But this gives me a bug: Count gets displayed twice each time as the counts loop is a nested loop with another loop which i have used to get the service name ,id and price. (As there are tow services here the count us displayed twice) So I the only way which I could see to solve this issue is to used indices over the list counts. How can I pass indiced list in django templates and is there any other way to solve this issue -
Dynamic progress bar django
I am trying to create a progress bar that will update in increments based on how close to completion a project is. So for example, if a project is made up of designing 4 logos, I want to be able to update the progress bar in increments of 25% as each logo design is completed. I thought that I would be able to do this using boolean values and a table but I am now completely lost and don't even know how to start this project. I am creating the project with django. please help. -
Error 502: Error during websocket handshake
I have django app with chat feature made in django channels hosted on AWS using Gunicorn, Nginx and Daphne. The websockets run perfectly fine on localhost but after deployment, I get WebSocket connection to 'ws://www.searchopal.com/ws/chat/z68qxzn1/' failed: Error during WebSocket handshake: Unexpected response code: 502 The logs are as follows:` HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" 2020/11/25 10:03:52 [error] 1051#1051: *311 connect() failed (111: Connection refused) while connecting to upstream, client: 103.116.251.158, server: ***********, request: "GET /ws/chat/z68qxzn1/ HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" 2020/11/25 10:04:18 [error] 1051#1051: *313 connect() failed (111: Connection refused) while connecting to upstream, client: 103.116.251.158, server: ***********, request: "GET /ws/chat/z68qxzn1/ HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" 2020/11/25 10:04:18 [error] 1051#1051: *315 connect() failed (111: Connection refused) while connecting to upstream, client: 103.116.251.158, server: ***********, request: "GET /ws/chat/z68qxzn1/ HTTP/1.1", upstream: "http://127.0.0.1:8001/ws/chat/z68qxzn1/", host: "www.searchopal.com" Settings.py has the following: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('127.0.0.1', 6379)], }, }, } Should I add my AWS instance IP or my domain in the CHANNEL_LAYERS? -
Name of the post_owner is not showing but it is showing the logged in user name
urls.py def post_profile(request): poste = Profile.objects.filter(user=request.user) context = {'poste':poste} return render(request, 'mains/post_profile.html', context) models.py class Post(models.Model): post_owner = models.ForeignKey(User,default=1,null=True,on_delete = models.SET_NULL) date_added = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.date_added class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') email = models.EmailField(max_length=60,default='') post_profile.html {% extends "mains/base.html" %} {% block content %} {% for topic in poste %} <a>{{ topic.full_name }}</a><br> {% empty %} <li>No informtion.</li> {% endfor %} </ul> {% endblock content %} I know that i am trying (user=request.user) in views, but what can i use instead of it ? Please help me in this. I will really appreciate your Help. -
How to use commit=False while saving a model instance without form in Django?
I have a Django web application and I want to add datas to my Data model class from an excel file. Normally, my app adds the excel line by line and if there is an error, it returns a message at that moment but I want it to check first without saving any of the lines and start to save if there is no error. That's why I have added the commit = False expression such as below into the save() function. for i in (df.index): new_data = Datas(author_id = id) try: for j in range(0, len(columns)): value = str(df.at[i,columns[j]]) if value == "nan": setattr(new_data, columns[j], None) else: if columns[j] == "count": value = int(float(value)) setattr(new_data, columns[j], value) new_data.save(commit=False) except Exception as err: print(err) return err However when I added the commit = False expression, I got the following error; save() got an unexpected keyword argument commit Is there any way for using the commit parameter without using forms? If there is not, could you please suggest any other solution? -
join 2 tables that have no foreign key to eact other
class A(Base): number = models.IntegerField(default=None) ... class B(Base): head_number = models.IntegerField(default=None) ... there is 2 model that have no relation to each other, how its possible to write query below with annotate in django orm? Select * from A inner join B on A.number = B.head_number I had tried with extra() but I want to have it with annotate(). Is there any way? -
Get first and last date of previous month in Django
I need to get the first and last date of the previous month from today. start_of_current_month = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) curr_month_start_date = start_of_current_month.date() prev_month_start_date = curr_month_start_date - relativedelta(months=1) The above lines will give a complete month from today, but I need the previous complete month (start and end date). -
Django rest framework Many to one relations
I want to display a list of attachments related to a task. How to pass the pk(uuid) of the task? So far I tried this: models.py class Task(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) title = models.CharField(max_length=50) description = models.TextField() def __str__(self): return self.title class Attachment(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) task = models.ForeignKey(Task, on_delete=models.CASCADE) attachment = models.FileField(upload_to='tasks-attachments/%Y-%m-%d/') def __str__(self): return self.task.title + " attachment" serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = [ 'id', 'task', 'created_at', 'updated_at', 'attachment' ] views.py class AttachmentsView(generics.ListCreateAPIView): serializer_class = AttachmentSerializer def get_queryset(self): return Attachment.objects.filter(task=task__id) urls.py urlpatterns = [ path('tasks/', TasksView.as_view()), path('tasks/<uuid:pk>', TaskView.as_view()), path('tasks/<uuid:pk>/attachments/', AttachmentsView.as_view()) ] -
Can Django models be accessed over REST?
I'm working on a project with a really large code base and decided it would be helpful in the long run to follow a micro-service driven approach and i hit a wall. Some models are interdependent on each other, but the problem is they're in different micro-services (and i would prefer they stay that way). So my question : is there a way (obviously unknown to me) to access ( Create, Read, Update and Delete) instances of my model from a different micro-service without writing the same model in that service?. some code to illustrate my problem. # Store Microservice class Store(models.Model): ... plugins = models.ManyToManyField("Plugins", blank=True) # some other fields # Plugins Microservice class Plugin(models.Model): ... installs = models.IntegerField(default=0) The ManyToMany relationship clearly won't work since Plugins is not defined in the Store's micro-service. Any Help? -
EnvironmentError: Could not find a suitable TLS CA certificate bundle
I'm trying to pip install a package on my server that has an SSL certificate. When I run the pip install I get the following error Could not install packages due to an EnvironmentError: Could not find a suitable TLS CA certificate bundle, invalid path: /etc/ssl/certs/ca-certificates.crt I found some other posts about this however they seem to be having this error on their local machine while mine is on a remote server where I host an app -
Python: How to read data from csv or xls and write overlay over a video?
I am having a setup in which I have data in XLS or CSV file: The data is the Speed and altitude of the plane Now I want to read this file using python or django and show the speed and altitude over a video which I will get from the server. Note: Speed and altitude changes and I want to update those values according to data I am getting over video and finally I want to download the overlayed video. What will be the best way for this? -
TypeError at /check-out
When i try to checkout i get this error : TypeError at /check-out Field 'id' expected a number but got {'id': 3, 'phone_number': '01622153196', 'email': 'sakibovi@gmail.com', 'password': 'pbkdf2_sha256$216000$H2o5Do81kxI0$2tmMwSnSJHBVBTU9tQ8/tkN7h1ZQpRKrTAKkax1xp2Y=', 'coin': 1200.0}. Here is my views.py: class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) print(fname, phone, address, products, cart, customer) for product in products: order = Order(customer=Customer(id=customer),product=product,fname=fname, price=product.price,phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart') Model.py : class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) @staticmethod def get_all_orders(self): return Order.objects.all() @staticmethod def placeOrder(self): return self.save() @staticmethod def get_orders_by_customer(customer_id): return Order.objects.filter(customer=customer_id) -
Django Admin Not Showing Complete Fields In a Model
I am quite new to the Django environment, Here's a problem I am facing: First I made a model: class ABC(Model): field A field B field C then, I migrated them successfully using the following commands: python manage.py makemigrations python manage.py migrate Then, I again added a new field to same model: class ABC(Model): #rest fields are here field D These also got migrated successfully. But, Here's the problem now. After migration, I am not able to see field D in the Django admin interface. (for which I want to edit the value) AM I missing anything here? (PS: Have tried sqlflush, dbshell every possible troubleshoot) I also restarted NGINX & Gunicorn (since I am hosted on AWS EC2) I am certain, that fields are getting created. Please help. -
Django Multiple-User Model
I need advice on a multiple user type. Scenario: A user can be an organization, where in this organization they can place adverts on the website. The owner of this organization(user) can edit/delete users and adverts of his own organization(group). In this organization user type there are users that also can log in and they can only see the adverts placed by them, but the owner of this group must see all adverts of his own and of his users. Think like an estate listing where an organization has multiple locations/users that can place adverts, and has to be managed by a admin user of this organization. What type or model is the best/cleanest for implementing this in a good way? Do I need the Django's User and Group model? -
Django Admin does not load CSS/JS file in Docker and setting request as cancelled
I am using Docker-based Django setup based on gunicorn. On accessing admin it is not loading css/js files. The settings.py looks like below: # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' -
I am tryinng to create a comment box with django in which user profile picture have to show but i dont know to do this / i have tried something
comment box with user and user profile picture I am tryinng to create a comment box with django in which user profile picture have to show but i dont know to do this / i have tried something models.py class comments(models.Model): sno = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) post = models.ForeignKey(article, null=True, on_delete=models.CASCADE) comment = models.TextField(max_length=255) user_dp = models.OneToOneField(profilepic, null=True, on_delete=models.CASCADE) timedate = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.comment + " by " + self.user.name views.py def postcomment(request): if request.method == "POST": comment = request.POST.get("comment") user = request.user postSno = request.POST.get("postSno") post = article.objects.get(sno= postSno) user_dp = comment = comments(comment = comment, user = user, post = post, user_dp=user_dp) comment.save() print("comment saved") return redirect(f"/readfull/{post.slug}") html % for comnt in feedback %} <ul class="list-unstyled" style="margin: 5px;"> <li class="media" style="padding: 0px;"> <img src="{{media_url}}{{ comnt.user_dp.propic }}" class="card-img-top profilePic" alt="DP" style="width:50px; height:50px;"><br><br> <div class="media-body" style="padding: 0px;"> <p class="mt-0 mb-1 list-group-item list-group-item-info" id="commentname">{{comnt.user.name}}</p> <p class="card-text list-group-item list-group-item-secondary" id="comment" >{{comnt.comment}} <button type="button" class="close" aria-label="Close"> <span aria-hidden="true">&times;</span> </button><br><span id="timedate">{{comnt.timedate}}</span></p> </div> </li> </ul> {% endfor %} -
Why is not displayed Field average_rank?
The Problem is I get response without field average_rank my serializer.py is: class CarSerializers(serializers.ModelSerializer): average_rank = serializers.DecimalField(decimal_places=1,max_digits=10,read_only=True) class Meta: model = Car fields = ['Make_Name','Model_Name','average_rank'] And I get response : { "Make_Name": "Honda", "Model_Name": "Civic" }, without Average_rank field my views.py is: class RatingViewSet(ListCreateAPIView): serializer_class = RatingSerializer def get_queryset(self): queryset = Car.objects.all() queryset = queryset.annotate(average_rank = Avg('ratings__rating')) return queryset and Models.py : class Car(models.Model): Make_Name = models.CharField(max_length=100) Model_Name = models.CharField(max_length=100) class Rating(models.Model): RATING_CHOICES = ( (1,1), (2,2), (3,3), (4,4), (5,5), ) rating = models.IntegerField(choices=RATING_CHOICES) car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='ratings') -
How can I use google translation API in Django with python
I am using Django to create a project where I can change the language of website where user can use the page in any language they are comfortable with. But I am not sure how to implement google translate API in Django can anyone help me. I know that we can install google translation API using "$ pip install googletrans" but how can we implement this in Django framework. I am new to python. Thank you in advance. -
How to create a Class Based Views search bar on Django
I'm making a search bar in Django using Class-Based Views on my Views.py. When I try to get the value submitted in the input it's not showing the query name and if I don't submit anything is NOT giving me an error. Also what is the way to get the post showed by the world searched? Thanks for all. My code is: Models.py: class Post(models.Model): # Post core title = models.CharField(max_length=299) author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE) category = models.CharField(max_length=50) image = models.ImageField(blank=True) desc = models.TextField() text = RichTextField(blank = True, null = True ) date = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(null = True, blank = True, unique=True) class Meta: # Order post by date ordering = ['-date',] def __str__(self): # Display title return self.title def get_absolute_url(self): # #TODO da cambiare return reverse("listpost") Views.py: class SearchView(TemplateView): model = Post template_name = "admin/search.html" def get(self, request, *args, **kwargs): q = request.GET.get('q', '') self.results = Post.objects.filter(text__icontains=q, desc__icontains = q, title__icontains = q) return super().get(request, *args, **kwargs) Urls.py: path('dashboard/listpost/search/', SearchView.as_view(), name="search") ListPost.html: {% extends "admin/layout.html" %} {% block title %} <title>Post List</title> {% endblock title %} {% block content %} <form action="{% url 'search' %}" method="GET"> <input type="text" placeholder="Cerca" name="search"> <button>Cerca</button> </form> <div class="postlist"> <div … -
django orm queryset - to perform sql query MIN/MAX FILTER
I am trying to get help to create django ORM queryset for the particular sql statement (you can also run it here) https://dbfiddle.uk/?rdbms=postgres_13&fiddle=31c9431d6753e2fdd8df37bbc1869e88 In particular to this question, I am more interested in the line that consist of: MIN(created_at::time) FILTER (WHERE activity_type = 1) as min_time_in, MAX(created_at::time) FILTER (WHERE activity_type = 2) as max_time_out Here is the whole sql if possible to convert to django ORM queryset SELECT created_at::date as created_date, company_id, employee_id, MIN(created_at::time) FILTER (WHERE activity_type = 1) as min_time_in, MAX(created_at::time) FILTER (WHERE activity_type = 2) as max_time_out FROM timerecord where date(created_at) = '2020-11-18' and employee_id = 1 GROUP BY created_date, company_id, employee_id ORDER BY created_date, employee_id -
Django_Tables2 Dynamic Columns with Filters
Goal was to implement a simple View for the Users to Select columns dynamically with some added calculated info (annotations on some specific columns) and also let them filter on fields. Thankful for any comments, since this took me quite a few hours to get it working properly I thought I would provide a short writeup for anyone looking at a similar problem :) Used Modules/Libraries etc: Django-Filter Django_Tables2 Bootstrap-Select to properly display Multiple Choice Fields Example Model which we would like to use: class Summary(models.Model): billing_date = models.DateField(verbose_name='Billing Date') period = models.CharField(max_length=10, verbose_name='Period') operator = models.CharField(max_length=50, verbose_name='Operator') product = models.CharField(max_length=30, verbose_name='Product') ... -
How to gracefully handle auto disconnect of Daphne websockets
Daphne has a parameter --websocket_timeout link. As mentioned in the doc, --websocket_timeout WEBSOCKET_TIMEOUT Maximum time to allow a websocket to be connected. -1 for infinite. The socket is disconnected and no further communication can be done. However, the client does not receives a disconnect event, hence cant handle it gracefully. How does my client get to know whether the socket is disconnected or not?? I don't want to keep (at client) a timer nor want to keep rechecking it. Whats the right way to go about it,.?? -
Input string recognise text and return date parse
I have a string input where text contains data as "monday of next month" or "4 days before new year" need to convert into dates as suppose today is 25/11/2020, so next month monday is on 07/12/2020, so how should i do it in python (i've tried using datetime, dateutil but didn't help') next week saturday 4 days before new year 3 days after new year second wednesday of next month i need output as 05/12/20 28/12/20 03/01/21 09/12/21 tried reading docs but didn't help can anyone shed some light on it. -
Loop over serializer.is_valid in Django
I am trying to send payload as a list of dictionaries in views and save all of them but only the last item of dictionary gets through the serializer. Views.py for i in payloads: print("i", i) serializer = PFEPSerializer(data=i) if serializer.is_valid(): serializer.save() os.remove('filename.xlsx') return Response(status=status.HTTP_201_CREATED) To see the error I printed the validated_data in the serializer but it too shows the last item in the list. why is if serializer.is_valid(): serializer.save() not working for every loop and how can I do this?