Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error 111 connecting to 127.0.0.1:6379 Connection refused using docker
I am trying to connect my celery with redis serve and getting this error in django. beat: Connection error: Error 111 connecting to 127.0.0.1:6379. Connection refused.. Trying again in 2.0 seconds... consumer: Cannot connect to redis://127.0.0.1:6379//: Error 111 connecting to 127.0.0.1:6379. Connection refused.. while my docker-compose file is like version: '3' volumes: postgresql_data: services: database: container_name: postgres hostname: sampleproject_database image: postgres:12-alpine environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} volumes: - postgresql_data:/var/lib/postgresql/data healthcheck: test: [ "CMD-SHELL", "pg_isready -U postgres" ] interval: 5s timeout: 5s retries: 5 ports: - "5432" app: container_name: sampleproject_app hostname: sampleproject_app build: context: . dockerfile: Dockerfile image: sampleproject command: > bash -c " python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " environment: - SECRET_KEY=${SECRET_KEY} - DEBUG=${DEBUG} - SENDGRID_API_KEY=${SENDGRID_API_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} - SITE_URL=${SITE_URL} - EMAIL_SENDER=${EMAIL_SENDER} - ASENTRY_DSN=${ASENTRY_DSN} - ENCRYPTION_KEY=${ENCRYPTION_KEY} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} env_file: .env ports: - "8000:8000" volumes: - .:/usr/src/app/ depends_on: - database - redis redis: image: redis:latest ports: - "6379:6379" celery: build: context: ./ dockerfile: Dockerfile command: celery -A sampleproject worker -l info volumes: - .:/usr/src/app/ environment: - DEBUG=${DEBUG} - SECRET_KEY=${SECRET_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} depends_on: - database - redis celery-beat: build: . command: celery -A sampleproject beat … -
Feeding image to a Django template
I've been working on a simple Django project for myself and I came into a little problem. When first developing the blog, I didn't make templates, I just made sure things were working properly, but now, I dived into making the templates and everything is working besides my header background-image. Before the templates, I was doing it like this: <header class="masthead" style="background-image: url({% static 'img/home-tech-bg.jpg' %})"> This was working just fine, but now that I'm trying to do the same as a template it doesn't work. It doesn't return me any errors, but the image doesn't display. What I did was the following: template base.html <header class="masthead" style="background-image: url({% block headerimage %} {% endblock %})"> blog.html {% load static %} {% block headerimage %} {% static 'image/image.jpg' %} {% endblock %} What is a better way to do this? -
Get the name of the submit button that was clicked in django
I have this form where I create submit buttons which each correspond to a Product object: <form action="/costcorrect/product_choice" method="post"> {% csrf_token %} {% for product in product_list %} <div class="product"> <img src="{{product.image_url}}" alt="{{product.name}}"> <h2>{{product.name}}</h2> <input type="submit" name="{{product.id}}" value="Choose Product"> </div> {% endfor %} </form> I want to get the name of the button the user clicks on, so I know which product was selected. Other questions (like this one) that are related to this had buttons with fixed names, so it was easy to refer to them. My issue is that I'm not sure what the names of the buttons will be, so I can't refer to them directly in views. -
Django Migrations not detecting is_active column
I created a custom user model using the AbstractBaseUser class (see source code below). However, after realising that the column I needed in the table should be called "is_active" not "active", I renamed the column in the models file, however, the migrations only removed the "active" column but didn't create an "is_active" column. Any ideas? class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=100, null=True) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user date_joined = models.DateTimeField(auto_now_add=True) manager_access = models.BooleanField(default=False) USERNAME_FIELD = 'email' # Email & Password are required by default. REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def get_full_name(self): return self.first_name + self.last_name def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.is_superuser @property def is_active(self): "Is the user active?" return self.is_active -
Django - How to filter products by price?
I am trying to build an E-Commerce application using Django. I am trying to add a price filter using select tag in HTML. So, every time select option changes I want to change to filter product by low-to-high or vice-versa. HTML Code <div class="d-flex flex-row-reverse" style="margin-right: 20px; margin-bottom: 20px;"> <label> <select class="bg-dark" name="price" id="priceFilter" onchange="getValue()"> <option value="normal">Sort by Price</option> <option value="low">Low to High</option> <option value="high">High to Low</option> </select> </label> </div> javascript function getValue() { let option = document.getElementById('priceFilter'); let value = option.value; let url = '/price_filter/'; fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({'value': value}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:', data) location.reload() }) } views.py def filterByPrice(request): data = json.loads(request.body) value = data['value'] print(value) if value == 'low': products = Product.objects.all().order_by('productDiscountedPrice') context = { 'products': products } return render(request, "Amazon/filteredResult.html", context) elif value == 'high': products = Product.objects.all().order_by('-productDiscountedPrice') context = { 'products': products } return render(request, "Amazon/filteredResult.html", context) else: products = Product.objects.all() context = { 'products': products } return render(request, "Amazon/filteredResult.html", context) So, the problem is, It is not getting redirected to filteredResult page, but value in getting printed in terminal. Any Idea why it is not getting redirected? -
How to add Django Template code in JavaScript innerHTML
I am trying to add a search feature for my Django project, but I have a problem knowing how to write Django Template in the Javascript Innerbox. I have an Item model as following: class Item(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) price = models.DecimalField(decimal_places=2, max_digits=100) discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True) timestamp = models.DateTimeField(default=timezone.now) Item list view as following: class ItemListView(ListView): model = Item paginate_by = 12 template_name = "store/product_list.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder) return context I have the following Script: <script> const data = '{{qs_json}}' const rdata = JSON.parse(data.replace(/&quot;/g, '"')) console.log(rdata) const input = document.getElementById('search_here') console.log(input) let filteredArr = [] input.addEventListener('keyup', (e)=>{ box.innerHTML = "" filteredArr = rdata.filter(store=> store['title'].includes(e.target.value)) console.log(filteredArr) if (filteredArr.length > 0){ filteredArr.map(store=>{ box.innerHTML += `<b>${store['title']}</b><br>` <------------------------------- Replace }) } else { box.innerHTML = "<b>No results found...</b>" } }) </script> I am trying to replace the innerHTML <b>${store['title']}</b><br> with <div class="col-4 mb-3"> <div class="card h-100"> <a href="{{item.get_absolute_url}}"> <embed src="{{ item.image.url }}" class="card-img-top" alt="..."/> </a> <div class="card-body"> <h5 class="card-title">{{ item.title }}</h5> <p class="card-text"> {% if item.description %} {{ item.description }} {% endif %} </p> </div> <div class="card-footer"> <small class="text-muted">{{ item.timestamp }}</small> </div> </div> </div> But the result is … -
How to initialize Neo4j driver on Django
I use Neo4j as an external database for additional requests in my Django project. There is an issue that I got stuck on, where should I initialize the Neo4j driver in my Django project? I do not want to recreate and close neo4j driver every time that requests came. So currently, I edited my settings.py file, I imported neo4j GraphDatabase and I initialized Neo4j driver as I mentioned below. ..settings.py from neo4j import GraphDatabase driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("test", "test")) But the problem is that I don't know if settings.py file the proper place to initialize Neo4j driver. Where should I initialize global variables in my Django project? Can you help me about this, please? Thanks. -
Calling function form another function to make code more DRY in Django
I'm not using DRF (yet) so I need to copy my code from view to view if i wanna have same functionality like seeing current items in my cart. I don't like that How can i call funcA that returns 2 variables in funcB, get them into context of funcB and render html with that data. def funcA(request): if request.user.is_authenticated: customer = request.user.customer else: customer = "abcd" customerTotal = 1234 context = { "customerTotal":customerTotal, "customer":customer, } def funcB(request,pk): funcA(request) product = Products.object.get(id=pk) context = { "customerTotal":customerTotal, "customer":customer, "product":product, } return render(request,'cart.html',context) -
Nested mutation Django + GraphQL
I am new to Django/Graphql/Graphene and struggling to write a nested mutation with several foreign keys and a many-to-many relation. I have read several posts on this topic but still struggling. I have highlighted several questions within the below code. It would be great to help me both on the foreign keys (Fare, Year) and on the Many-to-Many field (Parent), which I have not even included yet in the graphical request. It would be good to have help both on how to write the Python graphene code and then the Graphiql request. Many thanks to all Here is the code: Model (extract): class Student(models.Model): first = models.CharField(max_length=64) last = models.CharField(max_length=64) email = models.EmailField() phone = models.CharField(max_length=64) year = models.ForeignKey(Year, on_delete=models.CASCADE, related_name="students", blank=True) fare = models.ForeignKey(Fare, on_delete=models.CASCADE, related_name="at_fare", blank=True) parents = models.ManyToManyField(Parent, related_name="children", blank=True) Schema.py: class StudentType(DjangoObjectType): class Meta: model = Student // is the Student Type necessary???? class FareType(DjangoObjectType): class Meta: model = Fare class YearType(DjangoObjectType): class Meta: model = Year class ParentType(DjangoObjectType): class Meta: model = Parent Input object types: class StudentInput(graphene.InputObjectType): #id = graphene.ID() // is this field necessary?? first = graphene.String() last = graphene.String() email = graphene.String() phone = graphene.String() year = graphene.Field(YearInput) fare = graphene.Field(FareInput) parents … -
Django Forms and bootstrap - adding widgets works but not fully
I have problem with bootstrap in my django forms. In forms I have this code: make = forms.ChoiceField(choices=make_choices) make.widget.attrs.update({'class': 'form-control'}) And in tutorials I saw that it should be enough to render proper bootstrap choice field. But in my case it looks like this: Please notice: missing arrow indicating actual dropdown on the right grey select box is not wide enough, or rather box above is too wide? label "Make:" also doesn't look like proper bootstrap label. I checkout out several tutorials but in all of them adding this "{'class': 'form-control'}" in attrs was enough. I was also experimenting with django crispy forms but they were also not fully correct. What am I missing? What I did wrong? -
How to setup up new field in Django Model Serializer?
I have created a different model serilizers like LocationDetailSerializer, ListingDetialSerializer, ..so on. Each of their models share a OneToOne Relationship with a PropertySerializer's Model. class PropertySerializer(serializers.ModelSerializer): # location_detail = LocationDetailSerializer() # listing_detial = ListingDetialSerializer() . . . . . class Meta: model = Property fields = "__all__" While creating a PropertySerializer I also want fields like : location_detail, listing_details..passed with it. How to achieve that? -
How to set the FK automatically for Model in OneToOneRaltionship in Django?
Start of Property Model class Property(models.Model): # ? Relationships user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) # ? Fields property_unique_hash_id = models.UUIDField( default=uuid.uuid4, editable=False ) . . . . created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) def __str__(self): return "Property " + str(self.pk) Now I have divided subsections of Property Model in different models like: `LocationDetail`, `ListingDetail`... With them Property Model Shares a OneToOne Relationship. Example: ```python class ListingDetial(models.Model): # Relationships property = models.OneToOneField("properties.Property", on_delete=models.CASCADE) # ? Fields listing_property_type = models.PositiveSmallIntegerField( choices=choices.LISTING_PROPERTY_TYPE, default=choices.LISTING_PROPERTY_TYPE.single_family_detached, ) . . . . . def __str__(self): return "Listing Detail" + str(self.pk) # ***************************END*************************** Now I want to set the property id of ListingDetial Model automatically. How to do that? -
I need a couple development advices
First of all sorry for my English, I'm electronics eng. student and also working for a tech company for web development. The manager asks me today hey buddy we need a website and mobile app for tracking our inventory. I developed a couple of sites for the company with JavaScript and PHP. But I want to learn new things like react and Django. If I develop a website with react and Django, can I use their source code for a mobile app? -
Django Two Factor Authentication not working
I am trying to do the two-factor authentication set up for my Django project. Below is the configuration details settings.py 'django_otp', 'django_otp.plugins.otp_static', 'django_otp.plugins.otp_totp', 'two_factor', ... ] MIDDLEWARE = [ 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', ... ] LOGIN_URL = 'two_factor:login' LOGIN_REDIRECT_URL = 'two_factor:profile' TWO_FACTOR_PATCH_ADMIN = True TWO_FACTOR_CALL_GATEWAY = 'two_factor.gateways.fake.fake' TWO_FACTOR_SMS_GATEWAY = 'two_factor.gateways.fake.Fake' AUTH_USER_MODEL ='Products.CustomUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'two_factor': { 'handlers': ['console'], 'level': 'INFO', } } } urls.py urlpatterns = [ path('', include(tf_urls)), # path('admin/', admin.site.urls), ] when I access the url http://127.0.0.1:8001/account/login/ it navigates to the token generation page. when I scan the QR code with google authenticator and then when I enter the token system throws the error **not a valid token **. The application is already running with django default authentication using the custom user model. Now I am trying to incorporate the two factor authentication. Can someone guide me on what is missing in the above configuration?. -
Django Rest Framework Serializer Relations: How to get list of all child-child objects in parent's serializer?
I'm new to DRF and have just started building an API. I have three models, a child model connected to a parent model with a foreign key. Here is the simplified version of the model I have: union models: class Union(core_models.TimeStampedModel): # 공통 name = models.CharField(max_length=50) # 조합명 owner = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="owner" ) # 조합을 만든 계정 user models: class User(AbstractUser): nickname = models.CharField(max_length=20, blank=False) # 닉네임 password = models.CharField(max_length=100, blank=False) # 비밀번호 # 학력사항 education = models.ManyToManyField( education_models.Education, related_name="education", blank=True ) # 경력사항 career = models.ManyToManyField( career_models.Career, related_name="career", blank=True ) career models: class Career(core_models.TimeStampedModel): company = models.CharField(max_length=50) # 회사명 job = models.CharField(choices=JOB_CHOICES, max_length=50) # 직무 status = models.BooleanField() # 재직_상태 (재직상태면 True, 아니면 False) in documentation (https://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations), there is only parent-child case, but I create/update the career models in union serealizer. I think it's perfectly reasonable, but I couldn't understand what I'm missing here. How can I create/upate children-children in parent's serializer? -
My view doesn't save the instance from Form in Djagno
I'm trying make a comment section for my Q&A project.I made the model for comment , the form part in question_detail.html an , also the QuestionCommentForm() in form.py . model.py class QuestionComment(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add= True) body = models.CharField(max_length=200, null= True , blank = True, default ='') def __str__(self): return str(self.body) forms.py {%if c_form%} <form method="POST" action = action = "{% url 'blog:question-comment' question.pk %}">{% csrf_token %} {{c_form.media}} {{ c_form.as_p}} <button type = "submit" , name = "question_id", value = "{{question.pk}}", class ="btn btn-secondary btn-sm">submit comment</button> views.py @api_view(['POST','GET']) def question_comment(request, *args, **kwargs): form = QuestionCommentForm() print('finction comment started'*20) if request.method == 'Post': c_form = QuestionCommentForm(request.Post) if c_form.is_valid(): new_comment = c_form.save(commit=False) new_comment.refresh_from_db() new_comment.user = request.user new_comment.question = c_form.cleaned_data.get('question_id') new_comment.bldy =c_form.cleaned_data.get('body') context['c_form'] = c_form return render(request, 'blog/question_detail.html',context) class QuestionDetail(DetailView): template_name = 'blog/question_detail.html' model = Question context_object_name = 'question' count_hit = True def get_queryset(self): return Question.objects.filter(id = self.kwargs['pk']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) c_form = QuestionCommentForm() context = super(QuestionDetail,self).get_context_data(**kwargs) self.obj= get_object_or_404(Question, id = self.kwargs['pk']) self.object.save() self.object.refresh_from_db() answers = Answer.objects.filter (question_id = self.obj.id).order_by('-created_date') liked =self.obj.like.filter(id =self.request.user.id).exists() print('liked in class question not checked still' *10) comments= QuestionComment.objects.filter(question = self.kwargs['pk']) context['comments']= comments context["answers"]=answers context["liked "] = liked context['c_form'] = … -
Hello All, I'm trying to call the webpage but getting error while calling it. I'm new at learning Django so please suggest
THis is the views.py and getting error when I try to call the sports named function def index(request): ob=Com1.objects.all() return render(request,'index.html',{'ob':ob}) def sports(request,name): cat=Categ.objects.filter(name=name) com=Com1.objects.filter(categ_id=cat[0].id) return render(request,'sports.html',{'com':com}) This is the main URLs.. urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index,name='index'), path('sports/<str:name>',views.sports,name='sports'), AM I missing something to place or declare in Sports.html <li><a href="{%url 'sports'%}">Sports</a></li> -
Django claiming inconsistent migration history on first migration
I have been working on a project for a while, and I have been having no trouble with migrations. I decided reset the database and migrations, which I do from time to time. I went to delete all migrations, make them again, and after recreating the database, apply the migrations, at which point, I get the error "Migration users.0001_initial is applied before its dependency auth.0012_alter_user_first_name_max_length on database 'default'." Now, auth.0012_alter_user_first_name_max_length is apparently coming from django.contrib.auth, which is part of core django, so I don't see why I need any dependency on its migrations for a new project, yet whenever I make migrations on this project from the beginning, it adds a dependency to my user model of auth.0012_alter_user_first_name_max_length. I don't know why it does that, when it apparently wasn't doing that yesterday, but I am now having to remove that dependency from the user migration manually before it will migrate. What might cause this. Here is my users.models.py file. Maybe someone can figure out what would be so odd about it that it would do this. from django.contrib.auth.models import AbstractUser from django.db.models import CharField, EmailField from django.urls import reverse from django.utils.translation import gettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from … -
How to set cookie before setting context?
In Django to set cookies first I need to set render function. But i want to pass data from cookies to my template. How can i set cookies before setting context? Current code: def mainPage(httpRequest): # Set Render renderResponse = render(httpRequest, 'AppMain/index.html') # Get Cookies httpCookies = httpRequest.COOKIES # Get Empty Status isCookiesEmpty = True if len(httpCookies) == 0 else False # Empty State if isCookiesEmpty: # Set Cookies renderResponse.set_cookie('likedData', []) renderResponse.set_cookie('dislikedData', []) renderResponse.set_cookie('lovedData', []) # Return Page return renderResponse -
Creating a nested JSON from a value in Django Rest Framework
I'm very new to Django and the DjangoRest Framework and this is my first question on Stack overflow, please bear with me. I am trying to create a Django Rest API that can that to handle entries for an online raffle. So each entry would have details like name, email, and a string that represents the raffle entry in the form of numbers separated by spaces(Eg: "12,23,34,45,56,67"). So far, I've been able to do the basics and create a simple model, serializer, and views. What I need is to create a JSON similar to { "entry" : "12,23,34,45,56,67", "name" : "SampleName", "email" : "sample@sample.com", "values" : [ "one" : 12, "two" : 23, "three" : 34, "four" : 45, "five" : 56, "six" : 67 ] } models.py class EntryModel(models.Model): entry = models.CharField(null=False, max_length=17) name = models.CharField(null=False, max_length=100) email = models.EmailField(null=False) serializers.py class EntrySerializer(serializers.ModelSerializer): class Meta: model = EntryModel fields = ['entry', 'name', 'email'] views.py class EntryViews(viewsets.ModelViewSet): queryset = EntryModel.objects.all() serializer_class = EntrySerializer -
Using variables in Django template Loop/If Statement
Incoming noob Django question I have a Django template that receives two variables from a view: list_of_strings = ['non_target','target','non_target'] target_string = 'target' I want to make a dropdown menu of list_of_strings, & have the default value be target_string: <select name="list_of_strings" id = "list_of_strings"> {% for string in list_of_strings %} <option {% if string == target_string %} selected {% endif %} value="{{string}}">{{string}}</option> {% endfor %} </select> The above produces a dropdown menu with the first value in list_of_strings selected, i.e. 'non_target', so the if statement to select target_string doesn't appear to have worked. Hardcoding 'target' into the statement as per the below works: {% if string == 'target' %} selected {% endif %} My guess is target_string doesn't refer to the string variable. It works fine elsewhere, e.g. referring to it in an H1 element shows 'target': <h1>{{target_string}}</h1> Am I referencing target_string wrongly in the if statement? I've tried target_string, {target_string}, {{target_string}}, "{{target_string}}", "{target_string}", "target_string" as any good personwhohasnoideawhattheyredoing would do, to no avail. -
Django Error in Command Console AttributeError Models
I am getting the following error when I try and display my fields within the command prompt. Any idea what would be causing this? I've tried to adjust "return self.stakeholder" to a field listed above (e.g. return self.employee) but it presents the same error (still referencing 'stakeholder') models class Stakeholder(models.Model): employee = models.CharField(max_length=200) stakeholder_group = models.CharField(max_length=200) description = models.CharField(max_length=200) stakeholder_quadrant = models.CharField(max_length=200) def __str__(self): return self.stakeholder error Traceback (most recent call last): File "C:\Python38\lib\site-packages\werkzeug\local.py", line 72, in __getattr__ return self.__storage__[self.__ident_func__()][name] KeyError: 27232 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python38\lib\site-packages\werkzeug\debug\console.py", line 87, in displayhook stream = _local.stream File "C:\Python38\lib\site-packages\werkzeug\local.py", line 74, in __getattr__ raise AttributeError(name) AttributeError: stream During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python38\lib\site-packages\werkzeug\debug\console.py", line 89, in displayhook return _displayhook(obj) File "C:\Python38\lib\site-packages\django\db\models\query.py", line 255, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "C:\Python38\lib\site-packages\django\db\models\base.py", line 518, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "C:\Users\zzzz\Python\Price Tracking\Django\mysite\polls\models.py", line 38, in __str__ AttributeError: 'Stakeholder' object has no attribute 'stakeholder' -
Django Signals.py
I was wondering if it is possible to code a program such that when a blog post is made, a chatroom is created automatically and the blogpost maker is made admin of the chatroom. then everyone can talk about the blog post. I have studied django channels and django separately so I'm unsure how I can link those 2 together. Is it signals.py, and by any chance does anyone have sample code to show how it can be done? Thank you! -
How can I display data of a table based on common attribute value between two tables?
I am trying to display all data from table 'Class' based on common attribute value with table 'Student_class', where (Student_class.course_id==Class.id).There is an erron.How can I solve this? models.py class Class(models.Model): course_code = models.CharField(max_length=111, default="") course_title = models.CharField(max_length=111, default="") course_credit = models.FloatField(default=0.0) section = models.CharField(max_length=111, default="") teacher = models.ForeignKey(User, on_delete=models.CASCADE) code = models.CharField(max_length=10, default="", unique=True) def __str__(self): return self.course_title class Student_class(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) marks = models.FloatField(default=0.0) answered_ques = models.IntegerField(default=0) join_date = models.DateTimeField(default=datetime.now, blank=True) course_id = models.ForeignKey(Class, on_delete=models.CASCADE) views.py @login_required def my_class(request): current_user = request.user joined_class = Student_class.objects.filter(student=current_user).order_by('-id') all_class = Class.objects.filter() created_class = Class.objects.filter(teacher=current_user).order_by('-id') image = Profile.objects.get(user_id = current_user) params = {'created_class': created_class, 'teacher_name': current_user, 'image': image, 'all_class': all_class, 'joined_class': joined_class } return render(request, 'course/my_class.html', params) my_class.html {% for j in created_class%} {% for i in all_class%} {% if j.course_id==i.id %} <div class="service text-center"> <a href="#"><img src='{{image.profile_image}}' alt="Image" onerror="this.src='../../static/course/images/default-avatar.jpg'" style="border-radius: 50%;width: 80px;height: 80px; margin-left: 130px;"class="img-fluid"></a> <div class="px-md-3"> <h3><a href="#">{{i.course_code }} {{i.course_title }}</a></h3> <p>Course credit: {{i.course_credit}}<br> {{i.section}}</p> </div> </div> {% endif %} {% endfor %} {% endfor %} -
Serializing/deserializing a foreign key in django rest framework
I'm using the Django rest framework to create an API. Say I have the following models: class Category(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Item(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, related_name='items') def __unicode__(self): return self.name I want to write a serializer for Item such that it returns "category_name" during serialization (i.e. read) but then also takes "category_name" back and converts it into category during deserialization (i.e. write) [you can assume that category_name is unique in its table] I was able to find this link which solves the problem for reads but doesn't work for writes. class ItemSerializer(serializers.ModelSerializer): category_name = serializers.CharField(source='category.name') class Meta: model = Item fields = ('id', 'name', 'category_name') Is there a way to modify it such that it can be used to populate new items via an API?