Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
400 bad request when connecting android to django
I am trying to upload a clicked picture from android to Django API, but I am getting 400 Bad Request when I tried debugging with logging interceptor. I have surfed all the similar posts but none helped. My Django API works fine when I try uploading an image from local drive, the problem is only when I tried to POST an image from android to backend. It would be very nice if anyone could help me. This is what my logging interceptor looks like https://i.stack.imgur.com/zoB40.png This is what my Django API looks like: https://i.stack.imgur.com/c1ueV.png Method in Main Activity of android studio is: public void uploadPicture(File imageFile, Uri uri ){ System.out.println("The imagefile is stored in "+imageFile); OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); clientBuilder.addInterceptor(loggingInterceptor); /*Retrofit retrofit = new Retrofit.Builder() .baseUrl(DjangoApi.DJANGO_SITE) .client(clientBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) .build(); */ Retrofit retrofit = new Retrofit.Builder() .baseUrl(DjangoApi.DJANGO_SITE) .client(clientBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) .build(); Log.d("Django post API", retrofit+""); DjangoApi postApi= retrofit.create(DjangoApi.class); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile); MultipartBody.Part multiPartBody = MultipartBody.Part .createFormData("model_pic", imageFile.getName(), requestBody); Call<RequestBody> call = postApi.uploadFile(multiPartBody); call.enqueue(new Callback<RequestBody>() { @Override public void onResponse(Call<RequestBody> call, Response<RequestBody> response) { Log.d("good", "good"); } @Override public void onFailure(Call<RequestBody> call, Throwable t) { Log.d("fail", "fail"); } }); } Interface of Django API … -
Can't seem to find out the fields in request.POST(django)
I'm trying to find out the fields for request.POST so i can use them as fields for another function. i.e: def progress_view(request, form): count_pag = 200 for key in request.GET: print(key) value = request.GET[key] print(value) # result = hello.tasks.my_task.delay(request.POST['tweets'], count_pag, req$ # context = {'task_id': result.task_id} return render(request, 'display_progress.html', context={'task_id': result}) however it gives me these errors: Internal Server Error: /account/ 11:27:37 PM web.1 | Traceback (most recent call last): 11:27:37 PM web.1 | File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner 11:27:37 PM web.1 | response = get_response(request) 11:27:37 PM web.1 | File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response 11:27:37 PM web.1 | response = self.process_exception_by_middleware(e, request) 11:27:37 PM web.1 | File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response 11:27:37 PM web.1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) -
Deploying Django on Heroku?
I am trying to host a Python\Django app on Heroku. I followed the guide on heroku website but when I execute the line "heroku ps:scale web:1" it comes back the following message: No process types on ⬢ salty-brushlands-45215. ▸ Upload a Procfile to add process types. ▸ https://devcenter.heroku.com/articles/procfile I already tryed to commit a Procfile into my project (searching for a solution) but I don't know if requires any configuration inside it. Help please! -
How to user super() in Django views.py
I have this class in my views.py class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'chat/thread.html' form_class = ComposeForm success_url = './' def form_valid(self, form): thread = self.get_object() user = self.request.user message = form.cleaned_data.get("message") print(user, thread, message) ChatMessage.objects.create(user=user, thread=thread, message=message) print() return super().form_valid(form) I am using python3 return super().form_valid(form) and the error says Python version 2.7 does not support this syntax. super() should have arguments in python 2, any ideas? -
Django user model (user to user relation)
I would like to ask more experienced coleagues about setting relations between users in standard django user model. In my app I currently keep user data on 3 classes (User, Employee, Manager) as you can see on the below picture. I would like to simplify that model, but I'm not sure can I somehow do that on User class only. Is it possible to do something like this ? from django.contrib.auth.models import User class User(models.Model): manager = models.ForeignKey(User, related_name="employees", on_delete=models.CASCADE) -
Django admin - set a field to be the last row
So I have an abstract BaseModel which consists of different fields, and when I inherit it in my django models and register in the admin, the fields from the parent are always at the top, I want them to be at the bottom, is there a way to do so without without listing all fields for every model? For example I have a custom global class: class CustomGlobalAdmin(admin.ModelAdmin): exclude: List[str] = ('deleted_at',) and it would be great to define it there like fields = ('__all__', 'field_i_want_to_be_last') -
how to add bookmarks to project in django
Value Error at /bookmark save/ Cannot assign "''": "Bookmark.users" must be a "User" instance. -
How to make images stack on top of each other, while not affecting the parent element
I have this code that that creates a HTML code that shows a Card. Inside the card, there is a Image, Title, Price, Location, and Description. And if you click on the card, it links you to a specific website. And in some cards, there are multiple images. But the problem is that, if there are multiple images, it just line up vertically. When I try position: absolute;, it did stack the images on top of each other. BUT, it also stack the Title, Price, Location, and Description. Django template HTML: {% for info in post %} <a class="link_to_detail" href="{{ info.5 }}"> <div class="card"> {{ info.0|safe }} <div class="description"> <h3>{{ info.1 }}</h3> <p>{{ info.2 }}</p> <p><strong>{{ info.3 }}</strong></p> <p>{{ info.4|truncatechars:150 }}</p> </div> </div> </a> {% endfor %} My views.py on Images (I am new to programming..): for li_tag in li_tags: first_a_tag = li_tag.find('a') detail_page_url = first_a_tag.get("href") detail_response = requests.get(detail_page_url) detail_src = detail_response.text detail_soup = BeautifulSoup(detail_src, 'lxml') if first_a_tag.get("data-ids") and isinstance(first_a_tag.get("data-ids").split(','), list): post_image_list = first_a_tag.get("data-ids").split(',') post_image_setup = [] post_image_process = first_a_tag.get("data-ids").split(',') for images in post_image_process: post_image_setup.append('<img src="' + BASE_IMAGE_URL.format(images.split(':')[1]) + '" class="image">') post_image_setup.reverse() post_image_combine = ''.join(post_image_setup) post_image = '<div class="images slides">' + post_image_combine + '</div>' elif first_a_tag.get("data-ids") and isinstance(first_a_tag.get("data-ids"), str): post_image … -
Multiple Objects Returned: get() returned more than one Filter -- it returned 2
#views.py import jwt,json from rest_framework import views from rest_framework.response import Response from models import User class Notemobile(views.APIView): def post(self, request, *args, **kwargs): if not request.data: return Response({'Error': "Please provide mobile_no"}, status="400") mobile_no = request.data['mobile_no'] try: user = User.objects.get(mobile_no=mobile_no) except User.DoesNotExist: return Response({'Error': "Invalid mobile_no"}, status="400") if user: payload = {'id': user.id, 'mobile_no': user.mobile_no,} jwt_token = {'token': jwt.encode(payload, "SECRET_KEY")} return HttpResponse(json.dumps(jwt_token),status=200,content_type="application/json") else: return Response( json.dumps({'Error': "Invalid credentials"}), status=400, content_type="application/json") -
How to add choices from a view?
I am trying to dynamically populate two form choice fields, and namely person and work. The view called assign_work_to_person should allow the user to select a person, a work that has not yet been assigned to a person, and once the form is submitted the selected work should be linked to the selected person (e.g. 'Leonardo da Vinci' should be linked to 'Mona Lisa'). What I am doing is creating the form class with empty choices for the two fields class AssignWorkToPerson(forms.Form): person = forms.ChoiceField() work = forms.ChoiceField() and then retrieving the available persons and authorless works to populate the form fields when the user accesses the assign_work_to_person view. I am trying to dynamically set these choices in this way: form.fields['the_field_name'].choices = a_list_of_tuples When I access the view, the template renders ok, with all the available choices being correctly displayed. The problem is that when I submit the form, it raises validation errors for both fields, telling me to select a valid choice. By running some (very basic print) tests, I have realized that trying to populate the fields this way, doesn't actually add the choices, even though they are there in the template. In fact, as you can see … -
How to retrieve data in Django model using related name
I am trying to display the data from one of my models to the DetailView using the related name defined in the model. It works for the Rental Property model but it doesn't work for the contract model. What might seems to be the problem? my model: UserModel = get_user_model() class Landlord(models.Model): user = models.OneToOneField(UserModel, on_delete=models.CASCADE) address = models.CharField(max_length=255) def __str__(self): return str(self.address) class RentalProperty(models.Model): landlord = models.ForeignKey("Landlord", related_name='rentalproperty', on_delete=models.CASCADE) created_by = models.ForeignKey(UserModel, related_name='rentalproperty', on_delete=models.CASCADE) PROPERTY_LISTING_CHOICES = Choices( ('APARTMENT', _('Apartment')), ('HOLIDAY_HOME', _('Holiday home')), ('SINGLE_FAMILY_HOME', _('Single family home')), ('COMMERCIAL', _('Commercial')), ) type_of_property_listing = models.CharField( max_length = 50, choices = PROPERTY_LISTING_CHOICES, default = PROPERTY_LISTING_CHOICES.APARTMENT,) street = models.CharField(max_length=255) borough = models.CharField(max_length=255) def __str__(self): return str(self.type_of_property_listing) class Contract(models.Model): rentalproperty = models.ForeignKey("RentalProperty", related_name='contracts', on_delete=models.CASCADE) insurance_required = models.BooleanField(default=True) other_terms = models.TextField(blank=True) def __str__(self): return str(self.insurance_required) My html: <h1>This is the detail view</h1> <h3>From landlord</h3> <p>Address: {{landlord.address}}</p> <h3>From Rental property</h3> <ul> {% for rental in landlord.rentalproperty.all %} <li>landlord: {{rental.landlord}}</li> <li>createdby: {{rental.created_by}}</li> <li>Type of property: {{rental.type_of_property_listing}}</li> <li>Street: {{rental.street}}</li> <li>Borough: {{rental.borough}}</li> {% endfor %} </ul> <ul> {% for contract in rentalproperty.contracts.all %} <li> rental property: {{contract.rentalproperty}}</li> {% endfor %} </ul> -
Update data only on UI without storing in database || Django
In my Django project, in one of the views, I currently have a table with some data in the web page with Excel download functionality of entire table data. Now, I wanted to add edit option at every cell, where user can edit and update it and the changes should only reflect in the UI and the downloaded excel should contain the data of the updated values and these updated values are not stored on any database. Please suggest how to proceed on this. -
I'm unable to send email through django
I have a django project hosted on a share hosting server, While I'm trying to send email it's not working. Below is my code, EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'ninjawebhub.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'info@ninjawebhub.com' EMAIL_HOST_PASSWORD = '------' EMAIL_PORT = 465 EMAIL_USE_SSL = False def contact(request): if(request.method == 'POST'): data = Contact( first_name = request.POST['first_name'], last_name = request.POST['last_name'], email = request.POST['email'], phone = request.POST['phone'], message = request.POST['message'] ) data.save() send_mail( 'Contact Form', 'Here is the message.', 'info@ninjawebhub.com', ['info@ninjawebhub.com'], fail_silently=False, ) return render(request, 'contact.html',{'title': 'Contact Us'}) -
How to avoid requesting user on login page while using context_processors.py in Django?
I wanted to pass variables with the User information, that is linked to a Clients model through a ForeignKey to the django.contrib.auth.models, onto the base.html file. So, I created a context_processors.py with the following code from django.contrib.auth.models import User def userData(request): user = request.user u = User.objects.get(username=user) us = u.clients.first_name uv = u.clients.avatar return { 'u': u, 'us': us, 'uv': uv } Everything was working fine, until I logged out. When I try to login again, I get the accounts/login url and get a DoesNotExist at /accounts/login/ User matching query does not exist. -
Elastic Beanstalk Maximum Environment Variable Length
I have difficulty trying to set up over 100 environment variables in my production Elastic Beanstalk running Django. The AWS docs mention that "The combined size of all environment properties cannot exceed 4,096 bytes when stored as strings with the format key=value". To my understanding there are 3 ways to set env vars in ELB. 1) Through eb cli e.g eb setenv key=value(Doesn't work because it'll error out because of maximum length after reaching the maximum no. of characters) 2) Through the EB GUI Configuration > Software > Env variables (Doesn't work for the same reason above) 3) Through option_settings: - option_name: CUSTOM_ENV value: staging -
Django S3Direct rename the file name
I'm using S3Direct to upload to AWS S3, and it's working fine. However when I upload a different file of the same name it overwrites. I turned versions on and now it stores the file with a different url on the server but the reference URL in Django is the same, so I end up with two of the last uploaded image. -
How to i can import model by corresponding in two djanogapp model in django
How to i can import model by corresponding in two DJangoapp model in DJango the bellow table is my Inventory apps Model i already import my service app model in Inventory model Now i want to import Inventory Model in my service model code here from django.db import models from lcs_app.models import UserInfo, CareCenter, Years, LogisticsCompany class PartsType(models.Model): type_name = models.CharField(max_length = 50, unique=True) remark = models.TextField(max_length = 100, blank = True) added_by = models.ForeignKey(UserInfo, on_delete = models.CASCADE) status = models.BooleanField(default = True) def __str__(self): return str(self.type_name) class Meta: verbose_name = "Type" verbose_name_plural = "Parts Types" from django.db import models from ckeditor.fields import RichTextField from inventory.models import PartsSetup class PartsSetup(models.Model): parts_name = models.CharField(max_length = 50) parts_type = models.ForeignKey(PartsType, on_delete = models.CASCADE) parts_no = models.CharField(max_length = 50, unique=True) useable_model = models.TextField(max_length = 200, blank = True) usd_unit_price = models.FloatField(default=0) bdt_unit_price = models.FloatField(default=0) unit_sales_price = models.FloatField(default=0) remark = models.TextField(max_length = 100, blank = True) added_by = models.ForeignKey(UserInfo, on_delete = models.CASCADE) added_date = models.DateTimeField(auto_now_add = True) updated_date = models.DateTimeField(auto_now_add = False, blank = True, null = True) status = models.BooleanField(default = True) def __str__(self): return str(self.parts_name) class Meta: verbose_name = "Parts" verbose_name_plural = "Parts Setup" her i got the bellow error return _bootstrap._gcd_import(name[level:], … -
Django Postman error this field is required
I'm getting {"franchise":["This field is required."]} when I send POST request to localhost django via http://localhost:8000/api/franchise/charge/ I'm sending following 2 fields as Postman's body key: price value: 1000 key: franchise value: 1 Url router.register(r'franchise/charge', views.FranchiseChargeViewSet) View class FranchiseChargeViewSet(viewsets.ModelViewSet): queryset = FranchiseCharge.objects.all() serializer_class = FranchiseChargeSerializer def get_permissions(self): permission_classes = [] if self.action == 'create': permission_classes = [IsFranchise] elif self.action == 'retrieve': permission_classes = [IsFranchise] elif self.action == 'list': permission_classes = [IsFranchise] elif self.action == 'update' or self.action == 'partial_update': permission_classes = [IsFranchise] elif self.action == 'destroy': permission_classes = [IsFranchise] return [permission() for permission in permission_classes] Model class FranchiseCharge(models.Model): franchise = models.ForeignKey(Franchise,null=True,on_delete=models.SET_NULL, default=1) time = models.DateTimeField(default=timezone.now) price = models.PositiveIntegerField(default=0) Serializer class FranchiseChargeSerializer(RelationModelSerializer): franchise = FranchiseSerializer(is_relation=True) class Meta: model = FranchiseCharge fields = ('id','franchise','time','price') @transaction.atomic def create(self, validated_data): instance = FranchiseCharge.objects.create(**validated_data) return instance What do I need to do to fix this? -
How to resize an image in http response while my input image received to me in a plain data format?
I'm new in Django and recently I wrote a project about image representation. in my view's function, I have a function in order to show images. but I first download the image from a service which is an encryption/decryption service. it means that the downloaded image is in plain data byte format. Now I want to write a new function to show that image in a smaller size instead of real size for faster loading. also, I want to show an image in another function as a cropped image. How I can resize and crop images in the fastest way to save time waiting? -
ImproperlyConfigured urls.py in Django
I have the following error and I can't figure out what to change in my urls.py to fix this: django.core.exceptions.ImproperlyConfigured: The included URLconf 'MLtest.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here's what my urls.py looks like: """MLtest URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from MLT import views import debug_toolbar urlpatterns = [ path('admin/', admin.site.urls), path('', views.thankYou), path(r'^__debug__', include(debug_toolbar.urls)), ] My folder structure looks like this: MLtest MLT MLtest urls.py -
Multiple Images Upload Field in Django
I am new to Django and i am using this tutorial to add a multiple image upload field to a model in my web application. So far i am stuck at how to associate my Photo Model to the Hotels Model on the HotelCreateView. My question is how do i associate this multiple image filed with my Hotel model so that on creating the hotel the images uploaded are linked to the created hotel. Kindly assist. Thanks alot Hotel Model class Hotels(models.Model): """Stores all the information about the hotel and also used to query hotels""" name = models.CharField(max_length=255) #The name of the hotel address = models.CharField(max_length=255) city = models.CharField(max_length=255) country = models.CharField(max_length=255) mobile_number = models.CharField(max_length=12) created_at = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) description = models.TextField() slug = models.SlugField(unique=True) property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos') star_rating = models.PositiveIntegerField() contact_person = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True,) #Owner of the hotel or person who created the hotel class Meta: unique_together = ('name', 'slug') verbose_name_plural = 'Hotels' Photo Model class Photo(models.Model): title = models.CharField(max_length=255, blank=True) file = models.ImageField(upload_to='hotel_photos') hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, null=True, blank=True,) class Meta: verbose_name_plural = 'Photos' def __str__(self): """Prints the name of the Photo""" return f'{self.hotel} photos' Forms.py class PhotoForm(forms.ModelForm): class Meta: model = Photo fields … -
How to post nested arrays in Django REST Framework with Postman form-data?
I have a nested writable serializer with array fields. I need to test it with form-data because one of the field type is ImageField. When I changed the ImageField into CharField it worked fine if I posted it with raw JSON format. My simplified serializers.py: class ProductMarketSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) market = serializers.PrimaryKeyRelatedField(many=False, queryset=Market.objects.all()) slabs = serializers.PrimaryKeyRelatedField(many=True, queryset=Slab.objects.all()) thicknesses = serializers.PrimaryKeyRelatedField(many=True, queryset=Thickness.objects.all()) finish_types = serializers.PrimaryKeyRelatedField(many=True, queryset=FinishType.objects.all()) class Meta: model = ProductMarket fields = ['id', 'market', 'name', 'slabs', 'thicknesses', 'finish_types'] class ProductSerializer(serializers.ModelSerializer): collection = serializers.PrimaryKeyRelatedField(queryset=ProductCollection.objects.all(), many=False) color = serializers.PrimaryKeyRelatedField(queryset=ColorParent.objects.all(), many=False) images = ProductImageSerializer(many=True) descriptions = ProductDescriptionSerializer(many=True) markets = ProductMarketSerializer(many=True) class Meta: model = Product fields = ['id', 'product_code', 'collection', 'color', 'images', 'descriptions', 'markets', 'video', 'status'] def create(self, validated_data): image_data = validated_data.pop('images') description_data = validated_data.pop('descriptions') market_data = validated_data.pop('markets') images = [] for image in image_data: img_obj = ProductImage.objects.create(**image) images.append(img_obj) descriptions = [] for description in description_data: desc_obj = ProductDescription.objects.create(**description) descriptions.append(desc_obj) markets = [] for market in market_data: slabs = market.pop('slabs') thicknesses = market.pop('thicknesses') finish_types = market.pop('finish_types') market_obj = ProductMarket.objects.create(**market) market_obj.slabs.set(slabs) market_obj.thicknesses.set(thicknesses) market_obj.finish_types.set(finish_types) markets.append(market_obj) product = Product.objects.create(**validated_data) product.images.set(images) product.descriptions.set(descriptions) product.markets.set(markets) return product views.py: class ProductView(viewsets.ModelViewSet): permission_classes = [permissions.DjangoModelPermissions] serializer_class = ProductSerializer queryset = Product.objects.all() For now I can only send 1 slabs, thicknesses, … -
Running selenium tests in Gitlab CI for a django app
I am trying to get my selenium tests working in Gitlab CI but I'm stuck on the exact setup. Locally my tests run fine, but in the CI I get: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='gitlab-selenium-server', port=4444): Max retries exceeded with url: /wd/hub/session (Caused by NewConnectionError(': Failed to establish a new connection: [Errno -2] Name does not resolve',)) I think it has something to do with the link I use to connect to the selenium hub. My simple test code is this: class SeleniumTest(TestCase): def test_visit_site_with_chrome(self): driver = webdriver.Remote( command_executor='http://selenium_hub:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME ) driver.get('http://django:8000') self.assertIn(driver.title, 'mywebsite') driver.quit() In my CI I think I have to use the standalone mode for Selenium, but I am not sure: image: docker:19.03.0 variables: selenium_remote_url: "http://gitlab-selenium-server:4444/wd/hub" services: - docker:19.03.0-dind - selenium/standalone-chrome:latest tests-website: stage: unittests before_script: - apk update - apk upgrade - apk add python python-dev py-pip build-base libffi-dev openssl-dev libgcc - pip install docker-compose script: - docker-compose -f local.yml build - docker-compose -f local.yml run django pytest system-tests/ tags: - docker I am not sure what the correct setup in the CI should be, especially what link I should use. If I exchange the command-executor in my code with http://gitlab-selenium-server:4444/wd/hub it also doesn't work. Is there anywhere a standard … -
Override Ribbon in Django admin page to be same as the base.html
In my django admin pages, I would like to override the ribbon to be the same as the one in my "base.html" template. For different reasons: Users can navigate through the website even when they are in the admin views. To keep same style across pages, even in admin pages. I know I can extend an admin template simply by doing this on any template: {% extends "admin:admin/index.html" %} by looking at this previous post here which seems to be: A bit old Redundant if I have 5+ models. I am using django 2.2.6. I don't really know how to start and what would be the best approach. Any advices of how you would do this ? -
why i cannot able to connect to mysql with python?
C:\Users\alurilalith.sag\Desktop\website>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.