Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inlineformset_factory: validation failed (this field is required)
I have inlineformset_factory form with 3 fields. But when I update form, a new blank line is created. And if I decide to leave this line empty, validation failed because field required So issue come from "extra" parameters in inlineformset_factory MenuFormset. I thought about using a specific inlineformset_factory UpdateMenuFormset with extra=0 for Update view but it is probably not a good way doing this How can I manage this validation? models.py class Orders(SafeDeleteModel): """ A class to create a new order instance in the Schitt's Creek Cafe Tropical. """ _safedelete_policy = SOFT_DELETE_CASCADE order_id = models.AutoField("Order id", primary_key = True) table = models.ForeignKey(Tables, on_delete = models.CASCADE) # related table customers = models.IntegerField("Number of customer", null=True, blank=True) split_bill = models.IntegerField("Split bill", null=True, blank=True) delivered = models.BooleanField("Delivered", null=True, blank=True, default=False) paid = models.BooleanField("Available", null=True, blank=True, default=False) created_at = models.DateTimeField("Date created", auto_now_add = True) log = HistoricalRecords() class Orders_Menus(SafeDeleteModel): """ A class to create a new Orders_Menus instance in the Schitt's Creek Cafe Tropical. """ _safedelete_policy = SOFT_DELETE_CASCADE order = models.ForeignKey("Orders", on_delete = models.CASCADE) menu = models.ForeignKey("Menus", on_delete = models.CASCADE) cooking = models.IntegerField("Cooking", default=0, null=True, blank=True) tone = models.IntegerField("Tone", default=0, null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'Orders_Menus' forms.py MenuFormset = inlineformset_factory( … -
Failed lookup for key [category] in [{'True': True, 'False': False, 'None': None}, {}, {},
I'm getting this error Failed lookup for key [category] in [{'True': True, 'False': False, 'None': None}, {}, {}, .... in my application i have category and subcategory which repeated too much in my view for every function and for child or subcategory i used pip install django-mptt but it was Ok and worked will. so i decided to use custom template tags instead but right now I'm facing with this error for more info you can take a look to my code. myapptags.py from django import template from django.db.models import Sum from django.urls import reverse from mysite import settings from order.models import ShopCard from product.models import Category register = template.Library() @register.simple_tag def categorylist(): return Category.objects.all() code for views.py import json from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.urls import reverse from django.shortcuts import render, redirect from django.contrib import messages from django.template.loader import render_to_string from . models import Settings, ContactMessage, FAQ from product.models import Category, Comment, Images, Product, Variants from . forms import ContactForm, SearchForm from product.forms import CommentForm def index(request): setting = Settings.objects.get(pk=1) # category = Category.objects.all() products_slider = Product.objects.all().order_by('id')[:4] #first 4 product products_latest = Product.objects.all().order_by('-id')[:4] # latest products_picked = Product.objects.all().order_by('?')[:4] # random page = "index" context = { 'setting': … -
NoReverseMatch at /job_category/IT/
Reverse for 'job_category' with keyword arguments '{'id': <Category: Government>}' not found. 1 pattern(s) tried: ['job_category/(?P<category_slug>[^/]+)/$'] {% extends 'base1.html' %} {% block content %} <div class="left col-sm-4" style="float:left; width: 360px;"> <h6 class="p-2" style="background:#A9CCE3; color:#2F4F4F;">JOB CATEGORIES</h6> <ul class="list-group"> {% for x in categories %} <li class="list-group-item c1 list-group-item-action" style="color: rgb(2,96,170);"> <a href="{{ x.get_absolute_path }}"></a> <div class="p-2"> <h7 class="card-title"> {{x.name}} </h7> </div> <div class="overlay1"></div> </li> {% endfor %} </ul> </div> <div class="right col-sm-8" style="float: right; width:825px;"> <!--{% if category %}{{category.name}}{% endif %} !--> <div class="row container-fluid"> {% for i in jobs %} <div class="col-sm-3 mt-3"> <div class="card c1"> <div class="overlay1"></div> <div class="card-body"> <h5 class="card-title" style="color: rgb(2,96,170);"> {{job.post}}</h5> <h6 class="card-text" style="color: rgb(85, 85, 85);"> {{job.job_id.comp_name}}</h6> <p><i class="fas fa-map-marker-alt mr-1"></i>{{job.address}}<i class="far fa-calendar-alt ml-3 mr-1"></i>{{job.todate|date:'d M, Y'}}</p> <a href="{% url 'job_detail' job.job_id.id %}" class="btn btn-primary btn-sm right" style="position:relative; float:right;">View more</a> </div> </div> </div> {% endfor %} </div> </div> {% endblock content %} views.py def job_category(request, category_slug=None): category = None job_requirements = [] categories = Category.objects.all() jobs = Job.objects.all() if category_slug: category = Category.objects.get(slug=category_slug) print(category.slug) jobs = Job.objects.filter(job_category=category.slug) for job in jobs: job_requirements.append(JobRequirements.objects.get(job_id=job)) return render(request, 'JobCategory/category.html', {'categories': categories, 'jobs': job_requirements}) urls.py path('job_category/<str:category_slug>/', views.job_category, name='job_category'), Models.py class Category(models.Model): name = models.CharField(max_length=40, blank=True, null=True) slug = models.CharField(max_length=4, unique=True) def … -
Specify size of images in django
I am currently working on a django blog. However, I am experiencing some difficulties with the size of the post thumbnails. Here's a picture: What I marked in yellow is how the image should be filling the space. The width is fine, but the heigh isn't working well as you can see. Here's the code: {% extends 'base.html' %} {% load static %} {% block content %} <style> img { height: 100%; width: 100%; } </style> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> <a href="{{ obj.get_absolute_url }}"> <h2 class="h4">{{ obj.title }}</h2> </a> </header> <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p> <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap"> <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div> <div class="title"><span>{{ obj.author }}</span></div></a> <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div> <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div> </footer> </div> </div> </div> {% if forloop.first or forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the … -
Disallowed host in django
I am trying to deploy django app using apache2 and mod_wsgi. Below is the error it is throwing: DisallowedHost at / Invalid HTTP_HOST header: '10.1.1.1:9090'. You may need to add '10.1.1.1' to ALLOWED_HOSTS. My settings.py has ALLOWED_HOSTS = [] Why I am getting disallowed host? -
how to update plotly graph using ajax in django
I want to update my plotly graph using ajax in my Django project. This is what I tried so far. I'm following this guide to doing it and I'm totally new in jquery and ajax. urls.py urlpatterns = [ path('', views.index, name='index'), path('get/ajax/updategraph', views.updategraph, name = "updategraph") ] In views.py I defined a updategraph function(view) to do the job for GET request. def updategraph(request): # preparing my data data = pd.read_excel("/Sensorik.xlsx") columns = [] df_new = pd.DataFrame() df_georgian = pd.DataFrame() # selecting needed columns for item in data.columns: if not ("Unnamed" in item): columns.append(item) for item in columns: df_new.loc[:, item] = sensor.loc[:, item] df_new = df_new.drop(df_new.index[[0, 1]]) ind = df_new.index.size df_new.index = range(ind) df_georgian = df_new.set_index('Timestamp') # request should be ajax and method should be GET. if request.is_ajax and request.method == "GET": # get the data from the client side. coding = request.GET.get('coding') # check for the data in the database. if coding: trace2 = go.Scatter(x=df_georgian.index, y=df_georgian.loc[:, df_georgian.columns[2]], mode='lines') fig_new = go.Figure(data=[trace2]) plot_div_new = plot(fig_new, config=config, output_type='div') ser_instance = serializers.serialize('json', [ plot_div_new, ]) # send to client side. return JsonResponse({"instance": ser_instance}, status=200) else: # if data not found, then graph wont change return JsonResponse({}, status = 200) return JsonResponse({}, status … -
python (django) - conditional list comprehension db query
I have a table of selling offers for a book where one user may offer more copies (only one active, meaning not sold per user) and I would like to return true if at least one offer is set to is_sold = False. Can this be achieved with list comprehension? I am not really sure if this actually checks each book.is_sold and returns True when it finds False, but I'm not really getting result I'm looking for. return render(request, 'books/book.html', { 'book': book, 'is_offered': [True if not book.is_sold else False for book in BookSellers.objects.filter(book=book)], }) -
How can i receive JSON data from Django backend to Angular frontend
i have an application with Django on backend and i am using Angular 11 on my front. How could i receive data from db (sending JSON from back? or any other ways) and use it on my templates in Angular? I would be grateful if you provide any nice articles or guides with code examples. -
I want to run my Django project from a local branch. Is there a way to do this?
I'm working on a project and I want to test a feature locally for which I created a local git branch. I want python manage.py runserver to run changes made in the feature branch but it still runs from the master branch. It would be great if someone can explain why it does this as well. -
modelformset_factory duplicate queries issue
I want to know if there's a way to cache queryset when rendering each form of formset, like similar way as select_related. My formset made by modelformset_factory causes db hits for every form generated. If I have 100 instances, queries are dupliacated 100 times plus. I used select_related when I made queryset as an argument to formset, but it doesn't seem to cache it. views.py .... queryset=Allocate.objects.select_related('license').filter( date=date, license__number__range=(2101, 2105) ) # formset 설정 AllocateFormSet = modelformset_factory( Allocate, form=AllocateModelForm, extra=0 ) if request.method == 'GET': formset = AllocateFormSet(queryset=queryset) .... models.py class Allocate(models.Model): license = models.ForeignKey( 'license.License', verbose_name='차번', on_delete=models.CASCADE, ) morning_driver = models.ForeignKey( 'employee.Employee', verbose_name='오전기사', on_delete=models.CASCADE, related_name='morning_drivers', blank=True, null=True ) afternoon_driver = models.ForeignKey( 'employee.Employee', verbose_name='오후기사', on_delete=models.CASCADE, related_name='afternoon_drivers', blank=True, null=True ) forms.py class AllocateModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix='' for key in self.fields.keys(): self.fields[key].required = False self.fields['license'].disabled = True license_qs = License.objects.filter(id=self.instance.license_id) self.fields['license'].queryset = license_qs self.fields['morning_driver'].queryset = Employee.objects.none() self.fields['afternoon_driver'].queryset = Employee.objects.none() When I see SQL section from django-debug-toolbar, it says I have quite many duplicate queries. For every form it adds up 3 queries even when I set queryset of both morning_drvier and afternoon_driver none. Imagine how much pain I would have if I include actual queryset for the two … -
Django redirect link
I am working on a Django project and want to redirect the user to the download page when the user click on the button. I have tested the attribute store in book.download_url tested view enter image description here HTML file enter image description here -
NameError: name 'o' is not defined Error in django app
hi i'm soo new in django ,i'm try to learning this and i'm sorry i'm not so good in English I have a problem with my django app,I remove my products app for more practicing and when i use 'migrate' or 'makemigrations' code ,i get an error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return … -
Django python regex to include dollar symbol in URL
I have a Django 1.5 app wherein a particular URL is used to generate code 128 barcodes. I have a regular expression written for this URL which is as follows ... url(r'^code/(?P<barcode>[.a-zA-Z0-9_-]+)/$', CreateBarcode.as_view(), name='create_barcode'), ... This works fine for generating barcodes for values such as www.xyz.com/code/123ABC456/ www.xyz.com/code/AAA-BBBB-CCC/ www.xyz.com/code/A_B_C/ I recently had a problem where I had to generate a barcode for a value which contains a dollar symbol $ in it. I have tried out the below regular expressions but to no success url(r'^code/(?P<code>[$.a-zA-Z0-9_-]+)/$', ....), url(r'^code/(?P<code>[\$.a-zA-Z0-9_-]+)/$', ....), url(r'^code/(?P<code>[.a-zA-Z0-9_-][$]+)/$', ....), url(r'^code/(?P<code>[.a-zA-Z0-9_-\$]+)/$', ....), All of these return a 404 response since the URL patterns could not be matched. Let me know if there is any way of getting this implemented? -
Establishing M2M relationship with auth_user model
I am making a webapp based on django and kinda new to it , learning from the documentation. I am leveraging the default User model by django to create the customer database and authenticate them . Now I want to relate a field of a custom model e.g. iname with an M2M relationship to User . Usually I can create an M2M field and foreign key among two custom models , but here one of them is defined by default , so not sure how to use its fiels. Looking for a suggestion here. class sale_info(models.Model): icategory = [('chair', 'Chair'), ('table', 'Table'), ('book', 'Book'),('overcoat', 'Overcoat')] iname = models.CharField(max_length=20, choices=icategory) idesc = models.TextField(max_length=300, null=True) def __str__(self): return self.iname, self.icategory -
cart.js:6 Uncaught SyntaxError: missing ) after argument list
please answer this question i'm working on ecommerce website following the youtube chhanel name Dennis lvy https://www.youtube.com/channel/UCTZRcDjjkVajGL6wd76UnGg and i got this error in my js file var updateBtns = document.getElementByClassName('update-cart') for(var i=0;i<updateBtns.length; i++){ updateBtns[i].addEventListener('click', funcation(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', product, 'action:',action) }) } error in line 6 updateBtns[i].addEventListener('click', funcation(){ like cart.js:6 Uncaught SyntaxError: missing ) after argument list can anyone tell me how can i solve it? <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> -
How to connect Django and .net core project as a single application?
I want to connect Django project and .NET core project because I want it tack advantage of good library available in python so I will make one strong .NET core project.so through some lite on it. -
Hiding some of the fields in django forms
I am using modelformse_factory, where I can set extra value, which corresponds to the number of file inputs, that are in my form. ImageFormSet = modelformset_factory(PostImage,form=ImageForm, extra=3) Can I somehow limit the fields to some number, lets say 1 and then show 2 other by clicking some button? So basically the form renders all 3 fields, but two of them are hidden until I press a button? -
'RegisterAPI' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am trying to display a register_view here and I'm getting the error. I have made some changes to the views fil,e but i am still getting the errors and i don't know how to fix it. Here is my views.py file: from django.shortcuts import render from rest_framework.response import Response from rest_framework import generics, permissions from knox.models import AuthToken from .serializer import RegistrationSerializer class RegisterAPI(generics.GenericAPIView): user_serializer_class = RegistrationSerializer def post(self, request, *args, **kwargs): user_serializer = self.get_serializer(data=request.data) data = {} if user_serializer.is_valid(): user = user_serializer.save() return Response({ "user": RegistrationSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) else: data = user_serializer.error return Response(data) And here is what is in my serializer.py file: from rest_framework.serializers import ModelSerializer, CharField from rest_framework.serializers import ValidationError as Error from django.contrib.auth.models import User class RegistrationSerializer(ModelSerializer): password2 = CharField( style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = [ "username", "email", "password", "password2" ] extra_kwargs = { 'password': {'write_only': True} } def save(self): user = User( email=self.validated_data['email'], username=self.validated_data['username'] ) password1 = self.validated_data['password1'] password2 = self.validated_data['password2'] if password1 != password2: raise Error({'password': 'Passwords must match'}) user.set_password(password) user.save() return user -
Is there a more DRY way to create these repetitive django class based views, and URL patterns?
Is there a better, more DRY way to create repetitive sets of views and urls in django? Below are my views and urls. As you can probably see, There are currently two sets of views and urls that are would be identical if not for the different model name. Is there a way to create 3 classes at once as a mixin or something similar to that so that all I have to do to add a new set of classes is pass the model name to one function or child class? Is there something similar I could do for the urls? relevant section in views: class AlertMessageUpdate(LoginRequiredMixin, UpdateView): template_name = "LibreBadge/applicationadmin/AlertMessage/alertMessageForm.html" model = AlertMessage fields = "__all__" class AlertMessageCreate(LoginRequiredMixin, CreateView): template_name = "LibreBadge/applicationadmin/AlertMessage/alertMessageForm.html" model = AlertMessage fields = "__all__" class AlertMessageList(LoginRequiredMixin, ListView): template_name = "LibreBadge/applicationadmin/AlertMessage/alertMessageList.html" model = AlertMessage class BadgeTemplateUpdate(LoginRequiredMixin, UpdateView): template_name = "LibreBadge/applicationadmin/BadgeTemplate/badgeTemplateForm.html" model = BadgeTemplate fields = "__all__" class BadgeTemplateCreate(LoginRequiredMixin, CreateView): template_name = "LibreBadge/applicationadmin/BadgeTemplate/badgeTemplateList.html" model = BadgeTemplate class BadgeTemplateList(LoginRequiredMixin, ListView): template_name = "LibreBadge/applicationadmin/BadgeTemplate/badgeTemplateList.html" model = BadgeTemplate relevant section in urls.py: url(r'^applicationadmin/alertmessages/update/(?P<pk>[-\w]+)/$', views.AlertMessageUpdate.as_view(), name='AlertMessageUpdate'), url(r'^applicationadmin/alertmessages/create/$', views.AlertMessageCreate.as_view(), name='AlertMessageCreate'), url('applicationadmin/alertmessages/$', views.AlertMessageList.as_view(), name='AlertMessageList'), url(r'^applicationadmin/badgetemplates/update/(?P<pk>[-\w]+)/$', views.BadgeTemplateUpdate.as_view(), name='BadgeTemplateUpdate'), url(r'^applicationadmin/badgetemplates/create/$', views.BadgeTemplateCreate.as_view(), name='BadgeTemplateCreate'), url('applicationadmin/badgetemplates/$', views.BadgeTemplateList.as_view(), name='BadgeTemplateList'), The answer to this question will be used in … -
Django. How to "join" two models that have foreignkeys to a third model?
I'm learning Django and getting data from join tables is proving to be difficult. My models are: class User(AbstractUser): pass class Post(models.Model): username_p = models.ForeignKey("User", on_delete=models.CASCADE, related_name="user_p") post = models.CharField(max_length=365) like = models.PositiveIntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.username_p} posted {self.post} the {self.timestamp}, and the post has {self.like} likes" def serialize(self): return { "id": self.id, "username": self.username_p.username, "post": self.post, "like": self.like, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), } class Follower(models.Model): followername = models.ForeignKey("User", on_delete=models.CASCADE, related_name="follower") followedname = models.ForeignKey("User", on_delete=models.CASCADE, related_name="followed") def __str__(self): return f"{self.followername} follows {self.followedname}" I'm trying to join all tables to get all the posts (including username_p, post, like and timestamp) from all the followedname users that one followername user may have. Any ideas on what query could work on my views.py? -
How to organise relationships between Django model?
I have basic Django User model, from django.contrib.auth.models import User Person model class Person(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) and Comment model class Comment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) comment = models.CharField(max_length=255) I wanna make something like: I created User, I has own unique id ( for example 1). I created Person, I has own unique id and link to User. And then I created Comment - it has link to Person model. I want that one User can have many Persons. One Person can have Comments -
Collect Static Error when trying to deploy Django application to heroku
I have put a decent amount of work into my first Django project and I wanted to host it on heroku. I have seen solutions to this problem elsewhere but everything I've tried doesn't seem to fix the error I'm getting and I've been trying to fix this for 6 hours so I figuered I'd just ask. I'm trying to use whitenoise for the static files the static files work fine in my local server, and I can run collect static in my console without any error. Here is the error -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_2341adf2_/manage.py", line 22, in <module> main() File "/tmp/build_2341adf2_/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module … -
How can have two filed of Generic Relations in same model django
class Customer(models.Model): name = models.CharField(max_length=100) class Staff(models.Model): name = models.CharField(max_length=100) class MoneyTransfer(models.Model): received_by = generic relation payed_by = generic relation How Implement two generic field in django model ? -
fatal error: libmemcached/memcached.h: no such file or directory
I try to setup a development environment for developing on django itself. Docs: Contributing / Running the test suite for the first time python -m pip install -r requirements/py3.txt It fails: ... x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DUSE_ZLIB -I/home/guettli/.virtualenvs/djangodev/include -I/usr/include/python3.8 -c src/_pylibmcmodule.c -o build/temp.linux-x86_64-3.8/src/_pylibmcmodule.o -fno-strict-aliasing -std=c99 In file included from src/_pylibmcmodule.c:34: src/_pylibmcmodule.h:42:10: fatal error: libmemcached/memcached.h: no such file or directory 42 | #include <libmemcached/memcached.h> | ^~~~~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 What can I do to fix this? -
Django: How to display posts from specific categories on a page
i am building a blog in Django and where register user can write blog articles . I want to display posts that are associated with certain categories on one page. i tried to do that but it does not show the post associated to the article. here is my files models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): # return reverse('article', args=(str(self.id))) return reverse('home') # go to home page after article submission class Post(models.Model): title = models.CharField(max_length=255) tags = models.CharField(max_length=255, default="Ryan's World") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return self.title+' | '+str(self.author) def get_absolute_url(self): # return reverse('article', args=(str(self.id))) return reverse('home') # go to home page after article submission views.py created function based view from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-id'] def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats':cats ,'category_posts': category_posts }) . . . urls.py from django.urls …