Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Expose GET-Params for django-filter als CamelCase
I was wondering if I can expose the GET-parameters required for django-filter somehow as CamelCase instead of snake_case. Meaning changing http://example.com/api/v1/object/list?my_parameter=hello to http://example.com/api/v1/object/list?myParameter=hello. I know that I can transform the output of djangorestframework to CamelCase with this neat package: https://pypi.org/project/djangorestframework-camel-case/ I googled around for some time but couldn't come up with a clean solution. Help much appreciated. -
When should I raise PermissionDenied and when return HttpResponseForbidden in Django
I'm struggling to understand the different use cases for django.http.HttpResponseForbidden and rest_framework.exceptions.PermissionDenied. When should I rather raise the exception than returning a response? Why the exception anyway, if it is later handled as a 403 response? -
'InMemoryUploadedFile' object is not subscriptable
i am getting 'InMemoryUploadedFile' object is not subscriptable can anyone please help me views.py def addFee(request): if request.method=="POST": form=FeeResources() dataset=Dataset() data=request.FILES['myfile'] if not data.name.endswith('xlsx'): messages.info(request,'wrong format') return render(request,'admin/fee.html') imported_data=dataset.load(data.read(),format="xlsx") for i in imported_data: value=FeeStructure( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8] ) value.save() return redirect('managefee') return render(request,'admin/fee.html') -
In WSL, How do I get the following command after the server runs?
I use WSL. I run the 'python manage.py runserver'. After, How do I get the following command after the server runs?enter image description here -
Render a selected image from the option in Django Template
I have been trying to figure out how to render an image in a img tag (id="show_file") when a user selected an option in Django Template. Below is the part in question of my source code: {% block content %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var changeImage = function() { document.getElementById("show_file").src = this.options[this.selectedIndex].value } var imageList = document.getElementById("already_exist_file"); imageList.addEventListener("change", changeImage, True); </script> . . . . <br> <label for="already_exist_file">기존 이미지 사용</label> <select id="already_exist_file" name="image_url" class="selBox"> <option value="없음">(없음)</option> {% for notice in notice_list %} <option id="image" data-style="background-image: url({{notice.image}})" value="{{notice.image}}"> {{notice.image}} </option> {% endfor %} </select> <img id="show_file"> <br> And this is what the page looks like: When the image URL is selected, the img tag still does not show the image. -
Python Django End_of_file
def upload(request): if request.method == 'POST' and request.FILES['myfile'] : myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) length=len(filename) # sheet.cell_value(0, 0) i=1 wb = xlrd.open_workbook(filename) sheet = wb.sheet_by_index(0) for i in range(2): db.push(sheet.row_values(i)) return render(request, 'HafrApp/welcome.html') return render(request, 'HafrApp/welcome.html') #This code working for me but if I change the range of loop like range(length) its not working and gives a error. -
django NoReverseMatch Error when trying to link template to a view function
I'm trying to add a delete object function to an app I'm building and when I try to link to it in my template, I get... NoReverseMatchError Reverse for 'delete_player' with arguments '('',)' not found. 1 pattern(s) tried: ['game/delete_player/(?P[0-9]+)$'] As far as I can tell, (I think) I'm using the correct format in my template. I'm thinking that there's an issue with the object's id not being passed correctly or just not passed at all. I've been looking around Stack overflow here and google to try and find a similar problem but I can't find anything that quite matches what I'm experiencing. Any advice is appreciated. The models object in question that I'm trying to pass to the delete function is a choices field and looks like this. class Player(models.Model): PLAYER_ROLE_CHOICES = ( (1, 'Quarterback'), (2, 'Runningback'), (4, 'Widereceiver'), (5, 'Tightend'), (6, 'Kicker'), ) role = models.PositiveSmallIntegerField(choices=PLAYER_ROLE_CHOICES) The model uses a form in forms.py class PlayerForm(forms.Form): quarterback_name = forms.CharField(label='Quarterback', max_length=100) runningback_name = forms.CharField(label='Runningback', max_length=100) widereceiver_name = forms.CharField(label='Widereceiver', max_length=100) tightend_name = forms.CharField(label='Tightend', max_length=100) kicker_name = forms.CharField(label='Kicker', max_length=100) def save(self): quarterback_name = self.cleaned_data.get('quarterback_name') Quarterback.objects.create(name=quarterback_name) runningback_name = self.cleaned_data.get('runningback_name') Runningback.objects.create(name=runningback_name) widereceiver_name = self.cleaned_data.get('widereceiver_name') Widereceiver.objects.create(name=widereceiver_name) tightend_name = self.cleaned_data.get('tightend_name') Tightend.objects.create(name=tightend_name) kicker_name = self.cleaned_data.get('kicker_name') Kicker.objects.create(name=kicker_name) My delete … -
nested django serialisation through multiple foregin key
I have three models, artist, album and tracks. Artists have many albums and every album have many tracks. I try to serialize into json so that i get all tracks of a artist. Here is my code simplyfied: class Artist(models.Model): name = models.CharField(max_length=128) class Album(models.Model): album_name = models.CharField(max_length=128) artist = models.ForeignKey("Artist", related_name="art") class Tracks(models.Model): track_name = models.CharField(max_length=128) album = models.ForeignKey("Album") And my serialiser class TracksSerializer(serializers.ModelSerializer): class Meta: model = Tracks fields = ["track_name"] class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ["album_name"] class ArtistSerialiser(serializers.ModelSerializer): albums = AlbumSerializer(many=True, read_only=True, source="art") class Meta: model = Artist fields = ["name", "albums"] Function: def get_json(): artists = Artist.objects.all() serialiser = ArtistSerialiser(artist, many=True) content = JSONRenderer().render(serialiser.data) return Response(serialiser.data) To get all album of an artist works fine (also to get all tracks of an album), and give me this output: [ { "name": xxx, "albums": [ { "album_name": "xxx" }, { "album_name": "yyy" } ] } ] But how can write this to get all tracks of a artist (go through 2 reverse relations) My desired output is something like this, how can i persive that? (i have tryed to make an TrackSerialiser into the ArtistSerialiser class but dont know hot to go through … -
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 %}