Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having posts separated by more than one category on the Home Page|Django
I want to divide the home page into categories. And categories should contain post titles. I can redirect categories in another url, but I can't show it on the home page. i have 2 models: blog and category models.py class Category(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children'); title = models.CharField(max_length=120, verbose_name='kategori') slug = models.SlugField(unique=True, editable=False) class Blog(models.Model): user = models.ForeignKey('auth.User', verbose_name='yazar', on_delete=models.CASCADE, related_name='blogs') title = models.CharField(max_length=120, verbose_name='başlık') # content = models.TextField(verbose_name = 'metin') content = RichTextField(verbose_name='metin') category = models.ForeignKey(Category, on_delete=models.CASCADE, default='') image = models.ImageField(null=True, blank=True, verbose_name='foto') publishing_date = models.DateTimeField(verbose_name='tarih') onem = models.BooleanField(default='True') slug = models.SlugField(unique=True, editable=False) view.py from django.shortcuts import render # Create your views here. from blog.models import Blog,Category def home_view(request): categorys = Category.objects.all() blogs = Blog.objects.all() r =Blog.objects.filter(category__title=Blog.category) return render(request,'index.html', {'blogs' : blogs, 'categorys' : categorys, 'r':r,}) def about_view(request): return render(request, 'about.html' , {}) def category_detail(request, cats): category_posts = Blog.objects.filter(category__title=cats) return render(request, 'category.html' , {'cats':cats, 'category_posts':category_posts, }) How should the index.html structure be? -
django.db.utils.IntegrityError: NOT NULL constraint failed: unesco_site.category_id
I am trying to populate database from data in the csv file using a python script. I did some research but couldn't find a relevant example rather I found python packages that would load csv. And there some articles guiding on how to upload csv file which isn't what I wanted. Following is a glimpse of load.csv file. There are 11 columns as you can see. # models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=128) def __str__(self): return self.name class State(models.Model): state = models.CharField(max_length=25) def __str__(self): return self.name class Region(models.Model): region = models.CharField(max_length=25) def __str__(self): return self.region class Iso(models.Model): iso = models.CharField(max_length=5) def __str__(self): return self.iso class Site(models.Model): name = models.CharField(max_length=128) year = models.IntegerField(null=True) area = models.FloatField(null=True) describe = models.TextField(max_length=500) justify = models.TextField(max_length=500, null=True) longitude = models.TextField(max_length=25, null=True) latitude = models.TextField(max_length=25, null=True) #one to many field category = models.ForeignKey(Category, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) iso = models.ForeignKey(Iso, on_delete=models.CASCADE) def __str__(self): return self.name I'm not being able to make the relationship among the models while inserting data. Earlier, I had used get_or_create() method but I was recommended to not to use it as I had no defaultvalue to be given and used create() method. Somewhere … -
Deploying Django with Nginx, Gunicorn and Supervisor
I'm trying to deploy my Django app with Nginx and Gunicorn by following this tutorial, but I modified some steps so I can use Conda instead of ViritualEnv. The setup looks like this: Nginx replies with my Vue app Requests from Vue are made to api.mydomain.com Nginx listens to api.mydomain.com and directs requests to Gunicorn's unix socket Things I've checked: I can see the Vue requests in Nginx's access.log. I can also see those requests with journalctl -f -u gunicorn and in my supervisor.log. When my Django app starts, it's creates a log file, so I can see that Gunicorn starts it. But Django is not responding to requests from the unix socket. I can see a response from Django when I ssh in and run the following command: curl --no-buffer -XGET --unix-socket /var/www/mydomain/run/gunicorn.sock http://localhost/about. This command only gives a response when http://localhost is included. My Nginx, Supervisor and Gunicorn configurations all use the full path to gunicorn.sock. Should I see Django running on port 8000 or anything if I do something like nmap localhost? I saw another post mention that Nginx should point to port 8000 and that gunicorn should be run with either: gunicorn --bind 0.0.0.0:8000 <djangoapp>.wsgi --daemon … -
How to compare 2 fields from 2 different models in Django?
I want to compare 2 fields from 2 different models and here is the idea behind it. Teacher can create Class which has ManytoManyField with Student model. When the Class model is created it will generates a random_code and Students will have to enter that code via EnterCode model to join the Class model. models.py class Class(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) random_code = models.CharField(max_length=250, default=uuid.uuid4().hex[:6]) subject = models.CharField(max_length=150) class EnterCode(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE) code = models.CharField(max_length=50) class Teacher(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) So the Class object 1 will generates a code and when student enters that code it will adds that student to the student field (ManyToManyField) in Class Model. How can I compare code with random_code and add Student to ManytoManyField? -
Patch a class method used in a view
I'm trying to test my view given certain responses from AWS. To do this I want to patch a class I wrote to return certain things while running tests. @patch.object(CognitoInterface, "get_user_tokens", return_value=mocked_get_user_tokens_return) class TestLogin(TestCase): def test_login(self, mocked_get_user_tokens): print(CognitoInterface().get_user_tokens("blah", "blah")) # Works, it prints the patched return value login_data = {"email": "whatever@example.com", "password": "password"} response = self.client.post(reverse("my_app:login"), data=login_data) Inside the view from "my_app:login", I call... CognitoInterface().get_user_tokens(email, password) But this time, it uses the real method. I want it to use the patched return here as well. It seems my patch only applies inside the test file. How can I make my patch apply to all code during the test? -
Good option for Back end language [closed]
Is Go a good language to begin with Backend Development or other framework accept Express who uses React.js as Frontend? and which backend language do you use? -
I am working on a web app using Django, running on Nginx, and I am getting 111 connection refused, and I cant work out why
I have previously configured an app in the exact same way but when I updated Ubuntu, I broke my python install. I fixed python, and tried to set up another app in the exact same way, using the same tutorials, but I am getting a 111 error when I try to connect. I can connect if I run the app using gunicorn (which I only tried because it wasn't working using nginx), but I want to find the problem and fix it. As far as I can see everything is configured according to the documentation I went through. Here is the uwsgi config file # glossbox_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /usr/local/apps/glossbox/glossbox # Django's wsgi file wsgi-file = /usr/local/apps/glossbox/glossbox/glossbox/wsgi.py # the virtualenv (full path) home = /usr/local/apps/glossbox/venv plugins = python # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = server 127.0.0.1:8001 # ... with appropriate permissions - may be needed chmod-socket = 664 clear environment on exit vacuum = true here is the nginx conf file: # glossbox_nginx.conf # the upstream component … -
Django CharField as primary key still allow Null value to be save
Currently i have the following model that i would like to set CharField as primary key( my database is Mysql) class Customer(models.Model): class Meta: db_table = "customers" verbose_name = _('Customer') verbose_name_plural = _('Customers') customer_id = models.CharField(_('Customer ID'),max_length=255, primary_key=True) name = models.CharField(_('Name'), max_length=255) created_at = models.DateTimeField(auto_now_add=True) In the document it stated that : primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object. In Mysql the primary key has the following structure: customer_id, type=varchar(255), collation=latin1_swedish_ci, Attributes=blank Null=No, Default=None,Comments=blank, Extra=blank but when i try to use the save() method with null value for primary key: Customer.objects.create(customer_id=None, name="abc") It still save Null value in the primary key without returning any error or validation, why is that? -
Using django as a RESTAPI, how to run some modules(.py or .exe) and return result?
I made my web site using node.js. If I clicked some button at website, modules(.exe files) are run and make some result. That results are applied in next page. In this situation, I want to change running modules using RESTAPI. Can I develop RESTAPI using django? And Is it possible? -
Django Object is Not Serializable CommandError using Dumpdata with Natural Keys
I am trying to use 'natural keys' for serialization (docs) in a "manage.py dumpdata" command: python manage.py dumpdata --natural-primary --natural-foreign --indent 4 --format json --verbosity 1 > tests\test_fixtures\test_db2.json and I am getting the following error when I use --natural-foreign on other apps that use the Project or Task model (which they all must by design): CommandError: Unable to serialize database: Object of type Project is not JSON serializable Exception ignored in: <generator object cursor_iter at 0x000001EF62481B48> Traceback (most recent call last): File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\site-packages\django\db\models\sql\compiler.py", line 1586, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. If I just dumpdata from this, the 'projects' app, it works, but other apps are built with entities related to Project or Task and there the --natural-foreign option fails. The problem occurs when a model (say Question) calls for a natural_key from Task, which includes a for a natural_key from Project. If I use the Pycharm Python Console to access querysets of Projects or Tasks ('q' here), this works: serializers.serialize('json', q, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True) But if 'w' is a list of Question objects from another app that have a Task foreign key I get this error: Traceback (most recent call last): File "<input>", line 1, … -
How to check a radio button based on user input in a Django Template?
I'd like to check a specific radio button if one or two of the values of my two input fields exceeds a certain number. I am currently using Django Form to render both the textboxes and the radio buttons: Like this: The Radio Button: 'gap_result': HorizontalRadioSelect( choices=NG_gap, attrs={ 'default': 'OK', 'class': 'radio colorC', 'style': ' margin-top: 15px; margin-left: 25px;', 'name': 'radio_Gap', 'id ': 'radio_Gap_Result', }), The two textboxes: 'gap_X': forms.TextInput( attrs={ 'class': 'form-control cent ', 'placeholder': 'X', 'type': 'text', 'id': 'gap_X', # 'readonly': 'false', }), 'gap_Y': forms.TextInput( attrs={ 'class': 'form-control cent ', 'placeholder': 'Y', 'type': 'text', 'id': 'gap_Y', }), What I need is to change the radio button to be OK if neither of the values exceeds 8 and then NG if it does. Here's a visual representation: Here's what I have in my template using the django forms: <div class="row"> <div class = "col-3"> <div class="form-text"> {{form.gap_X}} </div> </div> <div class = "col-3"> <div class="form-text"> {{form.gap_Y}} </div> </div> {{form.gap_result}} </div> -
How to set a url pattern for year month and date?
I'm trying to create blog project using django I am getting this error. ValidationError at /^(?P2020\d{4})/(?P09\d{2})/(?P06\d{2})/(?Psoftware-industry[-\w]+)/$ ['“06” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
I am studying DRF, and I have a question about specifying ManyToManyField in serializers
While creating a group, I want to add the User received in the request to the members column, the ManyToManyField of the group model. So I created a serializer and modified create to implement the desired functionality, but I'm not sure if this is a good way. I think there is a better way, so I post a question. I hope you can help. User # users.models class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) introduce = models.TextField(max_length=300, blank=True, default=None) attendGroups = models.ManyToManyField( "groups.Group", related_name="groups", blank=True ) # users.serialize class userSimpleInfoSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("id", "nickname") Group # groups.model class Group(TimeStampModel): category = models.CharField(max_length=50) title = models.CharField(max_length=300, blank=True, null=True) discription = models.TextField(blank=True, null=True) leader = models.ForeignKey( "users.User", related_name="leader", on_delete=models.CASCADE ) members = models.ManyToManyField("users.User", related_name="members", blank=True) attends = models.ManyToManyField("users.User", related_name="attends", blank=True) time = models.IntegerField(default=1) def __str__(self): return self.title # groups.serialize class GroupBaseSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) leader = UserBaseSerializer(read_only=True) time = serializers.IntegerField(read_only=True) members = userSimpleInfoSerializer(many=True, read_only=True) attends = userSimpleInfoSerializer(many=True, read_only=True) def __init__(self, leader, *args, **kwargs): super(GroupBaseSerializer, self).__init__(*args, **kwargs) self.leader = leader class Meta: model = Group fields = ("id", "category", "title", "discription", "leader", "time", "members", "attends",) def create(self, validated_data): group = Group.objects.create( category=validated_data["category"], title=validated_data["title"], discription=validated_data["discription"], leader=self.leader, ) group.members.add(self.leader) group.save() … -
Mocking Django inclusion tag in pytest
I have an inclusion tag: from django import template from accounts.models import UserTracking register = template.Library() @register.simple_tag(takes_context=True) def has_shipped(context): return UserTracking.objects.filter(shipping=True, user=context['request'].user).exists() and I am testing a function, awarded, that is calling a template that contains that tag. from unittest.mock import patch from myproject.views import awarded @patch('myproject.templatetags.something.has_shipped') def test_awarded(mymock, rf): mymock.return_value = '' # this is not having any effect result = awarded(rf) assert result and the code under test: def awarded(request): return render(request, 'awarded_form.html', {'revisions' : revisions}) Pytest is yelling at me because it says I'm using the database, which I am (but don't want to), so I want to mock the function containing the database call, has_shipped. How do I do that? When I try to mock the function directly from where it is declared, it doesn't work, because it's apparently not the right scope, so how do I do this? And is this one of those situations where it's just easier to throw @mark_db on it? -
Error displaying list of registered user profiles in Django app using class based views
I created these two class based views to display the profiles of registered users according to their gender, to an authenticated user. here is the code #views.py class FemaleUserList(LoginRequiredMixin, generic.ListView): queryset = Profile.objects.filter(gender='Female').order_by('-age') template_name = 'users/female_user_profiles.html' context_object_name = 'female_users' paginate_by = 6 class MaleUserList(LoginRequiredMixin, generic.ListView): queryset = Profile.objects.filter(gender='Male').order_by('-age') template_name = 'users/male_user_profiles.html' context_object_name = 'male_users' paginate_by = 6 I know there is a better way to this since am basically repeating myself but then it was working fine with a template tag like this #male_user_profiles.html <div class="py-5 text-center"> {% for profile in male_users %} <div class="card" style="width:600px"> <div class="card-img-top"><img class="rounded-circle" src="{{ user.profile.avatar.url }}" alt="{{ user.username }}" width="300px"></div> <hr> <h3>{{ user.username }}</h3> <div class="card-body"> <p class="lead"> <div class="media-body"> <div class="card-text">BIO: {{ user.profile.bio }}</div> <p>Age : {{ user.profile.age }}</p> <hr> <p>Gender : {{ user.profile.gender }}</p> <hr> <p>Interested In : {{ user.profile.interested_in }}</p> <hr> <p>Studying : {{ user.profile.discipline }}</p> <hr> <p>At : {{ user.profile.campus }}</p> <hr> <p>Relationship Status : {{ user.profile.status }}</p> <hr> <p>Enjoys : {{ user.profile.hobbies }}</p> </div> <a class="btn btn-default" href="{% url 'postman:write' %}"><i class="fa fa-envelope"></i>Start Chat with {{ user.username }}</a> </p> </div> </div> {% endfor %} but now all it does is to list the profile of only the logged in … -
DRF APIView "get() returned more than one Article -- it returned 2"
I use DRF to create an API. I have created a view to articles belonging category. But instead I get an error: get() returned more than one Article -- it returned 2! Here is my view how I try to get articles: class CategoryArticlesListView(APIView): queryset = Article.objects.all() def get(self, request,slug=None, format=None): category = get_object_or_404(Category,slug=slug) articles = category.article_categories.get() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) and my traceback: Environment: Request Method: GET Request URL: http://localhost:8000/api/article_categories/yoga/list/ Django Version: 3.0.5 Python Version: 3.8.5 Installed Applications: ['baton', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fluent_comments', 'threadedcomments', 'django_comments', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'rest_auth', 'rest_auth.registration', 'django_rest_passwordreset', 'django_filters', 'crispy_forms', 'sorl.thumbnail', 'photologue', 'sortedm2m', 'ckeditor', 'webpack_loader', 'yogavidya.apps.core', 'yogavidya.apps.actions', 'yogavidya.apps.categories', 'yogavidya.apps.filemanager', 'yogavidya.apps.galleries', 'yogavidya.apps.tags', 'yogavidya.apps.articles', 'yogavidya.apps.books', 'yogavidya.apps.locations', 'yogavidya.apps.pages', 'yogavidya.apps.profiles', 'yogavidya.apps.statusses', 'yogavidya.apps.user_messages', 'yogavidya.apps.videolessons', 'baton.autodiscover'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'yogavidya.lang_middleware.ForceDefaultLanguageMiddleware', 'django.middleware.locale.LocaleMiddleware', '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'] Traceback (most recent call last): File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) … -
Is DRF (Django REST Framework) the equivalent to Express in JavaScript?
I'm a beginner-intermediate web developer, but I have a little more experience with JavaScript libraries, frameworks and Backend/Frontend development than Python/Django stuff. As I understand Django is a very Robust framework but I don't understand very well why to use DRF. Is it as express js? I mean, is it for making CRUD operations? Or is for much more than that? -
Static file is not showing in django
I am just learning django with static files.......Here the issue is my image is not loaded in browser its shows just like a icon here is snapshot of output and codes that I am using enter image description hereplz see my images MY codes.. Setitngs.py TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS=[STATIC_DIR,] Blockquote c2.html <!DOCTYPE html> {% load static %} <html <head> </head> <body> <H1> {{ title|upper }} <br> HEllo {{ cname }}</H1> <img src="{% static 'image/i1.png' %}" /> </body> </html> image description : this is what i get instead of full image image when hit url -
403 Forbidden Error when trying to post and put a axios request in a web app using Django and React
I am working on a web application with a backend in Django and a frontend in React. Currently I am able to create articles through my superuser account and list them on the frontend. I am now trying to create and update but I keep getting the following error: xhr.js:184 POST http://127.0.0.1:8000/api/ 403 (Forbidden) Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:69) In my research I believe that the error message deals with csrftoken. I have tried adding the following statements in my axios.post request: xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' And I have tried adding the following statements in my settings.py file: CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] INSTALLED_APPS = [ ... 'corsheaders', ... ] But I still have had zero success. Any help would be much appreciated! Thank you much in advance. import { Form, Input, Button } from 'antd'; import axios from 'axios'; axios.defaults.xsrfHeaderName = "X-CSRFToken" axios.defaults.xsrfCookieName = 'csrftoken' window.axios = require('axios'); /* window.axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('title') }; */ class CustomForm extends React.Component { onFinish = (values, requestType, articleID) => { console.log("Success:", values); const title = (values.title); const content = (values.content); console.log(this.props.requestType); const headers … -
(Django) It's possible to use a generic 'admin/' such as sb-admin bootstrap instead of the original one?
fellows. To answer this question properly you have to have good knowledge on Django Frameworks. I'm about to start this blog using Django, nothing serious, just playing around. All I want to know is if Django path('admin/', admin.site.urls) could be replaced by a generic admin page, such as this one. -
Django user.is_authenticated returns different results in different views
I have an API view (using DJ Rest Framework) that I am posting to via React in my frontend. request.user.is_authenticated returns True here (and returns the user I have attempted to sign-in as), however, in my view for rendering the login page template, request.user.is_authenticated returns False, and the user object is an AnonymousUser. Why is this? I've checked this question, but it only has information on templates. Here's the API view code: @api_view(['POST']) def login_api_view(request, *args, **kwargs): if request.user and request.user.is_authenticated: return Response({'message': 'User is already authenticated'}, status=400) username = request.data.get('username') password = request.data.get('password') if username is None or password is None: return Response({'message': 'Please specify a username and password'}, status=400) user = authenticate(request, username=username, password=password) if user is None: return Response({'message': 'Invalid credentials'}, status=401) login(request, user) return Response({'message': 'Successfully authenticated user'}, status=200) And here's the code for the template: def login_view(request, *args, **kwars): if request.user.is_authenticated: return redirect('/') return render(request, 'users/login.html') -
redirect author to his post after creating it and submitting its form with django
i want to redirect the user to the post after creating it with django forms in models.py class Text(models.Model): title = models.CharField(max_length=200, null=True) document = models.TextField(max_length=None, null=True) requirements = models.TextField(max_length=200, null=True) date_created = models.DateField(auto_now_add=True, null=True) deadline = models.DateField(null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.title in my view.py def text(request, pk): form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): text = form.save() text = Text.objects.get(id=pk) return redirect('text') text = Text.objects.get(id=pk) context = {'form': form, 'text': text} return render(request, 'main/text.html', context) in my forms.py class TextForm(ModelForm): class Meta: model = Text fields = ['title','document','requirements','deadline'] widgets = { 'title' : forms.TextInput(attrs={'placeholder':'Title','class':'form-control m-2 mb-4 pb-2'}), 'deadline' : forms.DateInput(attrs={'placeholder':'Deadline','type':'date','class':'form-control m-2 pt-2', 'id':'opendate'}), 'requirements' : forms.Textarea(attrs={'placeholder':ps_note,'class':'form-control col m-2','rows':'3'}), 'document' : forms.Textarea(attrs={'placeholder':ps_text,'class':'form-control'}), } in my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('text/<str:pk>', views.text, name="text"), path('signin/', views.signin, name="signin"), path('signup/', views.signup, name="signup"), path('logout/', views.logout, name="logout"), ] i had to add this so stackoverflow accepts my question because it said that it's mostly code even after saying all the details. -
how to get selected value detail from dropdown rest framework Django?
i am getting a dropdown menu of books from ManyToMany relation. i want to show the price of selected book from dropdown menu. how to make that type of query in backend if i select any book from dropdown menu then the price and created_on is show on frontend...? models.py class Book(models.Model): name = models.CharField(max_length=20) price = models.IntegerField(null=True) created_on = models.DateTimeField(auto_now_add=True) class Keeper(models.Model): saler_name = models.ForeignKey(User, on_delete=models.CASCADE) books = models.ManyToManyField(Book) serializer.py class BookSerialzer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' class KeeperSerializer(serializers.ModelSerializer): class Meta: model = Keeper fields = ['id', 'saler_name', 'books'] views.py class KeeperCreateApi(CreateAPIView): queryset = Keeper.objects.all() serializer_class = KeeperSerializer def perform_create(self, serializer): serializer.save(saler_name=self.request.user) -
Is channels required to use socket with django? Is there any other alternative or way?
I am using the django framework. I'll do the messaging part. I will do this with the socket. However, I always come across a channel library. Is there no other solution? -
Two lists. How to print members of one and not the other? Django tags
I have a situation where users adds products to Observed and then they can Purchase them. I want to print products that has been added to Observed but not Purchased. Products of name 1 2 3 4 were added to Observed but only 3 4 were Purchased. I want to print 1 2 only. I have little understanding of Django Tags but I aim to solve it, this is my company specific code so please share your thoughts and I might be able to make it work. Here is the code I tried, one of the dozens approaches: {% product_events event_type='add to observation' for_last_days=1 count=5 unique=1 order=-1 in_stock='true' as observe_list %} {% product_events event_type='purchase' for_last_days=1 count=5 unique=1 order=-1 in_stock='true' as purchase_list %} {% for event in observe_list %} {% if event.name not in purchase_list %} {{ event.name }} {% endif %} {% endfor %}