Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to show output text from db just in one line in django templates
In my Django project, I want to read some text from my PostgreSQL DB and show them just like emails that are shown in the inbox. i.e, each output shouldn't have any line-breaks(enters) or other tags. I've wrote something like this so far: <div> <p style="font-size: 15px;">{{ contact.message |safe|truncatewords:15|cut:"\n" }}</p> </div> I also tested |striptags tag instead of |cut:"\n". It removes line breaks, but some other problems come with it since I'm using CKEditor richtextfield and the text has some markups. how to show just 1 line of text ( up to a few words, 15 for example) without any linebreaks and HTML tags? any help is appreciated. -
Why does Django not find the slug?
An error is output when trying to move to a category: If there is not enough data to answer, write down what you need to add to the question. Thank you in advance NoReverseMatch at /1928/december_rush/ Reverse for 'category_list' with keyword '{'card': , 'category': 'backend'}' not found. 1 pattern(s) tried: ['1928/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/$'] class Card(models.Model): """ Карточка для выбора блога о сайте """ STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField('Заголовок', max_length=100) text = models.TextField('Текст') slug = models.SlugField('Url', max_length=150) status = models.CharField('Стаутс публикации', choices=STATUS_CHOICES, default='draft', max_length=15) published = PublishedManager() objects = models.Manager() def get_absolute_url(self): return reverse('blog:post_list', kwargs={'card':self.slug}) def __str__(self): return self.title class Meta: db_table = 'Cards' verbose_name = 'Карточка' verbose_name_plural = 'Карточки' class Category(models.Model): """ Категории постов """ STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField('Заголовок', max_length=100) slug = models.SlugField('url') status = models.CharField(', choices=STATUS_CHOICES,default='draft', max_length=15) published = PublishedManager() objects = models.Manager() def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:category_list', kwargs={'card':Card.slug, 'category':self.slug}) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' class Post(models.Model): """ Страница поста """ STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField('Заголовок', max_length=150) slug = models.SlugField('Url', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, related_name='blog_posts', verbose_name='Автор') text = models.TextField('Текст') created = models.DateTimeField('Дата создания', auto_now=True) … -
How to use context object to make query in Class based View?
I am trying to understand class based views and having difficulty to with variables. class TeacherView(generic.DetailView): model = Teacher context_object_name = 'the_object' template_name = urls['Teacher_detail'] # I declared an array and called urls to store template paths I want to use the Teacher variable that I am going to use in the template to make queries. Example: Homeworks.objects.filter(Teacher = Teacher_of_this_view) and pass also this Homeworks array to my template and use. Can someone atleast please tell me what to check exactly ? I got lost with functions like get_object(), get_context_object() etc. Thanks in advance -
How Django Default Model Form Validation Works?
I have create a model with email and username where email is my (pk). Both have arguements 'unique=True' in model fields. Then i have created form. My form when validates the data it always checks the uniqueness of the username but not the uniqueness of the email field. I don't know why? Since, i have mentioned unique=True why its not checking for the email data uniqueness. I have overided the clean_email() method in user registration to fix this issue but not in profile update form. I can fix this using same method but want to know why this is happening. I am still learning django a beautifull framework of python. Please help me understand this issue. models.py class MyAccountManager(BaseUserManager): def create_user(self,email,username,password=None): if not email: raise ValueError("Users Must Have email Address") if not username: raise ValueError("Users Must Have username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user( email = self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # //////////////////////////////////////////////////////////// def get_profile_image_filepath(self,filename): return f'profile_images/{self.pk}/{filename}' #pk= primary key def get_default_profile_image(): return "img/default_profile/default.png" class KeepSafeUserModel(AbstractBaseUser): first_name = models.CharField(verbose_name='first_name',max_length=30,default="") last_name = models.CharField(verbose_name='last_name',max_length=30,default="") email= models.TextField(verbose_name='email',max_length=60,unique=True,primary_key=True) username = models.CharField(max_length=30,unique=True) date_joined = models.DateTimeField(verbose_name="date … -
How to set Django queryset to GKE memcached
Somehow I thought, pymemcached should work out of the box like django cache. But what I am realizing is it doesn't. Going through the docs, there are methods like set_multi, get_multi. This should work well with django dictionaries(key/value pairs). Given that Django querysets are not tranditionally dictionaries, what would be the method to use with pymemcached. Here is how am using it for the moment: if not settings.DEBUG: from pymemcache.client.base import Client NODE_NAME = os.environ['NODE_NAME'] client = Client((NODE_NAME, 5000)) class ProductsListCacheAPIView(ListAPIView): model = Product serializer_class = TestProductSerializer filter_backends= [SearchFilter, OrderingFilter] permission_classes = [AllowAny] search_fields = ['product_title', 'product_description', 'user__first_name', 'product_type', 'product_price', 'product_city'] pagination_class = ProductPageNumberPagination def get_queryset(self, *args, **kwargs): query = self.request.GET.get("search") lookups = () ..... queryset_list = queryset_list.filter(lookups).distinct() cache_key = 'my_api_marketplace_cache' data = client.get(cache_key) if data is None: print('Getting marketplace fresh from database!') data = queryset_list client.set(cache_key, queryset_list, cache_time) return data This doesn't work ofcourse. Seems unlike django cache from django.core.cache import cache (django.core.cache.backends.memcached.PyLibMCCache) The set method seems to work only with strings for pymemcached. How can I use pymemcached here to cache django querysets? -
How can i list Parent categories only with django-mptt?
I want to list only the parent Categories in one page and the other sub-categories in another page. models.py class Category(MPTTModel): name=models.CharField(max_length=50) slug=models.SlugField(max_length=50, unique=True, help_text='Uniue Value product page url, created from name.') is_active=models.BooleanField(default=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) parent=TreeForeignKey('self',on_delete=models.CASCADE,null=True,blank=True, related_name='children') class MPTTMeta: order_insertion_by=['name'] views.py def index(request): listing=Category.objects.all() context={ 'listing':listing } return render(request,'catalog/index.html',context) -
Why is fetch API translating IP address into localhost:8000?
I am trying to make an api and front end app in the same django project. The front end app uses React which makes a call using fetch to the django api app using the url: http://server_ip/api/v0/codex. When I check in the browser it looks like this is getting translated (somehow) into http://localhost:8000/api/v0/codex. This causes an error because (from what I understand) the browser is looking for the file on the local machine (my personal computer) not the remote server. This is verified by the fact that if I run the django dev server on my personal computer the request goes through. I am using nginx and gunicorn for servers (on remote cloud server used for deployment). gunicorn is running on localhost:8000. gninx does a proxy_pass to http://localhost:8000. What is going on? How does the fetch API work with localhost? What can I do to get around this issue? -
Django with filtered join
I have an inner join: SELECT c.name, b.name FROM company c INNER JOIN branch b ON b.company_id = c.id WHERE c.id = 5 AND b.employees > 10; That I got 3 registers. How do I make this query in Django to returns only 3 registers? c = Company.objects.prefetch_related("comp_branches").filter(id=5, comp_branches__employees__gt=10) c[0].comp_branches.all() # returns 5 registers -
Test view queryset in django
I am trying to validate my views in Django and I have a problem. How to check queryset filter in test. This is my view class UpcomingEvents(generics.ListAPIView): queryset = Event.objects.filter(enabled=True, start_date__gt=datetime.datetime.now()).order_by('start_date') serializer_class = EventSerializer pagination_class = Paginator How can I check if enable is true or start date> now in test without creating objects? -
Understanding definition of Django's model class
If we create a new model as follows, from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) and run the database migrations, then I understand that the corresponding table is created with column names and field types, and I understand that we can do the following: >>> from myapp.models import Book >>> book = Book(title="Matilda", author="Roald Dahl") >>> book.save() >>> print book.title Matilda However I am struggling a little to understand the python code in the class definition, just in terms of how I understood classes to work, and was hoping someone could help my understanding with the following questions: In the definition of the class Book, title seems to be a class attribute. This class attribute is set to an instance of the CharField class? In which case when we create an instance of the Book class, if we do not pass in an argument, would title be set to this same instance of CharField? When we pass in title='Matilda' on creating this instance of Book, is this then overriding the attribute title? How do we know that Book takes in title as an argument? I hope these make sense. Thank you for any help. Lizzie -
Getting No Response While using js function in html
I'm working on a practice project trying to create Social media clone using python and javascript everything is going well but just stuck on an error so here's my code first html <form onsubmit="createComment('{{p.id}}')" > <input id="comment_text{{p.id}}" type="text" placeholder="Write an Answer"> <input type="submit"> </form> js function createComment(f){ alert('c') fetch('/comment', { method : 'POST', body : JSON.stringify({ post_id : f, comment_text : document.querySelector(`#comment_text${f}`).value }) }) .then(response => response.json()) .then(data => { alert('succes') }) } django models class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="commenter") text = models.TextField(max_length=250) time_comment = models.DateTimeField(auto_now_add=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_post") likes = models.ManyToManyField(User, related_name="likes") timestamp = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=1000) img = models.ImageField(upload_to="post", blank=True, null=True) comment = models.ManyToManyField(Comments,related_name="post_comments") url & view @csrf_exempt def new_comment(request): data = json.loads(request.body) print(data) post = Post.objects.get(id=data['post_id']) comment = Comments( user= request.user, text=data['comment']) comment.save() post.comment.add(comment.id) return JsonResponse({'message' : 'Succes'}, status=201) URL path("comment", views.new_comment, name="comment") I have some other function to create new post and edit which work similar and they are working well and I have checked my django views and url are fine I can do it without fetch method -
How can i use Django-mptt?
I want to make a navigation through categories and subcategories in Django. I install django-mptt and now i get this error."type object 'Category' has no attribute '_mptt_meta' " models.py from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Category(models.Model): name=models.CharField(max_length=50) slug=models.SlugField(max_length=50, unique=True, help_text='Uniue Value product page url, created from name.') is_active=models.BooleanField(default=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) parent=TreeForeignKey('self',on_delete=models.CASCADE,null=True,blank=True, related_name='children') class MPTTMeta: order_insertion_by=['name'] thanks beforehand. -
Filter from 2 different tables using Django rest Framework
Good day, I am trying to filter data from 2 different tables which have a one to many relationships. I have products table and specification table. 1 product is related to many specification list. I dont have any problems getting all the information of the product including the specifications. I am also successful in filtering the products table, like filter by category and manufacturer. but I want to filter also based on the specifications while filtering the category/manufacturer. here is my models. class Products(models.Model): product_partnumber = models.CharField(max_length=255) image_link = models.URLField(default=None, blank=True, null=True) pdf_link = models.URLField() manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Products' class ProductSpecification(models.Model): product = models.ForeignKey(Products, related_name='specifications', on_delete=models.CASCADE) specification = models.ForeignKey(Specification, related_name='specification_name', on_delete=models.CASCADE) value = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) and this is my codes for api and filtering. As of now I am only successful on filtering on one table. I have no idea how I can also add the ProductSpecification model on my filter class. class NumberInFilter(filters.BaseInFilter, filters.NumberFilter): pass class ProductFilter(filters.FilterSet): manufacturer__in = NumberInFilter(field_name='manufacturer', lookup_expr='in') class Meta: model = Products fields = ['category', 'product_partnumber'] class ProductsView(viewsets.ModelViewSet): queryset = Products.objects.all() serializer_class = ProductsSerializers filter_backends = [filters.DjangoFilterBackend] … -
Make a Django model class whose one of the field value is calculated by other model's fields values and it must be present in my actual Database table
models.py from django.db import models class model_A(models.Model): value_1 = models.IntegerField() value_2 = models.FloatField() class model_B(modles.Model): value_3 = models.FloatField() @property def value_4(self): return (model_A.value_1 - model_B.value_2) admin.py from django.contrib import admin # Register your models here. from .models import model_A, model_B model_lst = [model_A, model_B] for i in model_lst: admin.site.register(i) I want model_B to have value_4 as separate column in database table(model_B) -
'zip' object has no attribute 'model' using django
I want to obtain the code and the description of the code on my search bar using Django. I am getting an error as "'zip' object has no attribute 'model'" How may I resolve this or is there another way of defining it. My codes are: views.py def display_majorheads(request): outputs = ProcessedOutputs.objects.all() year = outputs.first().finyear.finyear be_year = int(year.split('_')[1]) p_majors = ProcessedOutputs.objects.only('major_cd') majors = Major.objects.only('description').filter(major_cd__in=p_majors.values_list('major_cd', flat=True)).distinct().order_by("pk") processed_outputs = zip(majors,outputs) myFilter = ProcessedOutputsFilter(request.GET, queryset=processed_outputs) processed_outputs = myFilter.qs context = { 'processed_outputs':processed_outputs, 'be_year':be_year, 'myFilter':myFilter, } return render(request, 'website/mhead.html', context ) filters.py class ProcessedOutputsFilter(django_filters.FilterSet): class Meta: model = ProcessedOutputs fields = '__all__' exclude = ['finyear', 'ag_salary'] mhead.html <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </button> </form> models.py class ProcessedOutputs(models.Model): major_cd = models.OneToOneField(Major, models.DO_NOTHING, db_column='major_cd', primary_key=True) finyear = models.ForeignKey(Finyear, models.DO_NOTHING, db_column='finyear') ag_salary = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'processed_outputs' unique_together = (('major_cd', 'finyear'),) -
Add steps to a model entry in Django
I am currently learning Django and was asking myself how I could add substeps to an entry. Lets take a recipe-app for example: A recipe consists of one ore many steps. The user wants to enter a recipe and gets provided with three form fields: Recipe name, ingredients and the option to add many steps. So how can I implement the functionality to add a ingredient list of unknown length and to add a unknown number of steps? I only know how to give the functionality of single form entries. Thanks for your hard work here. -
I want to write my product name like this - my_productnam....more... | in django
{{i.Title |slice:"0:30"}}... If Name of item crosses the limit of max characters then "More..." button should be automatically placed at 31st character. -
Django Request is missing required authentication credential, 'status' :UNAUTHENTICATED
I'm trying to social login with google, user_info = requests.get( f"https://www.googleapis.com/userinfo/v2/me", headers={"Authorization": f"Bearer {access_token}"}, ) print(info.json()) {'error': {'code': 401, 'message': 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.', 'status': 'UNAUTHENTICATED'}} using Django i wanna take user infomation and save my database and login how can i do? -
How to know action (HTTP method) type in DRF generic views?
When using ViewSets you can do self.action and get to know whether you are currently handling a GET or POST and such. How do you do the same with generic views like ListCreateAPIView? I want to return a different serializer context in get_serializer_context depending on the current HTTP method being called. How do I go about this? -
Pass a selection form to view in Django
I am making a feedback form with selection. But I got the error MultiValueDictKeyError when submitting the form. I tried changing the code in the views.py, it becomes hb_content=request.POST.get('hb_content', False). But when I checked the data, it only saves a False value. Could you help me please? Thank you in advance. models.py: CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ) class Feedback(models.Model): class Meta: db_table = 'feedback' get_latest_by = 'created' # healthbook hb_content = models.CharField(max_length=6, choices=CHOICES, default='None') forms.py: CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ) class FeedbackForm(forms.ModelForm): hb_content = forms.ChoiceField(choices=CHOICES, label="", initial='', widget=forms.Select(), required=True) views.py: def feedback(request): if request.method == 'POST': feedback_form = Feedback(hb_content=request.POST['hb_content']) feedback_form.save() return render(request, '../templates/home/feedback.html', {}) feedback.html <div class="main"> <h1>Feedback</h1> <form id="contact_form" action="{% url 'feedback' %}" method="POST"> {% csrf_token %} <div class="form-group"> <h2>HealthBook</h2> <label for="hb_content">1. あなたにとって有益な情報が得られると思いましたか。5段階で評価してください。 とてもそう思う⇔全くそう思わない</label> <select name="hb_content"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </form> -
Djoser login with token doesn't require x-csrf token,
I'm new to Django/Django Rest Framework and trying to create a login page using the djoser package. This is my sample code, im using vue.js: login(){ const auth_user = {}; axios.post('auth/token/login/', { username: this.username, password: this.password, }) .then((response) => { if (response.status == 200) { auth_user.auth_token = response.data.auth_token; window.localStorage.setItem('auth_user', JSON.stringify(auth_user)); location.replace(window.location.origin + '/dashboard'); } }) .catch((error) => { }); }, I've Created a Login form that directly post to '/token/login' url, and generate an auth token. Questions: Is this the right thing to do if your creating a login page?? I'm just curious why the URL '/token/login' doesn't require X-CSRF Token?? Thank you -
django foreign key selecting in html form
how to add ForeignKey selecting to html form omniva=models.ForeignKey(Omniva,on_delete=models.SET_NULL,blank=True,null=True,related_name='orders') how i can add this Foreign key selecting to html form -
How to use 2 models in 1 view django?
So I have a model class Question(models.Model): question = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.question def check_answer(self, choice): return self.choice_set.filter(id=choice.id, is_answer=True).exists() def get_answers(self): return self.choice_set.filter(is_answer=True) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) and another model class Choice(models.Model): question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) is_answer = models.BooleanField(default=False) def __str__(self): return self.choice_text def get_absolute_url(self): return reverse('article_list') How can I display both of these in the same view OR is there a better way of doing this -
Length filter on django template doesnt seem to work
I am trying to use raw query instead of the ORM. However I am having trouble when i try to count all instances from MyTable. Below is the code from my view : problems_raw_count = MyModel.objects.raw('SELECT * FROM MyApp_MyTable') problems_count = list(problems_raw_count) And now the variable I am trying to implement on template side : {{ problems_count|length }} I know I could simply use MyModel.objects.all() but it does interest me to know why it is not actually working. Many thanks. Romain -
How can I join two model tables using username as primarykey?
class Cust_detail(models.Model): Firstname = models.CharField(max_length=30) Lastname = models.CharField(max_length=30) signup_Username = models.EmailField(max_length=40) signup_Password = models.CharField(max_length=15) On my signup page, I have a row names "Username" which is unique for every customer. I would like to connect the two tables together using Username as the primary key class Cust_addres(models.Model): Phone_no = models.CharField(max_length=10) house_no = models.CharField(max_length=50) username=models.ForeignKey(Cust_detail,related_name='Users', on_delete=models.CASCADE,null=True, blank=True)