Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement updating a paragraph text or an image of the index page from the admin panel in Django?
So let's assume that I have a paragraph text and an image on my index html. How can I update it from the Django Admin panel? I have a model with two fields: image = models.ImageField(blank=True) text= models.TextField(max_length=200) I enclosed an image about the admin page. How can I update the text and image on the index page after I click save? -
In my code there is a problem in 13 line but i dont fix it
import requests from django.shortcuts import render def index(request): appid = '4d486d01bd28798a04a622360fa33694' url= 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric & appid' + appid city = 'London' res = requests.get(url.format(city)).json() city_info = { 'city': city, 'temp': res["main"]["temp"], 'icon': res["weather"][0]["icon"] } context = {'info':city_info} return render(request, 'weather/index.html',context) import requests from django.shortcuts import render def index(request): appid = '4d486d01bd28798a04a622360fa33694' url= 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric & appid' + appid city = 'London' res = requests.get(url.format(city)).json() city_info = { 'city': city, 'temp': res["main"]["temp"], 'icon': res["weather"][0]["icon"] } context = {'info':city_info} return render(request, 'weather/index.html',context) -
django not able to post data
This is my index.html <html> <body> <p>Please select Team from below:</p> <form action="teamspage/" method="post">{% csrf_token %} <select name="teams"> <option value="astra">Astra</option> <option value="everest">Everest</option> <option value="pulse">Pulse</option> <option value="gravity">Gravity</option> </select> <br><br> <input type="submit"> </form> </body> </html> views.py: @csrf_exempt def index(request): template = loader.get_template('piplanner/index.html') context = { } return HttpResponse(template.render(context, request)) def teamspage(request): if request.method == "POST": return HttpResponse("Got it new team") urlpatterns = [ url(r'^index/', include('piplanner.urls')), url(r'^admin/', admin.site.urls), url(r'^teamspage/', include('piplanner.urls')), ] On submit request is not going to teamspage view. Please let me know what is wrong with code? I am trying get method which returns form of drop down and on selection value it should go to teamspage url -
Django integration with JS
I am working in a Django app that must show an interactive visualization of different .stl files. I am using Madeleine.js and the problem is that just the last one appear. I have a principal .html with this loop: <div class="container"> <div class="row"> {% for piece in pieces %} {% include "element/element_card.html" %} {% endfor %} </div> </div> And inside the element_card.html this div tag: <div id="target" class="madeleine container"></div> A js file is called from element_card.html in order to create the visualization inside this div id="target". -
validating username while creating user in django rest framework
Here I am writing serializers for registering the users and trying to validate username with validate_username function but is not working. Exception Type: TypeError Exception Value: string indices must be integers Exception Location: ...serializers.py in validate_username, line 40 serializers.py class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=False) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) class Meta: model = get_user_model() fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'profile'] def validate_password1(self, password): validators.validate_password(password=password,user=get_user_model()) def validate_password2(self, password): validators.validate_password(password=password,user=get_user_model()) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def validate_username(self, validated_data): username = validated_data['username'] if len(username) < 6 and len(username) > 15: raise ValidationError('Username must be between 6 and 15 characters long') return username def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], ) user.set_password(validated_data['password2']) user.is_staff = True user.save() profile_data = validated_data.pop('profile') Profile.objects.create( user=user, address=profile_data['address'], contact=profile_data['contact'] ) return user -
Django Rest Framework in production to take 500 parallel requests
I have a current flask api which is running in 'development' server and doesn't take 500 concurrent requests(it hangs) I created a flask webserver using nginx and gunicorn to take multiple requests but I need to create a solution using Django REST Framework and I have heard that Django REST Framework doesn't need a web server(nginx and gunicorn) to run concurrent requests(around 500) and handles everything on its own. So I am looking for a api solution using below mentioned tools/conditions: 1. Django REST Framework 2. Docker/ECS deployment 3. can take 500 concurrent requests Any feedback will be helpful -
How can i access the text file or dynamic css file with help of django and jinja 2 syntex?
ERROR Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/test/mytext.txt 'test\mytext.txt' could not be found You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. my Html code is <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jinja2 Extd</title> </head> <body> {% load static %} <link rel="stylesheet" href="{% static 'test/style.css' %}"> <a href="{% static 'test/mytext.txt' %}">click me</a> <h1>Click Above Link!!!</h1> </body> </html> ==================================================================== i'm a beginner in django. i dont undrst how to slove dis issue .. can any1 help me on this issue...mytext.txt file saved in static/test/mytext.txt path. when i clickd on click me browser shows me above error. -
Django sessionid cookie missing and session_key is None
When an anonymous user request my page the sessionid does not exist, but if i test with a loggedin user sessionid exist? What could be the problem? After someone request my page I redirect him from HTTP protocol to HTTPS. Can it cause the issue?can this delete my sessionid? def test_anonymous_user_has_session(self): self.client.login(username=self.user.username, password='pass') # without this line sessionid does not exist url = reverse('difficult-test-select', kwargs={'questionnaire_id': self.questionnaire.id}) response = self.client.get(url, follow=True) self.assertIsNotNone(self.client.session.session_key) -
Django: How to use filter() or not based on optional param?
As you can see in this url city param is optional: re_path(r'all/(?P<category>\w+)/(?P<page_num>\w+)/?/(?P<city>\d+)?', views.show_all_objects, name="show-all-objects") views.py: def show_all_objects(request, category, page_num, city=''): if category == 'restaurants': objects = Item.objects.instance_of(Restaurant) elif category == 'sportfitness': objects = Item.objects.instance_of(SportFitness) elif category == 'carservice': objects = Item.objects.instance_of(CarService) elif category == 'beautysalon': objects = Item.objects.instance_of(BeautySalon) elif category == 'fastfood': objects = Item.objects.instance_of(FastFood) elif category == 'carwash': objects = Item.objects.instance_of(CarWash) elif category == 'fun': objects = Item.objects.instance_of(Fun) elif category == 'other': objects = Item.objects.instance_of(Other) paginator = Paginator(objects, 2) objects = paginator.get_page(page_num) context = { 'objects': objects, 'category': category, 'page_num': page_num, } return render(request, 'show_all_objects.html', context) I want if city param is set to add .filter(city=city), I can do it with if/else but it doesn't follow DRY principles. -
How to check if button hclicked and act accordingly (Django)
In my first project, I am trying to do add a new line/form whenever the user presses the 'add' button. The code I have produced is the following, and it's in the 'home.html' file: {% extends 'base.html' %} {% block content %} <h1>Create Your Meal</h1> <p>here you can select your meal and ingredients</p> <form action="/action_page.php"> Select quantity: <input type="number" name="quantity" min="1" max="5" value="0"> Select meal <select name="meals"> {% for meal in meals%} <option value="{{ meal }}">{{ meal }}</option> {% endfor %} </select> <button onclick="">Add Meal</button> {% if <br><br> <input type="submit"> </form> {% endblock %} I think has something to do with the 'onclick' mouse event attribute, but I don't know how to tackle this problem. At the moment I can only think of the following options: check if the button has been clicked with an 'if' template tag inside the template (I don't know how to write this though). do the check inside the view.py file (again, I don't know how to pass the argument). Thanks for your help -
unable to install mysqlclient for django using pip3 in ubuntu
command: sudo -H pip3 install mysqlclient Error: /usr/bin/ld: cannot find -lssl /usr/bin/ld: cannot find -lcrypto collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-b0rfercj /mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-lck3vdnw-record /install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-b0rfercj/mysqlclient/ I have already install python3-dev python3-dev is already the newest version (3.6.7-1~18.04). -
I want to access parent model fields using child model object in django
Hello guys I have one query in my Django project. First of all, You can see that I have two Django models named BookSeller and Book Bookseller model class BookSeller(models.Model): user_name = models.CharField(max_length=200) user_email = models.CharField(max_length=200) user_password = models.CharField(max_length=200) user_phone = models.CharField(max_length=100) user_photo = models.ImageField(upload_to='book/seller_photos/%Y/%m/%d/', blank=True) user_address = models.CharField(max_length=300) user_state = models.CharField(max_length=100) user_city = models.CharField(max_length=100) def __str__(self): return self.user_name Book Model class Book(models.Model): book_owner = models.ForeignKey(BookSeller, related_name='book_seller', on_delete=models.CASCADE) book_category = models.CharField(max_length=200) book_title = models.CharField(max_length=200) book_price = models.IntegerField() book_edition = models.CharField(max_length=200) book_author = models.CharField(max_length=200) book_old = models.IntegerField() book_page = models.IntegerField() book_description = models.TextField(max_length=200) book_image_1 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True) book_image_2 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True) book_image_3 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True) book_image_4 = models.ImageField(upload_to='book/book_photos/%Y/%m/%d', blank=True) def __str__(self): return self.book_title Want to DO: In my project I want to find books by that book seller's city. For example, if I write city name 'Silicon Valley' in my search field then it should show me all "Books" that's Sellers(BookSeller) belonging to Silicon Valley. Query: So my query is how can I do that Django Query set, because I can't find out any query which can do this task. If you guys have any other solution then please suggest me!!! -
How to update my setting to use part function of Django?
My Project structure as below : ├── conf │ ├── client.json │ ├── settings.py ├── logs │ └── management.log ├── dbs │ └── models.py └── src └── main.py In settings.py I add dbs in to INSTALLED_APPS settings.py ... INSTALLED_APPS = [ 'dbs', ] ... models.py # coding: utf-8 from django.db import models class User(models.Model): user_name = models.CharField(max_length=32, blank=True, null=True) I setted in main.py at started followed some opnions from websites: import sys, os import json from urllib.parse import urlparse import logging import django BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(BASE_DIR ,'conf')) sys.path.append(os.path.join(BASE_DIR ,'dbs')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') django.setup() from django.conf import settings from models import User But No module named 'dbs' showed, how can I correct my codes to use db, log part of Django Tnahsks. -
how could I correctly save every filed when I create a new data containing m2m field
my model class Person(models.Model): id = models.AutoField( verbose_name='Serial Number', primary_key=True, ) related_group = models.ManyToManyField( verbose_name='Related Group', blank=True, to='Group', through='Membership', ) class Membership(models.Model): id = models.AutoField( verbose_name='Serial Number', primary_key=True, ) person = models.ForeignKey( verbose_name='Person', to='Person', on_delete=models.CASCADE ) group = models.ForeignKey( verbose_name='Group', to='Group', on_delete=models.CASCADE ) def __str__(self): return f'{self.person} and {self.group}' my form class PersonAdminForm(forms.ModelForm): class Meta: model = Person exclude = [] group = forms.ModelMultipleChoiceField( queryset=Group.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Group', is_stacked=False ) ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk: self.fields['group'].initial = self.instance.group_set.all() def save(self, commit=True): g = super().save(commit=False) if commit: g.save() if g.pk: g.group_set.set(self.cleaned_data['group']) self.save_m2m() return g my admin @admin.register(Person) class PersonAdmin(admin.ModelAdmin): form = PersonAdminForm @admin.register(Membership) class MembershipAdmin(admin.ModelAdmin): pass When I add a new "Person" or "Group" on django admin's interface and set its name and m2m field and save, the m2m field remains empty next time I access. But if I set a old one's m2m field, it may save correctly. -
POST/GET request taking too long to reach server but response in fast
I am facing issue in post/get requests, its taking to long to reach to my server but once it reaches it takes just few seconds to response. It always take more than 20s for first packet to reach servers every time. If is submit form or load any page on my internal crm site, the black spinning loading of the browser at the favicon starts but it takes to long to turn to blue spinning wheel. But same on my live site for public use it works fast and smooth. Any one with facing same issue or have any solution please share. If need more clarity on query do reply will share. Server config :- # Shared Server # Nginx Server(with all the timeout set to 1000s) # Gunicorn(with all the timeout set to 1000s) # Python Django Application # DB on remote server with just reading config -
Create one endpoint with optional parameters and retrieve them when POST request
I know there are some previous posts about this on stack overflow, but nothing that matches what I am looking for. Having a look at this documentation: https://docs.djangoproject.com/en/2.2/topics/http/urls/ I manage to create two endpoints: # urls.py url(r'^ror-sb/$', views.Ror_SBView.as_view(), name='ror-sb'), url(r'ror-sb/<int:year>/<int:month>/', views.Ror_SBView.as_view()) Which means I can request my endpoint by accessing: http://127.0.0.1:8000/ror-sb/2/5/ or http://127.0.0.1:8000/ror-sb/ My question is: I would like to create a POST endpoint where I can pass parameters through the URL, maybe the above way to do is not the good way, as some parameters can be optional in my case... Is there a way for me to get all the parameters from URL and create only one endpoint with optional parameters? Ideally, by requesting: http://127.0.0.1:8000/ror-sb/?test=True&toto=5&date=20191125 I can get: test -> True toto -> 5 date -> 20191125 I am using django 2.6 and python 3.6 My view is quite empty for now: @method_decorator(csrf_exempt, name='dispatch') class RorSBViewModel(TemplateView): def post(self, request, *args, **kwargs): print(request.POST) return render(request, self.template_name) By requesting: http://127.0.0.1:8000/ror-sb/?toto=2&test=5, my request.POST is empty... -
How to divide Json strings.?
I have 4 models Category, Vendor, Location, Product. Vendor fall under the Category model (vendor is a foreign key to category). The remaining models are under Vendor (Location, Product) ProductSerializer and LocationSerializer are nested to VendorSerializer, and VendorSerializer is nested to CategorySerializer. class ProductSerializer(WritableNestedModelSerializer): class Meta: model = Product fields = ['id', 'item_name', 'price'] read_only_fields = ['id'] class LocationSerializer(WritableNestedModelSerializer): class Meta: model = Location fields = ['place'] class VendorSerializer(WritableNestedModelSerializer): vendor_location = LocationSerializer() product = ProductSerializer(many=True) class Meta: model = Vendor fields = ['vendor_name','vendor_location','product'] read_only_fields = ['id'] class CategorySerializer(WritableNestedModelSerializer): vendor = VendorSerializer(many=True) class Meta: model = Category fields = ['id', 'category_name', 'tittle', 'vendor'] read_only_fields = ['id'] # View class ProductView(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None, *args, **kwargs): products = Category.objects.all() serializer = CategorySerializer(products, many=True, context={'request': request}) return Response({'response': 'ok', 'result': serializer.data}) # Output { "response": "ok", "result": [ { "id": 1, "category_name": "Cake", "tittle": "test title", "vendor": [ { "vendor_name": "Nest", "vendor_location": { "place": "thrissur" }, "product": [ { "id": 1, "item_name": "test_1", "price": 3200, }, { "id": 2, "item_name": "test_2", "price": 2010, } ] } ] } ] } # Expected output { "response": "ok", "result": [ { "id": 1, "category_name": "Cake", "tittle": "test title", "vendor": [ { … -
Api test case failed for user create view
I am writing the test case here for CreateUser view but the test is failing. It is throwing the following error profile_data = validated_data.pop('profile') KeyError: 'profile' What I am doing wrong here ?Am I doing wrong a=in my view/serializers or my test code is wrong? It creates the users perfectly. models.py class Profile(models.Model): user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE) address = models.CharField(max_length=250,blank=True,null=True) contact = models.CharField(max_length=250,blank=True,null=True) serializers.py class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=False) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) class Meta: model = get_user_model() fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'profile'] def validate_password1(self, password): validators.validate_password(password=password) def validate_password2(self, password): validators.validate_password(password=password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data # def validate_username(self, validated_data): # username = validated_data['username'] # print('usr',username) # if len(username) < 6 and len(username) > 15: # raise ValidationError('Username must be between 6 and 15 characters long') # return username def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], ) user.set_password(validated_data['password2']) user.is_staff = True user.save() profile_data = validated_data.pop('profile') Profile.objects.create( user=user, address=profile_data['address'], contact=profile_data['contact'] ) return user views.py class CreateUser(generics.CreateAPIView): serializer_class = UserSerializer queryset = get_user_model().objects.all() tests.py class UserCreateListTest(APITestCase): def setUp(self): self.client = Client() def test_create_user(self): url = reverse('users:create_user') user = … -
Django CheckConstraint to check user from different models
I have the following models: class Project(models.Model): """ Handles the user projects """ #--> Fields name = models.CharField( verbose_name = ('Name'), max_length = 300, help_text = ('The name of the project.'), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.CASCADE, related_name = 'project_user', verbose_name = ('Created by'), help_text = ('User that created this project.') ) date = models.DateTimeField( verbose_name = ('Creation Date'), default = timezone.now, help_text = ('The project creation date.') ) class ProjectUser(models.Model): """ To link users to projects from other users """ #--> Fields project = models.ForeignKey( 'Project', on_delete = models.CASCADE, related_name = 'projectuser_project', verbose_name = ('Project'), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.CASCADE, related_name = 'projectuser_user', verbose_name = ('Link to'), help_text = ('User to link with this project'), ) link_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.CASCADE, related_name = 'projectuser_link_by', verbose_name = ('Linked by'), help_text = ('User creating the link'), ) date = models.DateTimeField( verbose_name = ('Link Date'), default = timezone.now, help_text = ('Link creation date.'), ) Now in ProjectUser, I want to add a constraint to avoid adding a link between a project and the user that created the project. But I cannot manage to set up the Q object. The first constraint in the Meta class … -
django Rest framework api is not working on another pc of same network
I have created an API named http://127.0.0.1:8000/event/allEvents and it works perfectly in my browser and on the Postman app. However, when I am trying to access the API from another PC of the same network it return an error this site cannot be reached -
Adding item to cart do not work properly after deleting that same item from cart
I am having a problem with adding item to cart after i delete same item from cart. When the item is added to cart and that item is deleted from cart, that same item does not display in cart when i try to add it again in cart. The item can only add in cart again when i delete it from the admin panel. Models.py: class Item(models.Model): title = models.CharField(max_length=250) image = models.ImageField(null=True) price = models.IntegerField() old_price = models.IntegerField(null=True, blank=True) description = HTMLField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = AutoSlugField(populate_from='title') timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) class Meta: ordering = ['-timestamp'] db_table = 'items' verbose_name_plural = 'Items' def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username Views.py: @login_required def remove_from_cart(request, slug): id = request.POST.get('id', None) #retrieve id print(id) item = get_object_or_404(Item, slug=slug) #if no item found raise page not found print(item) obj_order_qs = Order.objects.filter( user=request.user, ordered=False ) if … -
How can UI be added to my Django rest API?
I want to replace this with with custom UIHi stack overflow community! my question is that I have developed a REST API using django rest framework, when you run the API you get Django's predefined rest framework web UI and the data in json in that web UI. How do I add my own User Interface? I am very stuck on this and want to make a dashboard but how do I add the front end code and web design to the json coming from Django in the predefined UI. Thank you! -
How to use search query search input in multiple class
enter code here`VIEWS.py file class SearchResultsView(ListView): model = User template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list -
python dictonary to callable
I have this class enum in my code. class TimeDurationTypeَ(Enum, metaclass=ChoiceEnumMeta): d30 = "30d" d14 = "14d" d7 = "7d" d1 = "1d" hr12 = "12hr" hr6 = "6hr" hr1 = "1hr" I want to be able to filter results (query) based on this time durations. I want to have a dictionary from these enum vals to callabe something like this: TimeDuration2datetimeField = { TimeDurationTypeَ.d30: datetime.timedelta(days=-30), } so I can get this values in the filtering process. How to have such a dictionary? Or is there a better way for this situation? -
How to authenticate admin in Pythonanywhere or Heroku?
I have created a blogging app and i want to deploy it in pythonanywhere or heroku.In that website admin only can register and post something and users can see and read blogs. In django we can access admin site by giving /admin field to our Url. But how can we access to admin site in pythonanywhere and Heroku.