Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Implementing django authentication system for my project
Going bit lengthy so that you can get complete picture.. I am building a ticketing system (called TS for short in post ) for a issue resolving for the product (called P for short in post ) in my company. The TS has 2 type of users : customers (which are also employee of same company but in other location ) company internal people (includes developers/project manager/product owner ..etc) Note: Company uses Ldap for authentication. customers raise a ticket from P giving all information/problem(like username, issue description etc) and it gets stored in a central database. The ticket raiser gets a link via mail to track the progress of ticket like http://127.0.0.1:8000/cust_view/12 here 12 is ticket id of ticket the customer raised. Note: while raising ticket from P the customer provides its username which is checked in backend (using LDAP) for successful ticket generation(which i implemented successfully). when clicking the above link the customer should be redirected to a login page like http://127.0.0.1:8000/customer_login/?next=/cust_view/12(if the customer is not logged in) or will be in http://127.0.0.1:8000/cust_view/12 displaying that customer is authenticated but is not authorized to view this ticket detail if the user is logged in from previous session but not authorized … -
Apache jena-useki server refuses connection when running tests from a shell script
I'm unittesting an application that uses apache-jena-fuseki from python backend with sprql. I didn't find any means for using an in-memory jena test-db, thus I decided to start a test-fuseki-server from the shell script that runs my tests. #!/bin/sh set -x cd jena/apache-jena-fuseki-3.13.1 nohup jena/apache-jena-fuseki-3.13.1/fuseki-server --update --file sandbox_2019-11-20_10-57-04.nq / >/dev/null 2>&1 & export pid=$! cd - JENASERVERPASSWORD="<myJenaPw>" \ JENASERVERUSERNAME="rommi" \ DBPASS="" \ DBUSER="" \ DBHOST="" \ DBNAME='db.sqlite31' \ DBENGINE="django.db.backends.sqlite3" \ JENAHOST="http://localhost:3030" \ JENADATABASE="{0}/ds/{1}" \ python manage.py test kill -9 $pid Every time when I run the script above I get "Connection refused error" errno 111 in the middle of the execution even though my fuseki-server is up and even though the previous tests succeeded. I've also tried without the last command (kill -9), but it does not help. If I run the above commands manually everything goes fine. What can be the reason ? -
How to provide a validation check for inputting the right file path (remote or local server) in Django?
I have a form that should accept a file path (directory) if it's within a valid format (regardless of it being in a remote/local server i.e FTP) and does not contain any specific files i.e <'file_directory'>\pic.png'. If the path is not valid, it should not save it into the model. I have tried the following: views.py: from pathlib import Path as PATH #using pathlib since it's used on all OS platforms. def home(request): if request.method == 'POST': form = PForm(request.POST) if form.is_valid(): user_id = request.user.id folder_path = form.cleaned_data['folder_path'] path = PATH(folder_path) #using pathlib module to check if the folder_path exists. root, extension = os.path.splitext(folder_path) #checks if extension is seen in folder_path. if extension or not path.resolve(strict=True): messages.warning(request, "Path is not valid.") return redirect('home') else: #save the path to the model else: form = PForm() return render(request, 'template/home.html, {'form' : form}) The validation for checking file extensions work but once I enter an invalid directory path, I am getting this error: Exception Type: FileNotFoundError Exception Value: [WinError 3] The system cannot find the path specified: '<invalid pathname>' #eg 'var/html/www/pictures' How can I implement a better validation check and a way to handle the errors? Thank you in advance. -
uwsgi: OSError: write error during GET request
Here is the error log that I received when I put my application on a long run. Oct 22 11:41:18 uwsgi[4613]: OSError: write error Oct 22 11:41:48 uwsgi[4613]: Tue Oct 22 11:41:48 2019 - uwsgi_response_write_body_do(): Broken pipe [core/writer.c line 341] during GET /api/events/system-alarms/ Nov 19 19:11:01 uwsgi[30627]: OSError: write error Nov 19 19:11:02 uwsgi[30627]: Tue Nov 19 19:11:02 2019 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET /api/statistics/connected-clients/?type=auto&required_fields=0,11 Also I need to know the reason for the os write error and broken pipe in detail. -
Django check if next record will change (ifchanged, but in the future)
In Django, there is a very handy ifchanged function. However, instead of using ifchanged to look up if the current record has changed from the previous record, I am trying to find out if the next record will change from the current record. Something like this: {% for record in list %} {% ifchanged record.date %}<h1>{{ record.date }}</h1>{% endifchanged %} <p>- {{ record.title }}</p> {% ifwillchange record.date %} <p>View more details for <a href="list?date={{ record.date }}">{{ record.date }}</a></p> {% ifwillchange %} {% endfor %} Does something like this exist? If not, what would be another way to achieve this? Just FYI I am trying to print a link underneath each group of records that has a particular date, like so: Jan 10, 2020 Record 1 Record 2 Record 3 View more on Jan 10, 2020 Jan 11, 2020 Record 4 Record 5 View more on Jan 11, 2020 etc. -
Blocked by CORS policy on form submit - Django
I have a form on a website, where I have a form to capture the lead. - Tech is Php The action on this form goes to another django project where I save it to the database. - Tech is Django Now I have used django-cors-headers==2.4.0 for handling the CORS part. In my settings.py CSRF_TRUSTED_ORIGINS = ['www.test.com', 'test.com', 'https://test.com'] CORS_ORIGIN_WHITELIST = ( 'www.test.com', 'test.com', 'https://test.com' ) INSTALLED_APPS = [ 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware' ] Still after this I am getting this error when I submit the form(ajax function doesn't goes to he success instead it goes to the error): Access to XMLHttpRequest at 'https://test1.com/crm/addnewlead_website/' from origin 'https://test.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested What am i doing wrong? resource. -
Django form doesn't show error on template page
My code is exactly the same as https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html#rendering-bootstrap-forms this. But when I click on the "post" button in the template it shows me the same page without the errors like the field is required. In my virtualenv, Python 3.7.4, Django 2.2.7 and I've installed Django-widgets-improved. -
how do i return in my class based view after updating data
here is my views.py function: class ProfileUpdateView(UpdateView): model = UserProfile fields = ['first_name','last_name','username','gender','datetimepicker','p_photo','h_photo','subtitles','political_incline', 'about_me','birthplace','lives_in','country','province','city','occupation', 'relationship_status','website','phone_number','religious_belifs','political_incline', 'facebook','twitter','RSS','dibble','spotify'] AND HERE IS MY URLS.PY PATH: url(r'^updateprofile/(?P\d+)/$',views.ProfileUpdateView.as_view(success_url='/postlist/')), -
I want to pass a argument to Django meta class , like this
I can alternatively create different types of form, but that's tedious. So is it possible to pass the type to the form,then show the form accordingly ? This code shows NameError: name 'review_type' is not defined class Contest1_for_review(ModelForm, review_type): class Meta: model = Contest1 decision = review_type + '_decision' comment = review_type +'comment' fields = [ decision, comment, ] -
Django form data not saving into databsae
I have a form on web app, using to get the data and store into database. The problem is: I am using different fields along with 2 Date Fields. When I removed the 2 date fields from the Model and Form, the form data stores easily into database but when added again into the Model and Form, it dose not save anything into database. Model: name = models.CharField('Name', max_length=50, help_text='Co-worker name.') email = models.EmailField('Email', help_text='Co-worker email.') address = models.TextField('Address', help_text='Co-worker address.') phone = models.CharField('Phone Number', max_length=20, help_text='Co-worker phone number.') companyName = models.CharField('Company Name', max_length=80, help_text='Co-worker company name.', null=True, blank=True) workingLocation = models.CharField('Working Location', max_length=50, help_text='Co-worker working ' 'location.') workingShift = models.CharField('Working Shift', max_length=50, help_text='Co-worker working shift.', default='') workingSpace = models.CharField('Working Space', max_length=50, help_text='Co-worker working space.', default='') teamMembers = models.CharField('Team Members', max_length=15, help_text="Co-Worker's Team Size.", default='') coworkerPicture = models.ImageField('Co-Worker Picture', upload_to='../media/images/co-woker-pictures' , help_text='Co-worker Picture.', default='profile_pics/default.jpg', ) joiningDate = models.DateField('Joining Date', help_text='Joining Date of Co-worker',default=date.today, ) dob = models.DateField('Date of Birth', help_text='Date of Birth of Co-worker', default=date.today, View: def Coworkers(request): # If user is not logged In if not request.user.is_authenticated: return redirect('login') if request.method == 'POST': form = addCoWorkerForm(request.POST, request.FILES) print(request.POST) if form.is_valid(): form.save() messages.success(request, 'Co-Worker added successfully.') return redirect('admin/co-workers') c = … -
data retrieving from data base 1 after another in 1 page Django
guys i was building an online quiz computation.In the user side i need to display questions 1 at a time onclick next, next question should display.Here i am able to retrieve question from database.But all are displaying in 1 page like i have 1200 questions in total. what functionality and method i need to use here. language - python ; frame-work - django ; database - mysql; frontend - Html, css, javascript . thanks in advance.enter image description herebelow attachment is template