Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Bootstrap input range slider POST value into db
I have some range slider and I can't figure out why doesn't they post the value into my database. I made this job with select box before and worked fine on the same way. views.py def viselkedestipus_item(request): if request.method == 'POST': vis_01_a = request.POST.get('vis_01_a', "") vis_01_b = request.POST.get('vis_01_b', "") vis_01_c = request.POST.get('vis_01_c', "") vis_01_d = request.POST.get('vis_01_d', "") vis_01_e = request.POST.get('vis_01_e', "") vis_01_f = request.POST.get('vis_01_f', "") vis_01_g = request.POST.get('vis_01_g', "") vis_01_h = request.POST.get('vis_01_h', "") viselkedestipus = Viselkedestipus(vis_01_a=vis_01_a, vis_01_b=vis_01_b, vis_01_c=vis_01_c, vis_01_d=vis_01_d, vis_01_e=vis_01_e, vis_01_f=vis_01_f, vis_01_g=vis_01_g, vis_01_h=vis_01_h) viselkedestipus.save() return render(request, 'stressz/viselkedestipus-form.html') class ViselkedestipusCreateView(CreateView): model = Viselkedestipus form_class = ViselkedestipusForm template_name = 'stressz/viselkedestipus-form.html' def form_valid(self, form): form.instance.user_name = self.request.user return super().form_valid(form) models.py class Viselkedestipus(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) vis_01_a = models.IntegerField(null=True) vis_01_b = models.IntegerField(null=True) vis_01_c = models.IntegerField(null=True) vis_01_d = models.IntegerField(null=True) vis_01_e = models.IntegerField(null=True) vis_01_f = models.IntegerField(null=True) vis_01_g = models.IntegerField(null=True) vis_01_h = models.IntegerField(null=True) urls.py urlpatterns = [ path('', views.index, name='index'), path('login/', views.login, name='login'), path('viselkedestipus', views.ViselkedestipusCreateView.as_view(), name='viselkedestipus_item'), ] forms.py class ViselkedestipusForm(forms.ModelForm): class Meta: model = Viselkedestipus fields = ['vis_01_a', 'vis_01_b', 'vis_01_c', 'vis_01_d', 'vis_01_e', 'vis_01_f', 'vis_01_g', 'vis_01_h' ] viselkedestipus-form.html <form method="POST"> {% csrf_token %} <h4>1. question</h4> <br> <div class=""> <label for="slider" class="form-label">A1</label> <input type="range" class="form-range" min="0" max="10" name="vis_01_a" id="vis_01_a" value="0"> </div> 7 more … -
How to store Google credentials in Django model
How I can store Google credentials in Django model without using oaut2client -> DjangoORMStorage? Old version with using oaut2client: storage = Storage(models.GoogleCred, 'act', act, 'credential') storage.put(credentials) But oaut2client does not support Django>=2.0 -
Django - filter a model with multiple parameters passing to function
I have a model as below class Brand(models.Model): name = models.CharField(max_length=32) nationality = models.CharField(max_length=32) class Mobile(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) and I need a query for filtering all Mobiles objects that have the same brand name equal to the input. Input have multiple entry. And it may has no entry, in this situation have to return all the objects. def some_brand_mobiles(*brand_names): query = Mobile.objects.filter(brand__name=Q(brand_names)) return query -
Filtering an user to post something in a group only if he is already a member in that group -> Django Social Media Clone App
I'm new to Django and I've finished a course on Udemy where the project was building a simple social clone. You can look for groups, join or leave them and you can post something in that groups whether you are a member or not. I want a person to post something in a group only if he has already joined the group. In this example, a person can post something whether he is a member of not of that group. I have 2 apps, groups and posts. Here are my models: models.py - groups from django.db import models from django.utils.text import slugify from django.urls import reverse import misaka from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args,**kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('groups:single',kwargs={'slug':self.slug}) class Meta(): ordering = ['name'] class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta(): unique_together = ('group','user') models.py - posts from django.db import models from django.urls import reverse from django.conf import settings import misaka from groups.models import Group from … -
why am i getting error of AttributeError at /admin/main/consultation/ 'NoneType' object has no attribute 'lastname'
in my admin page when i click on consultation i am getting this error #model.py class doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) is_patient = models.BooleanField(default=False) is_doctor = models.BooleanField(default=True) firstname = models.CharField(max_length = 50) lastname = models.CharField(max_length = 50,default='') dob = models.DateField() address = models.CharField(max_length = 100) countrycode=models.CharField(max_length=5) mobile_no = models.CharField(max_length = 15) gender = models.CharField(max_length = 10) registration_no = models.CharField(max_length = 20) specialization = models.CharField(max_length = 30) rating = models.IntegerField(default=0) qualification = models.CharField(max_length=100,default='') year_of_registration = models.CharField(max_length=50,default='') medical_experience = models.CharField(max_length=50,default='') medical_council=models.CharField(max_length=80,default='') charges = models.IntegerField(default=0) profilephoto = models.ImageField(null=True,blank=True,upload_to="dprofile/") def __str__(self): return "Dr. " + self.firstname +" "+ self.lastname class consultation(models.Model): patient = models.ForeignKey(patient ,null=True, on_delete=models.SET_NULL) doctor = models.ForeignKey(doctor ,null=True, on_delete=models.SET_NULL) diseaseinfo = models.OneToOneField(diseaseinfo, null=True, on_delete=models.SET_NULL) consultation_date = models.DateField() status = models.CharField(max_length = 20) def __str__(self): return self.patient.firstname + " "+self.doctor.lastname + '- Dr.' +self.doctor.firstname + ' ' +self.doctor.lastname -
Django DRF filter and update only runs on server reboot
I have this model: class Applicant(models.Model): first_name = encrypt(models.CharField(max_length=35, blank=False)) last_name = encrypt(models.CharField(max_length=35, blank=False)) email = encrypt(models.CharField(max_length=255, null=True, blank=True)) ... application_status = models.ForeignKey( ApplicationStatus, on_delete=models.CASCADE, related_name="applicant_application_status", null=False, blank=False, ) objects = models.Manager() mask = MaskApplicantManager() With this custom manager: class MaskedQuerySet(models.QuerySet): def mask_applicants(self): return self.exclude(application_status__status="Hired").update( first_name="Masked", last_name="Masked", email="masked@mail.com" ) class MaskApplicantManager(models.Manager): def get_queryset(self): return MaskedQuerySet(self.model, using=self._db) def mask_applicants(self): return self.get_queryset().mask_applicants() What is the best approach for adding this to a generic view? Currently tried this: class AppliedListView(generics.ListAPIView): serializer_class = ApplicantSerializer permission_classes = (IsAuthenticated,) pagination_class = Set10Pagination lookup_url_kwarg = "job_vacancy" def get_queryset(self): vacancy = self.kwargs.get(self.lookup_url_kwarg) applicant = Applicant.mask.filter(job_vacancy=vacancy).order_by("-id") return applicant Although the masked details never run, if I change applicant to: applicant = Applicant.mask.mask_applicants().filter(job_vacancy=vacancy).order_by("-id") Then the error below is returned but on dev server reboot the masked details are applied: 'int' object has no attribute 'filter' Any tips most helpful. -
Django 'QuerySet' object has no attribute 'title'
I am creating E-Learning website and I want to show course content like playlist. For that I use foreign key in models. Here is the code of models.py class Subject(models.Model): subject_id = models.AutoField(primary_key=True) title = models.CharField(max_length=500) desc = models.CharField(max_length=800) slug = models.CharField(max_length=130) image = models.ImageField() timeStamp = models.DateTimeField(default=now) def __str__(self): return self.title class Videos(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=500) cont = models.TextField() vurl = models.URLField(max_length=200) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='videos') position = models.PositiveSmallIntegerField(verbose_name="videono.") slug = models.CharField(max_length=130) timeStamp = models.DateTimeField(default=now) def __str__(self): return self.title Code of Views.py def allsubject(request): subj = Subject.objects.all() # print(videos) context = {'subj': subj} return render(request, 'allsubject.html', context) def pvideo(request, slug): vds = Videos.objects.filter(slug=slug).values() cont = Videos.objects.get(title=vds.title) context = {'vds':vds, 'cont':cont} return render(request, 'pvideo.html', context) I think I made a mistake here cont = Videos.objects.get(title=vds.title) . If anyone has any other idea besides this, so please help me Here is the code of templates to let you know what I really want to do. {% extends 'base.html' %} {% block title %}Free Video Course{% endblock title %} {% block body %} {% for v in vds %} <div class="container"> <div class="embed-responsive embed-responsive-21by9"> <iframe class="embed-responsive-item" src="{{v.vurl}}" allowfullscreen></iframe> </div> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link … -
Django app not recognized when inside another module
I have a project with a structure like this: my-django-project/ venv/ .gitignore README.md my_django_project/ db.sqlite3 manage.py my_django_project/ settings.py my_first_app/ __init__.py inside_app/ __init__.py apps.py serializers.py models.py views.py ... In settings.py i loaded the app like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_first_app.inside_app', ] Running py manage.py runserver gives the following error: File "C:\Users\\Documents\GitHub\tin_api_v2_test\venv\lib\site-packages\django\apps\config.py", line 246, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'inside_app'. Check that 'my_first_app.inside_app.apps.InsideAppConfig.name' is correct. However, it works fine when I don't use the Virtualenv. I've also tried putting the venv inside the django project folder to see if that would change anything but it didn't work. -
Could not parse some characters: video.viewers.all.count| ans video.viewers_by_ip.all.count||intcomma
How I can parse or sum two ManyToMany field in the template <div class=""> <h6 class="card-text ml-2 p-2 bd-highlight" style="text-align: left; height: 1px; "><small class="text-muted ">{{ video.viewers.all.count + video.viewers_by_ip.all.count|intcomma }} views . </small></h6></div> -
filtering by one-digit number in MultiSelectField
I have MyModel: class MyModel(models.Model): ELEMENTS_CHOICES = Choices( (1, 'element1'), (2, 'element2'), (3, 'element3'), (4, 'element4'), (10, 'element10'), (12, 'element12'), ) elements = MultiSelectField( _('elements'), choices=ELEMENTS_CHOICES, blank=True, ) I have also some MyModel objects with elements values like below: obj1.elements = ['1', '2', '3', '10', '12'] obj2.elements = ['1', '3', '10', '12'] obj3.elements = ['1', '3', '10'] obj4.elements = ['2'] How do I filter through this field values? The filter I tried to use is: search_id = 2 MyModel.objects.filter(elements_icontains=search_id) It was ok before the two-digit numbers appeared in the MyModel field choices. Now it returns obj1, obj2 (because 12 is on the list, and it contains 2 as the part of it) and obj4. I would like to search just for values with 2 number and get just obj1 and obj4 as results. Currently, the results are objects that contains 2 and 12. What is the right way to filter this field? -
Django save signup form sent via Ajax with fetch() API
I am trying to send a signup form using Ajax and the fetch() API. The Ajax call works and I am able to send data to Django's backend: Ajax call: const sendForm = function(endpoint, formData) { const request = fetch(endpoint, { method: 'post', body: formData, credentials: 'same-origin', // pass CSRF token to the backend headers: { "X-CSRFToken": getCookie("csrftoken"), 'X-Requested-With': 'XMLHttpRequest' } }).then(console.log(formData)) } const getForm = function(endpoint) { const request = fetch(endpoint) .then(response => response.text()) .then(data => modal.innerHTML = data) .then(() => { const signupForm = document.getElementById('signup-form') // prevent default submit behaviour signupForm.addEventListener('submit', function(e){ e.preventDefault() // store form data to send to the backend const formData = new FormData(signupForm) sendForm(endpoint, formData) }) } ) } btnSignup.addEventListener('click', function(){getForm('/accounts/signup')}) If I check the request I get on the backend, I can see that form data is passed correctly and I can access it from the server: views.py if request.method == 'POST': for value in request.POST.values(): print(value) Output: giulio giulio@g.com Password123 Password123 So data is correctly sent to the server. Now, if I try to instantiate the signup form to later save it, it does not work. This is what I'm doing: views.py def SignUpView(request): # if this is a POST request we … -
Passing two Models in update view to a same template
I want to render two models User (built in model) and Profile model to the same template profile_form.html so that the user can update the data of both User model as well as Profile model This is my Profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') description = models.TextField() def __str__(self): return self.user.username + "'s Profile" This is my profile_form.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %} Make your Profile {% endblock title %} {% block content %} <div class="container mb-6"> <form action="" method="POST" class="form-group"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Submit</button> </form> </div> {% endblock content %} This is my UserUpdateView class UserUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model=User fields=['username', 'first_name', 'last_name'] success_url='/' def test_func(self): x = self.request.user.id y = self.kwargs['pk'] if x == y: return True else: if self.request.user.is_authenticated: raise Http404("You are not authenticated to edit this profile") I want my Profile model's to be below User model's form Please help me with this -
Calling a Python C extension blocks all Django processes/users
Problem I have written a Python C extension (ftaCalculate) in order to improve the performance of a given function that was previously written in pure Python. I have been able to increase the execution speed by a factor of x10, so no problem on this site. import ftaCalculate cs_min = ftaCalculate.mcs(N, tree) However, I am executing this function in a Django framework. The problem is that, until the function ftaCalculate.mcs does not finish, I cannot do anything on my website. When the function was in Python, I could press other buttons and access other URLs. This is specially a problem when several users are working at the same time in the website, because the other users cannot do anything while this function is being executed. Actually, you can see in the following image that one core is at 100% when running the function: Question Do you know any way I could call my Python C extension without "freezing" the Django framework? Possible workaround In the worst case, I could try calling this part of the code with Celery. However, I would prefer another solution, since I do not need Celery when running in pure Python. -
Template inheritance doesn't inherit encoding?
I have managed to deploy my first django app to heroku. After some struggle I got it to work and the main site is loading well however other views result in Server Error 500. Firefox console spits out this: '''The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.''' Now I'm the base.html template I am using on the main page which is loading fine has a charset="UTF-8" metatag defined. I'm extending that template for every other view in my app so I assume this tag should be also included. When I was running that locally then the templates were working fine. Any ideas on how to solve this? -
Django Admin - How to exclude an item for user permissions?
I have an app where it is not inside the permissions that I want the user to access to, but there is one item inside of it that I would like the user to change it content! Is there any solution to do that by using Groups? -
Gunicorn error 203 while setting up django project
I try setting up a django project with nginx and gunicorn but get a gunicorn error 203: My installation is located at path /webapps/sarlex and all project files are owned by user "sarlex" and group "webapps". The virtualenv is located at /webapps/sarlex/environment. Gunicorn is located at /webapps/sarlex/environment/bin/ and owned by user sarlex. Gunicorn confirmation is set in /webapps/sarlex/gunicorn_start.sh: NAME="sarlex" # Name of the application DJANGODIR=/webapps/sarlex/ # Django project directory SOCKFILE=/webapps/sarlex/run/gunicorn.sock # we will communicte using this unix socket USER=sarlex # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=9 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=sarlex.settings # which settings file should Django use DJANGO_WSGI_MODULE=sarlex.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /webapps/sarlex/environment/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Executing gunicorn_start.sh works with environment activated and deactivated. /etc/systemd/system/gunicorn.service is owned by root and has this content: [Unit] Description=gunicorn daemon After=network.target [Service] User=sarlex Group=webapps WorkingDirectory=/webapps/sarlex ExecStart=/webapps/sarlex/gunicorn_start.sh [Install] … -
Contacts matching query does not exist in django rest framework
I am trying to update Contact model fields while creating the new fields of UpdateInfo model and add them to the existing model. But I am getting this error contacts.models.Contacts.DoesNotExist: Contacts matching query does not exist. I know the contact object with the id 19 exists because I can see it when I try the get contacts API. I am sending data like this. My models: class Contacts(models.Model): full_name = models.CharField(max_length=100, blank=True) ......... def __str__(self): return self.full_name class Meta: verbose_name_plural = 'Potential Clients' class UpdateInfo(models.Model): contacts = models.ForeignKey(Contacts,on_delete=models.CASCADE, related_name='update_info') updated_at = models.DateTimeField(auto_now=True) modified_by = models.CharField(max_length=100, blank=True) def __str__(self): return f"Last modified by {self.modified_by} at {self.updated_at}" My views: class EditContactView(RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Contacts.objects.all() serializer_class = ContactsUpdateSeializer My serializers: class UpdateInfoSerializer(serializers.ModelSerializer): contacts= serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = UpdateInfo fields = ['id','contacts','updated_at','modified_by'] class ContactsUpdateSeializer(serializers.ModelSerializer): update_info = UpdateInfoSerializer(many=True) id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Contacts fields = ['id', 'full_name', 'lead_source', 'email', 'phone', 'contact_owner', 'contact_status', 'company_name', 'job_position', 'tasks', 'notes', 'email_list', 'created_by', 'created_at', 'update_info'] def update(self, instance, validated_data): update_data = validated_data.pop('update_info') id = validated_data.get('id') contacts = Contacts.objects.get(id=id) #contacts.save() #contact_only_update_logic instance.full_name = validated_data.get('full_name') instance.lead_source = validated_data.get('lead_source') instance.email = validated_data.get('email') instance.phone = validated_data.get('phone') instance.contact_owner = validated_data.get('contact_owner') instance.contact_status = validated_data.get('contact_status') instance.company_name = validated_data.get('company_name') instance.job_position = … -
Django rest framework legacy DB foreign keys appearing as Null on API
I am using django connected to a legacy mysql DB. So i used inspectdb to get the DB tables. There are 2 models that I am using: class ScCustomerTypes(models.Model): customer_type_id = models.AutoField(primary_key=True) customer_type = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'sc_customer_types' class ScCustomers(models.Model): customer_id = models.CharField(primary_key=True, max_length=100) identification_number = models.CharField(unique=True, max_length=100) customer_type = models.ForeignKey('ScCustomerTypes', models.DO_NOTHING, related_name='customer_types2customers', to_field='customer_type_id') customer_names = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True, null=True) location = models.CharField(max_length=100, blank=True, null=True) created_by = models.CharField(max_length=100, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) updated_by = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'sc_customers' Using the above I made the below serializer: from rest_framework import serializers from allDBModels.models import ScCustomers, ScCustomerTypes from employees.serializers import AllEmployeeSerializer class AllCustomerTypesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ScCustomerTypes fields = ('customer_type',) class AllCustomerSerializer(serializers.HyperlinkedModelSerializer): customer_type_id = AllCustomerTypesSerializer() class Meta: model = ScCustomers fields = ('customer_id', 'customer_type_id', 'customer_names', 'phone_number', 'identification_number', 'location', 'created_by', 'created_at', 'updated_by', 'updated_at',) Issue now is when i pull the api it returns as such: { "customer_id": "ICXY38ZP", "customer_type_id": { "customer_type": null }, "customer_names": "Test xxxxxxxxxxx", "phone_number": "2547xxxxxxx", "identification_number": "yyyyyyyyyy", "location": null, "created_by": "3b1e3f79", "created_at": "2020-10-20T13:58:21Z", "updated_by": null, "updated_at": null }, The issue is that its not returning the customer_type. … -
Django won't redirect bu urls
I am currently working on a project called NewsPaper. I bet there is a lot of works about this here. After adding a post, I have a button that subscribe the user to the category presented in the post. But, when it comes to redirect, It doesn't work at all. From my point of view, when I add a post, the "category" in Post.model doesn't refere to "category" in Category.model, and the subscribeView won't call Models.py # Create your models here. from django.urls import reverse class Author(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.author}' class Category(models.Model): category = models.CharField(max_length=255, unique=True, default='select category') subscribers = models.ManyToManyField(User, related_name='subscriber', ) def __str__(self): return self.category class Post(models.Model): news = 'news' article = 'article' Posts = [(news, 'news'), (article, 'article'), ('select', 'select')] author = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='User', blank=True, null=True) choosing = models.BooleanField(default=False) time_in = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=255, unique=True) text = models.TextField(max_length=255) rating = models.FloatField(default=0.0) def __str__(self): return f'{self.title}: {self.text[:50]}' def get_absolute_url(self): return f'/Posts/{self.id}' Views.py # Create your views here. class Post_List(ListView): model = Post template_name = 'News/post_list.html' context_object_name = 'Posts' queryset = Post.objects.order_by('-id') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['time_now'] = datetime.utcnow() return context class Post_detail(DetailView): model = Post … -
Where can I find training materials on django-otp? [closed]
I received a test task from a potential employer - to implement otp authorization in django. I completed this task through the service api.msg91.com. In the Internet I found information about the existence of the django-otp package. But I didn't find any material that I could understand about it. Please share the training materials on django-otp? Is this really a used tool? -
Reverse for 'detail_view' with keyword arguments '{'pk': 11}' not found
I am building a BlogApp and I am stuck on a Error. What i am trying to do :- I just add slug into my model and also updated get_absolute_url and url. BUT after that whenever i try to open page in browser then it shows Reverse for 'detail_view' with keyword arguments '{'pk': 11}' not found. 1 pattern(s) tried: ['detail_view/(?P[-a-zA-Z0-9_]+)/(?P[0-9]+)$'] models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') slug = models.SlugField(null=True) def get_absolute_url(self): return reverse('detail_view',kwargs={'pk':self.pk,'slug':self.slug}) views.py def detail_view(request,pk,slug): data = get_object_or_404(Post,pk=pk) urls.py path('detail_view/<slug:slug>/<int:pk>',views.detail_view,name='detail_view'), template.html <a href="{% url 'detail_view' pk=topic.pk %}">More</a><br> I have no idea what is causing this error. Any help would be Appreciated Thank You in Advance -
twillio sending message via Browser
I have implemented a Django app for sending SMS via browser, The app is working fine when I have a custom message defined from the codes. The issue is that the view codes cannot read the message input from the browser for sending. VIEWS CODE def pastor_send(request): #recepient=Ministry.objects.all() template_name='corecode/pastor.html' if request.method=='GET': message=request.GET.get('sms') client = Client(settings.ACCOUNT_SID,settings.AUTH_TOKEN) message = client.messages \ .create( body=message, from_='+somenumber', to='somenumber' ) return render(request,template_name) return HttpResponse("Message sent Succesfully",200) HTML CODE {%extends 'base.html'%} {% load crispy_forms_tags %} {%block title%} Send to Ministry Pastors {%endblock%} {%block content%} <h4><b>Create the message here<b></h4> <br> <form method='GET'> <textarea id="w3review" name="sms" rows="7" cols="70" value="{{request.GET.q}}"> </textarea> <br> <br> <a class="btn btn-primary" href="{% url 'p-sms' %}"><i class="nav-icon fas fa-sms"></i> Send</a> </form> {%endblock%} -
how to solve NOT NULL constraint failed error in django models.py
I don't want to print 'NULL' value in my django template, so I set the model property to null=False. However, during the process of adding data by uploading a file, a NOT NULL constraint failed: error is displayed. Is there a way to upload data without outputting 'NULL' to the database and template? -
Which is the better way to create a follower-following system, Foreign Key vs ManyToMany in django?
Which one would be optimal for creating the followers-following system in Django. 1.Foreign Key class Follower(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') following = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') 2.Many-To-Many class Follower(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') users = models.ManyToManyField(User) -
Logout one session with cookie domain set in Django
The host of two project are af-abc.com and abc.com. And set SESSION_COOKIE_DOMAIN SESSION_COOKIE_DOMAIN = ".abc.com" to share cookie in these two domain. My question is how to logout one project with it's own session cleared? I mean if I can keep loging in af-abc.com as I logout abc.com