Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: index page's url configuration not working after deployment
Everything works fine on local server but when deployed to lightsail, index page just opens the default django page with this rocket picture telling url configuration is missing, meanwhile all the other url combinations work just fine. main project url: path('',include("mainpage.urls")), mainpage url: urlpatterns = [ path('', views.index, name= "index"), ] On local server http://127.0.0.1:8000/ returns the mainpage but when the app is deployed public-ip/ returns the default django success page. -
How to get boolean result in annotate django?
I have a filter which should return a queryset with 2 objects, and should have one different field. for example: obj_1 = (name='John', age='23', is_fielder=True) obj_2 = (name='John', age='23', is_fielder=False) Both the objects are of same model, but different primary key. I tried usign the below filter: qs = Model.objects.filter(name='John', age='23').annotate(is_fielder=F('plays__outdoor_game_role')=='Fielder') I used annotate first time, but it gave me the below error: TypeError: QuerySet.annotate() received non-expression(s): False. I am new to Django, so what am I doing wrong, and what should be the annotate to get the required objects as shown above? -
Vue.js - push method for object throws Type Error
I am using push() method to add data to an object and receiving an Error: Uncaught (in promise) TypeError: this.message.push is not a function Some data is received from an API call, which is to be added to the object. var price = new Vue({ delimiters: ["[[","]]"], el: '#app', data: { message: {} }, mounted () { {% for i in arr %} axios .get('https:apicall/symbol={{ x }}') .then(response => (this.message.push({name : response.data.price , cost: response.data.price.regularMarketPrice.fmt})) {% endfor %} } }) However when I changed: message: [] and .then(response => (this.message.push(response.data.price)) it worked fine. I am using Vue in Django framework and am new to Vue.js -
Query a range of dates in range of dates in Django model
I m working in hotels reservation project, In which have a model for "Room" in which there is a a specific number of rooms available for booking per day ... I created a "Booking" model in which i ll save every booked room, with ForeignKey for "Room" model, and booking_from , booking_to fields .. What i need now is to query availability of free rooms in every single date in the range between the (from, to) fields ... Putting in consideration that i ll use a range (from, to) of the user input in search engine.. Finally, I ll have a date range of the user input that i want to check if every single day is in the Booked dates range too ... And if so, i ll need to count the number of this query result to check if it is possible to book a room or not. models.py class Booking(models.Model): room = models.ForeignKey( 'Room', on_delete=models.CASCADE, null=True, related_name="roomtype_set") booked_from = models.DateField(null=True) booked_to = models.DateField(null=True) def __str__(self): return '{} / {}'.format(self.room_type, self.booked_from) class Room(models.Model): room_type = models.ForeignKey(RoomTypesNames, on_delete=models.CASCADE) number_of_rooms_available_per_day = models.PositiveIntegerField() -
How to add field to django.contrib.auth forms
I want to add fields to django.contrib.auth forms. Is there anyway to do that? from django.contrib.auth import get_user_model, forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ User = get_user_model() client = Client(URL, API_KEY) class UserChangeForm(forms.UserChangeForm): class Meta(forms.UserChangeForm.Meta): model = User class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( { "duplicate_username": _( "This username has already been taken." ) } ) class Meta(forms.UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) Usercreationform is basically the ACCOUNT_FORMS signup and I am using django allauth forms but I cant figure out how to add a field to it e.g phone number. -
how do i add http host header: '0.0.0.0:8000 to ALLOWED_HOSTS to successfuly run django server?
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 20, 2020 - 13:54:55 Django version 3.0.8, using settings 'django_app.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Bad Request: / [20/Jul/2020 13:55:29] "GET / HTTP/1.1" 400 65263 Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Bad Request: /favicon.ico [20/Jul/2020 13:55:32] "GET /favicon.ico HTTP/1.1" 400 65300 ^Cemma@emma-HP-Notebook:~/django-projects/django_app$ python3 manage.py runserve0.0.0.0:8000 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 20, 2020 - 13:57:31 Django version 3.0.8, using settings 'django_app.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Bad Request: / [20/Jul/2020 13:58:43] "GET / HTTP/1.1" 400 65250 Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Bad Request: /favicon.ico [20/Jul/2020 13:58:46] "GET /favicon.ico HTTP/1.1" 400 65287 Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Bad Request: / [20/Jul/2020 14:54:41] "GET / HTTP/1.1" 400 65250 Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. … -
In django admin database I am not getting expected view
In django admin database I am not getting expected view. I am following the tutorials to make a quiz app in Django. I did exactly as shown in video but still I am not getting same output. I have attached the picture of expected view and picture of what I am getting. Getting This: Expecting This: models.py (in quiz): from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Quiz(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=70) slug = models.SlugField(blank=True) roll_out = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['timestamp',] verbose_name_plural = 'Quizzes' def __str__(self): return self.name class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') label = models.CharField('Question', max_length=255) order = models.IntegerField(default=0) def __str__(self): return self.label class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') label = models.CharField('Answer', max_length=255) is_correct = models.BooleanField('Correct answer', default=False) def __str__(self): return self.label class QuizTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) score = models.IntegerField(default=0) completed = models.BooleanField(default=False) date_finished = models.DateTimeField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username class UserAnswer(models.Model): quiz_taker = models.ForeignKey(QuizTaker,on_delete=models.CASCADE) quistion = models.ForeignKey(Question,on_delete=models.CASCADE) answer = models.ForeignKey(Answer,on_delete=models.CASCADE) def __str__(self): return self.question.label In admin.py from django.contrib import admin import nested_admin from .models import Quiz, Question, Answer, QuizTaker, UserAnswer # … -
I am creating a products page for my site using python django and postgresql.I am having a problem in comparing fields from two tables
Currently in a database i have two tables 1.Category(id , type) and 2.Products(id,category,name,price). I want to display the product only when the "type of category" is same as "category of products". This is how i am proceeding but its showing error. {% for i in types %} {% for j in prods %} {% if i.type== j.category %} <div class="product-img"> <img src="{{j.disimage.url}}" alt=""> </div> <div class="product-caption"> <h4><a href="#">{{j.name}}</a></h4> <div class="price"> <ul> <li>RS {{j.currentprice}}</li> <li class="discount">RS {{j.originalprice}}</li> </ul> </div> </div> {% endif %} {% endfor %} {% endfor %} this line is showing error.{% if i.type== j.category %} Please tell me how to implement it.Thanks -
error ModelForm has no model class specified in django
i am working with django and i have the form: from django import forms from clientes.administrativo.models import Customer class CustomerForm(forms.ModelForm): """Formulario para el catálogo de clientes""" model = Customer class Meta: fields = ['code_customers', 'trade_name', 'legal_name','name_owner', 'name_manager','address','email','phone','city','post_code','customers_type', 'locked','special_credit','tax_exempt','distributor','customers_subgroup', 'final_consumer','retention_agent','nit','contac'] def clean(self): cleaned_data = super().clean() def save(self, commit=True): model = super().save(commit=False) if commit: model.save() return model But when i try to do this save() with this method: @api_view(['POST', 'PUT', 'GET']) @permission_classes([LoginRequired]) @renderer_classes([JSONRenderer]) def register_customer(request, format=None): customerFM = CustomerForm(request.data) if customerFM.is_valid(): customerFM.save() return {'success': True,'message': ''} return {'success': False,'message': 'Hubo un error, por favor intente nuevamente..'} I get the error ModelForm has no model class specified... Any help with this? Thank you!... -
Django: Can we use Joins in filter(id__in = RawSQL(),[])
I want to use join in Django QuerySet, not RawQuerySet records = MailBoxEmailViewLog.objects.filter(evl_id__in=RawSQL( '''SELECT a.*, b.* FROM AT_MailBoxEmailViewLogs a INNER JOIN AT_MailBoxs b ON b.mail_box_id = a.evl_mail_box_id''', [] )).values() return HttpResponse(records) I run this but I get this error ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. (116) (SQLExecDirectW)') -
Why I can open my website through my own IP address with this setting
I want to use Apache and Django together. However, I can use myIP:8080 to access the page if I only use the Django as server, I can't use myIP to directly access the page after I finished all the setting of Apache. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['myIP'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'charts.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'charts.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = … -
Django authentication problem in HTML not working
I wrote a small application for a social media site and I have a problem. I'm using {% if user.is_authenticated %} after I log in I'm getting the options in the navbar which should not be displayed for an authenticated user. The page keeps bouncing between two pages. I have made a video of the problem. Please have a look at it. Video. Files tree image: File tree base.html <!DOCTYPE html> {% load static %} <html > <head> <title>Colab</title> <link rel="stylesheet" type="text/css" href="{% static 'reg_sign_in_out/style.css' %}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Colab</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'posts:home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a> {%else%} <a class="nav-item nav-link active" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="{% url 'reg_sign_in_out:user_login' %}">Login</a> <a class="nav-item nav-link" href="{% url 'reg_sign_in_out:registration' %}">Register</a> {% endif %} <!-- <a class="nav-item nav-link disabled" href="#">Disabled</a> --> </div> </div> </nav> <div class="container"> {% block body_block %} {% endblock body_block %} </div> </body> </html> posts/urls.py app_name = "posts" urlpatterns = [ path('home/',views.home,name='home'), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += … -
"exceptions.AttributeError: exit" troubleshoot
I am getting this message when a part of my code gets executed. Here the output with error and after the code section where the error is generated. The same code works well on ubuntu x86 arch but not on armv7 where I get this message. I think some arm lib are not happy with this code so I m wondering if I can avoid the "with.. conn". Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/basic.py", line 572, in dataReceived why = self.lineReceived(line) File "/usr/local/lib/python2.7/dist-packages/twisted/web/http.py", line 2155, in lineReceived self.allContentReceived() File "/usr/local/lib/python2.7/dist-packages/twisted/web/http.py", line 2284, in allContentReceived req.requestReceived(command, path, version) File "/usr/local/lib/python2.7/dist-packages/twisted/web/http.py", line 946, in requestReceived self.process() --- --- File "/usr/local/lib/python2.7/dist-packages/twisted/web/server.py", line 235, in process self.render(resrc) File "/usr/local/lib/python2.7/dist-packages/twisted/web/server.py", line 302, in render body = resrc.render(self) File "/usr/local/lib/python2.7/dist-packages/twisted/web/resource.py", line 265, in render return m(request) File "/home/pi/pol/pol/server.py", line 347, in render_GET res = self.feed.getFeedData(feed_id) File "/home/pi/pol/pol/feed.py", line 155, in getFeedData with closing(get_conn(self.db_creds, dict_result=True)) as conn, conn as cur: exceptions.AttributeError: exit def getFeedData(self, feed_id): # get url, xpathes feed = {} with closing(get_conn(self.db_creds, dict_result=True)) as conn, conn as cur: cur.execute("""select f.uri, f.xpath as feed_xpath, fi.name, ff.xpath, fi.required from frontend_feed f right join frontend_feedfield ff on ff.feed_id=f.id left join frontend_field fi on fi.id=ff.field_id where f.id=%s""", (feed_id,)) … -
Django rest framework to_representation must be implemented
This issue has similar headings to other threads on this forum, but I'm sure this is not a duplicate because I didn't overwrite my pagination details or anything (which turned out to be the cause in other questions). Anyways, Django raised to_representation() must be implemented. I'm completely stuck as there is no relevant documentation regarding this (please comment if you have some) and my case didn't fit in with other people's. For those of you that think I didn't include everything in the error message, the error message is just this short and ambiguous. View this on github issues Code: settings INSTALLED_APPS = ['rest_framework',] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } view from rest_framework import viewsets from .models import Todo from .serializers import TodoSerializer class TodoViewSet(viewsets.ModelViewSet): queryset = Todo.objects.all() serializer_class = TodoSerializer serializers from .models import Todo from rest_framework import serializers class TodoSerializer(serializers.BaseSerializer): class Meta: model = Todo fields = ['title', 'desc', 'level', 'created'] urls from django.urls import path, include from rest_framework import routers router = routers.DefaultRouter() router.register(r'todos', views.TodoViewSet) urlpatterns = [ path('api/', include(router.urls)), ] Many thanks in advance. Note: in case you're wondering is this all, this IS all as I jus started to learn drf a few … -
Django and Yubikey integrate
I want to integrate Yubikey with my Django application. Whenever I try to add a 2FA Yubikey: localhost:8080/account/login/ I get a 403 HTTP Forbidden error. How do I implement the Yubikey in Django, because when I use these tutorials then the implementation fails. When I follow the example here to do the same I get a Server Error 500 I followed these tutoriols: django-two-factor-auth django-otp-yubikey djangp-otp This is what I have done: pip install django-two-factor-auth pip install django-otp-yubikey pip install django-otp I use Python 3.7.3 and Django 3.0.8 In my settings.py I added: INSTALLED_APPS = [ ... # OTP 'django_otp', 'django_otp.plugins.otp_static', 'django_otp.plugins.otp_totp', 'two_factor', 'otp_yubikey', ... ] MIDDLEWARE = [ ... 'django_otp.middleware.OTPMiddleware', ... ] LOGIN_URL = 'two_factor:login' TWO_FACTOR_PATCH_ADMIN = True In my urls.py I added: from two_factor.urls import urlpatterns as tf_urls from django_otp.views import LoginView ... urlpatterns = [ ... # OTP path('', include(tf_urls)), ... ] And in my views.py I have added: from django_otp.decorators import otp_required @otp_required def home_view(request): return render(request, 'home.html', {'result': 'test') My home.html is simple: <html> <head></head> <body><p>test</p></body> </html> -
Does django_background_tasks support django 3 and python 3.7?
app/tasks.py from background_task import background @background(schedule=60) def schedule_task(): print('running_tasks') app/views.py schedule_task(repeat=300, repeat_until=obj.end_date) I have placed django_background_tasks into the INSTALLED_APPS and run migrate. But When I try to run the tasks with the command python manage.py process_tasks the command doesn't work at all. When I hit the enter after writing the command nothing happens. -
How to filter choice field by the type of user Django-Python
I have created a customer User model and I have another model Enquiry. I enquiry model there is one service field that has relation with the custom User model. I want the field service is filtered by the user type. I want that the service filed will on show me the staff user choice only. Here is my models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254,unique=True) name = models.CharField(max_length=254, null=True) email = models.EmailField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_Customer = models.BooleanField(default=False) is_Service_Provider = models.BooleanField(default=False) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def get_username(self): return self.username class Enquiry(models.Model): name = models.CharField(max_length=254 , null=False) email = models.EmailField(max_length=254, null=False) phone_no = models.IntegerField(null=False) service_requied = models.ForeignKey('accounts.Category', on_delete=models.CASCADE, null=False) subcategory = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE, null=False) country = models.ForeignKey('accounts.Country', on_delete=models.CASCADE, null=False) state =models.ForeignKey('accounts.State', on_delete=models.CASCADE, null=False) city = models.ForeignKey('accounts.City', on_delete=models.CASCADE, null=False) address = models.CharField(max_length=254, null=False) defects = models.TextField(max_length=254, null=False) service = models.ForeignKey('accounts.User', on_delete=models.CASCADE, null=False) def __str__(self): return self.service.username Thanks in advanced. -
DJANGO - FileNotFoundError: [Errno 2] No such file or directory: '' when trying to acess a file
I'm accessing a function from a script that basically reads a JSON file and returns some value. main/randomgenerator/generatorran.py def getName(): with open('names.json','r') as names: .... The function works normally when executing it manually (python generatorran.py) I'm currently importing that function and calling it when creating a model. main/models.py from main.randomgenerator import generatorran class myModel: ... model_name = models.CharField(max_length=100,default=generatorran.getName()) When applying migrations it throws an error FileNotFoundError: [Errno 2] No such file or directory: '' when trying to acess a file The same happens when I move the function inside of the models.py Is there another way to read data from external files,am I missing something? -
Trying to render a python dictionary into django template with javascript
Im trying to render a python dictionary into my django template using ajax. I have some results from the whoisLookup which i want to render in certain table rows. Be gentle im litteraly new to django and JavaScript! My views.py code def whois_lookup(request): if request.is_ajax(): domain = request.session.get('domain_or_ip') res = whois.whois(domain) data = {'message': 'whois-lookup completed.', 'domain_name': res.domain_name } return HttpResponse(json.dumps(data), content_type='application/json') else: raise Http404 what i tryed in my .js file. $(document).ready(function () { $('#whois-btn').click(function () { $.ajax({ type: "GET", url: "/WanDashboard/whoisLookup/", beforeSend: () => { $(".ajax_loader").show(); console.log('BeforeSend whoisLookup'); }, success: function (data) { # this works. alert(data.message); # this does not work alert(data.domain_name) }, complete: () => { $(".ajax_loader").hide(); console.log('Completed whois ajax request.'); } }); }); }); -
Relate existing object in django nested serializer's create method
I am trying to overwrite the create method in django REST's nested serializer. I have three models Project => Network => Building. Project and Network are related via m2m and a network can contain many projects. What I am trying to do now is to send a Network and create buildings at the same time while relating (an) already existing project(s) to the network. What I can do successfully is: I can send a network and create buildings and also create projects. This works great like this: if ('buildings' and 'projects') in validated_data: buildings = validated_data.pop("buildings") projects = validated_data.pop("projects") network, _ = Network.objects.get_or_create(**validated_data) for building in buildings: network.buildings.add(Building.objects.create(**building)) for project in projects: network.projects.add(Project.objects.create(**project)) network.save() else: network, _ = Network.objects.get_or_create(**validated_data) network.save() return network But my problem is that I do not want to create a new project. I want to relate the network to an already existing project. But no matter how I change the code it always tells me: project already exists when I send an existing project with my json-data. I am pretty sure that REST checks the data before and that validated data can't contain existing projects in this case. I tried overwriting validate and just return the … -
Djang forms ModelChoiceField Use __Str__ or lable_for_Instance and how?
Upon rendering ModelChoiceField as radio buttons in template it returns 'shareholder Object(2) as oppose to data in field name. Somewhere in my view form.fields['shareholder'] = forms.ModelChoiceField( empty_label=None, queryset=ShareHolder.objects.filter(session_key=mykey), to_field_name="id", widget=forms.RadioSelect(), required=False ) In my template {% for sh in form.shareholder %} <div class="radio-group"> {{ sh }} </div> {% endfor %} my model is class ShareHolder(models.Model): session_key = models.CharField(max_length=40, null=True) # Person first_name = models.CharField(max_length=25, null=True, blank=True) middle_name = models.CharField(max_length=25, null=True, blank=True) last_name = models.CharField(max_length=25, null=True, blank=True) # Company company_name = models.CharField(max_length=256, null=True, blank=False) Now i could use the good old str function and i would get my values, but is there an alternate? I tried to used to add the following in my forms file class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "My Object #%i" % obj.id and then replaced the view code with form.fields['shareholder'] = forms.MyModelChoiceField( But when i run this it says module cannot find MyModelChoiceField. Having said this i donot understand how the lable_form_instance works in the first place. My fear with using str is that if i need to use the model another way then Str will need to be changed. Any pointers? -
Ruby on Rails API - The best Way to retrieve all model-related data
I have been doing my first API project on RoR today. How can we retrieve all model-related data? If we look on MVC pattern and many layers architecture, we will see that all a database logic must be in a model layer (like repository in Java/.NET). A Controller or a Serializator don't have to be responsible for that, it must do Repository or something like that. We do it in Serializator in Django, retrieve all model-related data from its. What about RoR? When I just tried to retrieve all my news from a category, I saw only a category and nothing anymore. When I added an include method in my category controller (show method), it worked: render json: @category, include: [:news] It works, that's great. But it breaks at least one MVC principle, we don't have to put any database logic in a controller. But this method (include) looks like a hack. Do we have a better way for it? I suppose it might be like in Django, we can do it in serializator. Could you help me with it? I wanna remove any logic from my controllers And the second question. Is it correct to use an include method … -
What is the purpose of building a docker image inside a compose file?
I was reading Quickstart: Compose and Django when I came across "defining a build in a compose file". Well I've seen it before but what I'm curious about here is what's the purpose of it? I just can't get it. Why we just don't build the image once (or update it whenever we want) and use it multiple times in different docker-compose files? Here is the Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ And here is docker-compose.yml: version: '3' web: # <<<< # Why not building the image and using it here like "image: my/django"? # <<<< build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" You might say: "well, do as you wish!" Why I'm asking is because I think there might be some benefits that I'm not aware of. PS: I mostly use Docker for bringing up some services (DNS, Monitoring, etc. Never used it for development). I have already read this What is the difference between `docker-compose build` and `docker build`? -
Django 'objects.filter()' is not working?
I am trying to filter my products based on the categories but the Listing.object.filter(category = category) is not able to filter as desired and return EMPTY every time. On the bottom code at views.py where the function is category with an argument as well category. Maybe there is some logical error from my side, any help would be appreciated. Here is my code: Here is my models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings CATEGORY_CHOICES = ( ('MC','Mens Clothing'), ('WC','Womens Clothing'), ('G','Games'), ('T','Tech'), ('BP','Beauty Products'), ('O','Others'), ) class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length = 100) price = models.FloatField() description = models.TextField() image = models.URLField(blank = True) time = models.DateTimeField(auto_now_add=True) category = models.CharField(choices = CATEGORY_CHOICES, max_length = 2) winner = models.ForeignKey(User, on_delete=models.CASCADE, null = True, blank = True, related_name="winner") user = models.ForeignKey(User, on_delete=models.CASCADE) availability = models.BooleanField(default=True) def __str__(self): return self.title My views.py def index(request): items = Listing.objects.filter(availability = True) category_list = [] for d,k in CATEGORY_CHOICES: category_list.append(k) context = { 'items': items, 'title': "Active Listing", 'categories': category_list } return render(request, "auctions/index.html", context) def categories(request): data = [] for d,k in CATEGORY_CHOICES: data.append(k) context = { 'categories': data } return render(request, "auctions/categories.html", context) def category(request, … -
How do I give each user different form in Django formset?
So, I'm trying to give each user his/her own form in Django. I'm giving users same question, and trying to let them input their own answers in modelformset_factory. First let me show you my code. (I'll skip the codes regarding question model, since the problem is in the answer form.) models.py class Answer(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None) questionNumber = models.IntegerField(null=True, default=None) answer = models.CharField(max_length=500) def __str__(self): return self.answer forms.py class AnswerForm(forms.ModelForm): answer = forms.CharField(max_length=500) class Meta: model=Answer fields=['answer',] def answerSheet(request): AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, extra=1) formset = AnswerFormSet(initial=[ { 'authuser':request.user } ]) if request.method == "POST": formset = AnswerFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('index') context = { 'formset':formset, } return render(request, 'formset/index.html', context) I figured initial = [{'authuser':request.user}] part will do what I intended, but apparently it doesn't. What I get instead is the same accumulated answers in formset, regardless of which user I log into. What I want, again, is to have different formset to different users. What do you think is the problem? Thank you very much in advance. :)