Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add pagination during filtered in django
my url appear like this '''http://127.0.0.1:8000/menu/?[%27tags%27,%20%271%27]&page=2''' I want to make 'http://127.0.0.1:8000/menu/?tags=2&page=2' Thank you all.. munu_extras.py from django import template from ..models import Menu register = template.Library() @register.simple_tag def my_url(value,field_name,urlencode=None): url = "{}={}".format(field_name,value ) if urlencode: querystring = urlencode.split('=') filtered_querystring = filter(lambda p: p.split('=')[0]!=field_name, querystring) print(filtered_querystring) encode_querystring = '='.join(filtered_querystring) url = '?{}&{}'.format(querystring,url) return url In My menu.html {% if menus.has_previous %} <a href="{% my_url 1 'page' request.GET.urlencode %}"><<<</a> <a href="{% my_url menus.previous_page_number 'page' request.GET.urlencode %}"><<</a> {% endif %} {% if menus.has_next %} <a href="{% my_url menus.next_page_number 'page' request.GET.urlencode %}">>></a> <a href="{% my_url menus.paginator.num_pages 'page' request.GET.urlencode %}">>>></a> {% endif %} -
Binding an application to a djangocms page
Hello everyone I am writing a project on django(3.0.11)+django cms(3.7.4). I created several applications, and when I try to link the application to a page created via django cms, these applications are not displayed. Has anyone encountered such a problem? cms_apps.py from aldryn_apphooks_config.app_base import CMSConfigApp from cms.apphook_pool import apphook_pool from blog.cms_appconfig import BlogConfig @apphook_pool.register class BlogApp(CMSConfigApp): name = "Статьи" urls = ["blog.urls"] app_name = "blog" app_config = BlogConfig cms_appconfig.py from aldryn_apphooks_config.utils import setup_config from app_data import AppDataForm from djangocms_text_ckeditor.fields import HTMLField class BlogConfig(AppHookConfig): description = HTMLField("описание", blank=False, default="") class Meta: verbose_name = 'Настройка блога' verbose_name_plural = 'Настройки блога' class BlogConfigForm(AppDataForm): pass setup_config(BlogConfigForm, BlogConfig) -
Django redirect with pk passed as argument
How can django redirect work with id parameter? return redirect('/invoices/status/',pk=est.invoice.id) it matches to following urls.py urlpatterns=[ path('',views.index,name='invoice_index'), path('insert/',views.insert_,name='invoice_insert'), path('<int:id>/',views.insert_,name='invoice_update'), path('delete/<int:id>/',views.delete_,name='invoice_delete'), path('status/<int:id>/',views.status_,name='invoice_status'), path('details/<int:id>/',views.details_,name='invoice_details'), ] It generate following error [name='home'] admin/ clientservices/ clients/ taxauthority/ vendor/ invoices/ [name='invoice_index'] invoices/ insert/ [name='invoice_insert'] invoices/ <int:id>/ [name='invoice_update'] invoices/ delete/<int:id>/ [name='invoice_delete'] invoices/ status/<int:id>/ [name='invoice_status'] invoices/ details/<int:id>/ [name='invoice_details'] estimate/ quotation/ ^media/(?P<path>.*)$ -
Update/Change information of currnet User instance in ModelForm in Django
How can I edit an User Instance information of a user(first_name, last_name, email) with extending OneToOne Relationship profile page. Below my code is not giving me any error but also not updating my given information in DB for user. The User model is not created by me but I use django.contrib.auth.models.User also I don't want to use UpdateView class from Django. Any help would be appreciated. PIP Freeze asgiref==3.3.1 Django==3.1.5 django-crispy-forms==1.10.0 Pillow==8.1.0 pytz==2020.5 sqlparse==0.4.1 Code: users/forms.py from django import forms from django.contrib.auth.models import User from .models import Profile class UserUpdateForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField() class Meta: model = User fields = ['first_name', 'last_name', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] users/views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import UserUpdateForm, ProfileUpdateForm from django.contrib import messages @login_required def profile(request): if request.POST == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, "Your profile has been updated !") return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'title': "Profile", 'act': 'profile', 'u_form': u_form, 'p_form': p_form, } return render(request, 'users/profile.html', context) users/profile.html {% extends 'base.html' %} {% load crispy_forms_tags … -
'Users' object has no attribute 'values' django rest framework
I'm having a problem with serializing the data with joined tables. Am i doing this right? i'm just a newbie in django. here's my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser class Agency(models.Model): agency_id = models.CharField(primary_key=True, max_length=50) agency_shortname = models.CharField(max_length=20, blank=True, null=True) agency_longname = models.CharField(max_length=255, blank=True, null=True) date_created = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'agency' class Users(AbstractBaseUser): USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] user_id = models.CharField(primary_key=True, max_length=50) first_name = models.CharField(max_length=50, blank=True, null=True) middle_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField(unique=True, max_length=50, blank=True, null=True) password = models.CharField(max_length=100, blank=True, null=True) agency = models.OneToOneField(Agency, models.DO_NOTHING) date_created = models.DateTimeField(blank=True, null=True) active = models.CharField(max_length=8) login_status = models.CharField(max_length=6) last_login = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'users' Then in my serializers.py from rest_framework import serializers from .models import Users, Agency class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' class AgencyDetailSerializer(serializers.ModelSerializer): agency_id = UserDetailSerializer() class Meta: model = Agency fields = ['agency_id','agency_shortname','agency_longname'] and my views.py from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from .serializers import UserDetailSerializer from .models import Users, Agency from rest_framework.permissions import IsAuthenticated @api_view(['GET']) @permission_classes([IsAuthenticated]) def userData(request): username = request.GET.get('username') r_type = request.GET.get('type') user = Users.objects.get(username=username).values('user_id','first_name','middle_name','last_name','username','email','agency__agency_id','agency__agency_shortname','agency__agency_longname') user_serializer … -
Unable to follow django-quickbook steps
I am working on a Django web application and I want to push data to Quickbook Desktop. So i was following this link https://github.com/weltlink/django-quickbooks/. The third step where you have to create the qwc file with the manage.py command is not working. How to perform this step- python manage.py create_qwc error:- Unknown command: 'create_qwc' In settings.py:- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'bootstrap4', 'faqTable', 'pdftrack', 'informations', 'django_quickbooks'] I have ran manage.py makemigrations and migrate command but It's not working. Can any body help? -
How to get session variable in class Meta django?
def getdb(): print(request.session['process']) return request.session['process'] I need to access this function in class Meta: in django -
How do I include my def clean_slug function into my views or template so that it will work and show "title alr exist"
Hi I have written a clean_slug in forms to make sure that was previously already a post with the same title, they will return a message saying that the title already exists and hence the form cannot be submitted. How do I include this in my views and templates so that it will work and show the "title alr exists" message? or did I write my function in forms.py wrongly? because the form isnt valid now. Note: There is no slug field in my form. The slug is only for the url..thank you! views.py def create_blog_view(request): context = {} form = CreateBlogPostForm(request.POST or None, request.FILES or None) if form.is_valid(): obj= form.save(commit = False) author = Account.objects.filter(email=user.email).first() obj.author = author obj.save() obj.members.add(request.user) return redirect('HomeFeed:main') context['form'] = form return render(request, "HomeFeed/create_blog.html", {}) forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['chief_title', 'brief_description'] BlogPost.objects.exclude(pk=self.instance.pk).filter(chief_title__iexact=chief_title): def clean_slug(self): slug = slugify(self.cleaned_data.get("chief_title")) if len(self.cleaned_data.get("slug", )) == 0 \ else self.cleaned_data.get("slug", ) if BlogPost.objects.filter(slug=slug).exists(): self.add_error("slug", "BlogPost with the same title/slug already exists") return slug html <label for="id_title">Chief Title!</label> <input class="form-control" type="text" name="chief_title" id="id_title" placeholder="Title" required autofocus> </div> {{form.chief_title.errors}} -
How to sort list in Django Template form button click?
I have a Django View where I get all Expanses from the DB. I render them in the HTML Template like below. I want to have a button that is changing the sorting of the items by date on button click. What is best practise to do so ? // View Snippet def expanse_list(request): #List of all expanses expanses_list = Expanse.objects.all() // Template Snippet {% for expans in expanses %} <li class="expanse-card"> -
Django InlineAdmin field already exist
I have a table FilmWork which is linked to a table Perosn via FilmWorkPerson table. Person table has name and persons role (actor, writer, director). I wanted to be able to edit actors, writers, directors separately. So far, I am able to display them separately but not save: Models: class FilmWorkPerson(models.Model): id = models.AutoField(primary_key=True, editable=False) movie = models.OneToOneField('FilmWork', models.CASCADE, unique=False) person = models.ForeignKey('Person', models.CASCADE, unique=False) created_on = models.DateTimeField(auto_now=True) class Meta: db_table = 'film_work_person' unique_together = (('movie', 'person'),) class FilmWork(models.Model): # what we have from sql id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(, max_length=255) people = models.ManyToManyField('Person', through=FilmWorkPerson) class Person(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField( max_length=100) role = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now =True) movie = models.ManyToManyField(FilmWork, through=FilmWorkPerson) class Meta: db_table = 'person' def __str__(self): return self.name class ActorManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(role='actor') class Actor(Person): objects = ActorManager() class Meta: proxy = True admin.py: class PersonInlineAdmin(admin.TabularInline): model = Person.movie.through @admin.register(Actor) class ActorAdmin(admin.ModelAdmin): list_display = ('name', ) fields = ('name', ) search_fields = ('name', ) list_filter = ('movie',) inlines = (PersonInlineAdmin,) Does someone know how do I save this properly now? Do I have to write custom save function? I can also save name alone, but it does not … -
django.db.utils.OperationalError: FATAL: Peer authentication failed for user ""
This has been giving me problems for a few days now. I have a django application that I am trying to connect to an elephantsql database. My settings look like this: DATABASES = {'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name_provided_by_elephantsql', 'USER': 'name_provided_by_elephantsql', 'PASSWORD': 'xxxxxxxxxxxxxxxx', 'Host': 'ziggy.db.elephantsql.com', 'PORT': '5432', } } Every time I try to makemigrations, I get the following error: `django.db.utils.OperationalError: FATAL: Peer authentication failed for user "name_provided_by_elephantsql" My pg_hba.conf file looks like this, but I have tried adding the credentials under IPv6, as well as changing several of the 'peer' to 'md5': # Database administrative login by Unix domain socket local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. local replication all peer host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5 Then I tried to create a psql user with the same name, and created a database with it: createdb -U name_provided_by_elephantsql -h ziggy.db.elephantsql.com -p 5432 And it returned: createdb: error: … -
Login authentication in different user table django
I am using custom table for login and registration of user, But I am getting error in login for not matching data with same table of user. Here my code is : I have changed user model in settings file. settings.py AUTH_USER_MODEL = 'assets.userInfo' models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,BaseUserManager ,UserManager class userInfo(AbstractBaseUser): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) username = models.CharField(max_length=200) email = models.EmailField(max_length=200,verbose_name="email" , unique=True) password = models.CharField(max_length=200) abn = models.CharField(max_length=200) password = models.CharField(max_length=200) isActive = models.BooleanField(default=True) created_date = models.DateTimeField(default=timezone.now) REQUIRED_FIELDS =['username'] USERNAME_FIELD = 'email' objects = UserManager() class Meta: db_table="userInfo" views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate from django.contrib.auth.models import User , auth from django.contrib import messages from .models import userInfo , sector ,companyInfo ,capability , saleStages ,companySaleStages from django.contrib.auth.hashers import make_password from .forms import CompanyDataForm # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] abn = request.POST['abn'] email = request.POST['email'] if password1==password2: if userInfo.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('register') elif userInfo.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') elif userInfo.objects.filter(abn=abn).exists(): messages.info(request,'ABN Number Taken') return redirect('register') else: user = userInfo.objects.create(username=username, password=make_password(password1), email=email,first_name=first_name,last_name=last_name,abn=abn) user.save() # … -
Django Webpack Loader, in production django.cgi not rendering VUE.js dist/ file
I am having an issue about rendering /dist file that collected as static. It's very much renders without a problem on development serve. But after I build, it doesn't. vue.config file const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "https:/domain.com/django-folder/", // publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' css: { extract: { filename: 'bundle.css', chunkFilename: 'bundle.css', }, } }; django settings.py STATIC_URL = '/django-folder/static/' STATIC_ROOT = "/home/domain-name/www/django-folder/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "frontend/dist"), ] after I built the vue frontend. I copy/paste the dist folder inside the domain.com/django-folder/frontend/ and then run manage.py collectstatic command. All /dist collects in the static folder without a problem. But it doesn't renders. NO ERROR, just a blank page. Additionally django.cgi I am appending the django-folder like below. # Change this to the directory above your site code. sys.path.append("/home/domain-name/venv/lib/python3.8/site-packages") sys.path.append("/home/domain-name/www/django-folder") os.environ["DJANGO_SETTINGS_MODULE"] = "src.settings" And Django paths are working like admin/ or api/endpoints But vue is not showing up. -
How to do a POST request in a DetailView
im following a tutorial for the project but it does it on function views and im trying to do it on class based views i get a ( The view blog.views.PostDetailView didn't return an HttpResponse object. It returned None instead.) error but thats not my concern now ... because the data(new comments) arent getting saved so how can i save them with the post request and redirect to the same page of the DetailView my urls app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='blog-home'), path('blog/<slug:slug>/', views.PostDetailView.as_view() , name='post-detail'), ] my models class Post(models.Model): options = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish_date') publish_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.CharField(max_length=10, choices=options, default='draft') class Meta: ordering = ('-publish_date',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() publish_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-publish_date',) def __str__(self): return f'Comment By {self.author}/{self.post}' my forms class AddCommentForm(forms.ModelForm): content = forms.CharField(label ="", widget = forms.Textarea( attrs ={ 'class':'form-control', 'placeholder':'Comment here !', 'rows':4, 'cols':50 })) class Meta: model = Comment fields =['content'] my views class PostDetailView( DetailView): … -
Django RestAPI 500 error when trying to GET a list of records
What I am trying to achieve: Is get a simple list of ALL links FOR THE logged in User - using this end point : http://127.0.0.1:8000/api/affypartnerlinks/ The list should include ALL of the fields (including key) from the USERaffylinks model table PLUS the associated site_name from the USERaffiliates table - but only for the current logged in user. CURL test curl -X GET http://127.0.0.1:8000/api/affypartnerlinks/ -H 'Authorization: Token afdf84a95d53e15aea484b011fd3c754b165c1f2' This is the error I am getting. 500 Error: AttributeError: Got AttributeError when attempting to get a value for field owner_link_useraffyid on serializer USERaffylinksSerializer. The serializer field might be named incorrectly and not match any attribute or key on the USERaffiliates instance. Original exception text was: 'USERaffiliates' object has no attribute 'owner_link_useraffyid'. --- Thank you :) VIEWS.py @action(methods=['POST','GET',], detail=True) class AffyPartnerLinksViewSet(viewsets.ModelViewSet): queryset= USERaffylinks.objects.all() #need to filter on login user > owneruserid=request.user.id serializer_class = USERaffylinksSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, ) def get_queryset(self): #restrict to current logged in user user = self.request.user return USERaffiliates.objects.filter(owneruserid=user) SERIALIZER.py class USERaffylinksSerializer(serializers.ModelSerializer): class Meta: model = USERaffylinks fields = '__all__' extra_fields = ['site_name'] #from USERaffiliates table extra_kwargs = { 'owneruserid': {'required':True}, 'owner_link_useraffyid': {'required':True} } def get_field_names(self, declared_fields, info): expanded_fields = super(USERaffylinksSerializer, self).get_field_names(declared_fields, info) if getattr(self.Meta, 'extra_fields', None): … -
order_by not working on a filtered queryset
i have this view def post_list(request,user_id=None): posts = Post.objects.all().order_by('-created') if user_id: user = User.objects.get(id=user_id) posts = Post.objects.filter(user=user).order_by('-created') return render(request,'post/list.html',{'posts': posts}) the Order_by is working for Post.objects.all() but not for Post.objects.filter(user=user) , any idea why? they are rendered the same way, to the same html -
Add AJAX to Django to update data without a page reload
I've seen other similar questions, but still confused as to how AJAX implementation works. I have an html table that currently gets updated when the page gets reloaded. I would like to accomplish this asynchronously using AJAX to Django. My views.py def scan_status(request): path = 'network_path/test/example.json' try: scan_data = json.load(open(path)) except Exception: traceback.print_exc() scan_data = None print('Path not found!') if scan_data is not None: df = pd.DataFrame( columns=['Folder', 'Scan Time', 'Generate Time']) for folder in scan_data['input_folders']: scan_time = scan_data['input_folders'][folder]['scan_time'] if 'generate_time' in scan_data['input_folders'][folder]: generate_time = scan_data['input_folders'][folder]['generate_time'] df = df.append({'Folder': folder, "Scan Time": scan_time, 'Generate Time': generate_time}, ignore_index=True) else: df = df.append({'Folder': folder, "Scan Time": scan_time}, ignore_index=True) table = df.to_html( na_rep='0', justify='left', float_format='%.0f', border=0, index=False) else: table = None return render(request, 'webpage/scan.html', context={'table': table}) My HTML <div> {{table | safe}} </div> -
Generate PDF Document From Django And Dot Net Core
I developed some web apps by Django and .NET Core which let user input the formatted text and saved to database by using TinyMCE editor. The formatted text will be saved as HTML text. I want to generate a PDF document which include the formatted text and the document has fixed format of every page. For example, the Purchase Order will show the Supplier and PO number on every pages. I try JasperReport community and FastReport Open Source but found that it is lack of HTML tags they supported. So the output of HTML text almost unformatted. Do you have any suggested Reprot Tools which have better support of HTML used in Django and .NET Core? Thank you! -
DRF. Matching query does not exist
Okay I have been at this for a while and cannot figure it out. Whenever I make a new job post I get the following error jobs.models.Positions.DoesNotExist: Positions matching query does not exist. Business Model: from django.db import models from django_google_maps import fields as map_fields from django.conf import settings User = settings.AUTH_USER_MODEL Company = settings.COMPANY_USER_MODEL class Business(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) business = models.CharField(max_length=50, unique=True) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) about = models.TextField(max_length=1000, null=True) def __str__(self): return self.business Job Model: from django.db import models from django_google_maps import fields as map_fields import uuid as uuid_lib from django.conf import settings User = settings.AUTH_USER_MODEL Business = settings.BUSINESS_MODEL class Positions(models.Model): position = models.CharField(max_length=100) def __str__(self): return self.position class Job(models.Model): employer = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey('business.Business', related_name='jobs', on_delete=models.CASCADE) position = models.ForeignKey(Positions, on_delete=models.CASCADE) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) job_detail = models.TextField() # TODO: set length full_time = models.BooleanField(default=False) part_time = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address Job Serializer: from rest_framework import serializers, fields from .models import Job, Type, Positions def get_business_model(): return django_apps.get_model(settings.BUSINESS_MODEL, require_ready=False) Business = get_business_model() # Position Serializer class PositionSerializer(serializers.ModelSerializer): class Meta: model = Positions fields = "__all__" class JobSerializer(serializers.ModelSerializer): … -
How to colve SSL SYSCALL error: Bad file descriptor with celery?
I had an issue running celery tasks. celery was down for unkonwn issue. I tried to use django dbshell to check the table contains the task results: SELECT * FROM django_celery_results_taskresult LIMIT 1; Here is the query output: I found an error related to SSL and the same errors populated over and over on sentry issue. Is there a way to get rid of it? -
get M2M model from intermediate table name
I need to get access to m2m model from intermediate table name. Example models: class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person) so the table name is group_person, how can i access to it's model only from name? Due to circumstances i can't use through/etc from parent/related model. Im getting list of m2m tables names like this: m2m_fields = model_class._meta.local_many_to_many if m2m_fields: for field in m2m_fields: table = field.remote_field.through intermediate_table_name = table.__name__ while iterating over some models Thanks! Sorry for bad eng:) -
django: how to implement public like button
I would like to implement a simple 'like' button. No need for user authentication etc, I prefer to be simple, on click +1 like. Any ideas on how to implement this like btn? I appreciate your help! models.py class Mainnews(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to = 'photos/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) views_counter = models.IntegerField(default=0) likes = models.IntegerField(default=0) def number_of_likes(self): return self.likes.count() def __str__(self): return self.title -
Uncaught TypeError: Cannot read property 'id' of undefined at HTMLParagraphElement.<anonymous>
I've been looking at this for ages and feel like I'm missing something obvious, any help much appreciated! I'm trying to create nested accordions to represent a Django model in a convenient way. Paragraph elements are created and given ids using a Django for loop. Then JS is used to assign functionality (code below). The title error points to the first id reference from this line, suggesting it is undefined. if (acc2[i].id.slice(acc2[i].indexOf("_")+1) === acc3[j].id.slice(acc3[j].indexOf("_")+1)) { However, using console.log I can get the expected values for these ids ("chain_name_1" and "chainseq_1" in the first iteration of the loop, when the error occurs). I can't figure out why they subsequently show up as undefined. var acc2 = document.getElementsByClassName("prot_acc_2"); var acc3 = document.getElementsByClassName("prot_acc_3"); var i; var j; for (i = 0; i < acc2.length; i++) { acc2[i].addEventListener("click", function() { for (j = 0; j < acc3.length; j++) { console.log(acc2[0].id) console.log(acc3[0].id) var content = acc3[j]; if (acc2[i].id.slice(acc2[i].indexOf("_")+1) === acc3[j].id.slice(acc3[j].indexOf("_")+1)) { if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } } } }); } -
Call Python command within Javascript using Django
I have a registration form that asks for username. So in javascript I want to check if the username exists in the database (via python), every time the text is edited. So how can I call a python command from within javascript and get the resulting list/array? $("#inputUsername").change(function() { var userNameInput = $("#inputUsername").val(); var existingUsernames = getExistingUsernames(); // get from python if (existingUsernames.includes(userNameInput)) { // reject form } }) def getExistingUsernames(): return database.get("users").usernames() -
How can i do a POST request in a Deatil View with a create view for comment form / Django
i dont think my approach is a good one by passing my CommentView to the DetailView... and because of the the comment view makes a form for the post model instead of the comment model but now i dont know how to save the form and return the new comments and when i try to do that a new empty post is made instead (draft) .. (i see the post in the admin site) and i get a Reverse for 'post-detail' not found. 'post-detail' is not a valid view function or pattern name error should i change the whole code to function views? my urls app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='blog-home'), path('blog/<slug:slug>/', views.PostDetailView.as_view() , name='post-detail'), ] my models class Post(models.Model): options = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish_date') publish_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.CharField(max_length=10, choices=options, default='draft') class Meta: ordering = ('-publish_date',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() publish_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-publish_date',) def __str__(self): return f'Comment By {self.author}/{self.post}' my forms class …