Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use use the URL from feed and redirect to the user to a custom landing page based on URL in Django
I am working on a project where I am trying to build a news summarizer. It will use feedparser to parse and list the articles on home page and then if user clicks any of the links, it would redirect him to post page where he will see summary of the arcticle for which I am using newspaper and nltk library. **my views:** from django.shortcuts import render import feedparser import urllib import bs4 import nltk import newspaper from newspaper import Article url = 'https://timesofindia.indiatimes.com/rssfeedstopstories.cms' feed = feedparser.parse(url) def home(request): return render(request, 'entries/home.html', {'feed': feed}) def post(request): toi = newspaper.build('https://timesofindia.indiatimes.com/rssfeedstopstories.cms') for i in toi.articles: article = toi.articles[i] article.download() article.parse() nltk.download('punkt') article.nlp() return render(request, 'entries/post.html', {'article': article}) **Home HTML:** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Newzed</title> </head> <body> <h1>{{ feed.feed.title }}</h1> {% for item in feed.items %} <div> <p> {{ item.published }} <a href="post">{{ item.title }}</a> {{ item.author }} </p> </div> {% endfor %} </body> </html> **post HTML:** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ article.title }}</title> </head> <body> <h1>{{ article.title }}</h1> <div> <p> {{ article.summary }} </p> <p> Source for detail: <a href="{{ url }}">{{ article.title }}</a> </p> </div> </body> -
Django - my html files ignore what I change in css file?
This is my css. I want to have black font color, but I get white? and I don't know why? /* selected tag{ property: value; }*/ body{ background-image: url("/static/img/sample.jpeg"); /* top, right, bottom, left */ margin: 10px 30px 30px 30px; color: black; } This is my base html file {% load static %} <!DOCTYPE html> <html lang="en"> <link> <meta charset="UTF-8"> <title>Strona startowa</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> </head> <body> <div w3-include-html="base.html"></div> <div class="container"> <h1>Witaj użytkowniku w świecie sztucznej inteligencji</h1> <section> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="">Strona Główna</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/blog/"> Newsy <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/history/"> Historia </a> </li> <li class="nav-item active"> <a class="nav-link" href="/present/"> AI obecnie <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/philosophy/"> Filozofia AI <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/chatbot/"> Chatbot <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/talk/"> Rozmowa z moim chatbotem <span class="sr-only">(current)</span></a> </li> </div> </nav> </section> {% block content %} {% endblock %} <img src="{% static "images/AI.jpg" %}" alt="Images not found"> </div> </body> </html> This … -
CommandError: [WinError 5] Access is denied: 'C:\\Windows\\System32\\Django_Projects\\Random_Password_Generator_Project\\projectApp'
CommandError: [WinError 5] Access is denied: 'C:\Windows\System32\Django_Projects\Random_Password_Generator_Project\projectApp' I have written PS C:\Windows\System32\Django_Projects\Random_Password_Generator_Project> python manage.py startapp projectApp but getting the error above mentioned as my projectApp is not created.I have run it in VS code editor. can anyone help me in this situaton please -
404 Static file not found - Django
I have an issue with django. I recently bought an instance of a shared server and I wanted to move my django website from AWS to this server (which use Cpanel). All worked fine with AWS but when I switched to Cpanel all statics files were missing. this is my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] my project structure: my_project |-app/ |-... |-views.py |-db.sqlite3 |-manage.py |-media/ |-my_project/ |-... |-settings.py |-static/ |-main_page/ |-js/ |-my-script.js I add static files like this: {% load static %} <script src="{% static 'main_page/js/my-script.js' %}"></script> This is the error: GET http://my.domain.com/static/main_page/js/my-script.js net::ERR_ABORTED 404 (Not Found) When I go to the URL of the file it understands it like one of my URLs: 404 error screenshot I hope you will help me to solve this issue ;) thanks. -
Using multiple instance and Senders in django signals
how can i use multiple instances and senders (different models) in django signals. receiver(post_save, sender=Comment) @receiver(post_save, sender=Post) def create_comment_notification(*args, **kwargs): #comments notifier comment = kwargs['instance'] post = kwargs['instance'] if kwargs['created']: if comment.author != comment.post_connected: Notification.objects.create( assigned_to = post.author, group='NC', body=f"{comment.author} commented: {comment.content} on your post.", pk_relation=comment.id ) else: if comment.author != comment.post_connected: Notification.objects.create( assigned_to = post.author, group='NC', body=f"{comment.author} commented: {comment.content}.", pk_relation=comment.id ) I notice it work but does not recognizes the POST model, it uses COMMENT only. How can i use the two models as senders. and for the code to recognize them separately. Thank you -
Fill 24 Hours Values, Rounding the range in TImeFIeld Formset and Save in Views Django
I have following formset to save and rounding the range of TimeField in Views Django: Forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' MyModelFormSet = modelformset_factory( MyModel, form=MyModelForm, extra=1, max_num=24, ) Views.py: begin1 = datetime.datetime.strptime('01:00', '%H:%M').time() end1 = datetime.datetime.strptime('02:00', '%H:%M').time() begin2 = datetime.datetime.strptime('02:00', '%H:%M').time() end2 = datetime.datetime.strptime('03:00', '%H:%M').time() import datetime if formset.is_valid(): for item in formset: myformset = item.save(commit=False) if myformset.mytime is not None and myformset.mytime > begin1 and myformset.mytime < end1: myformset.mytime = '01:00' elif myformset.mytime is None: myformset.mytime = '01:00' else: pass if myformset.mytime is not None and myformset.mytime > begin2 and myformset.mytime < end2: myformset.mytime = '02:00' elif myformset.mytime is None: myformset.mytime = '02:00' else: pass myformset.save() It work properly to rounding the timefield when user input the mytime: 00:52 and rounding to the lowest hour as 00:00. But it failed to save the others of mytime when is None, except the user inputed. Example: When user fill the mytime: 00:52, 01:32, and 02:43 then it will save into 3 fields of mytime as: 00:00, 01:00, 02:00. But currently, it's not save the other 21 fields of mytime as: 03:00, 04:00, 05:00, 06:00, 07:00, ...... 21:00, 22:00, 23.00. How to save 3 user input … -
After creating a custom user with django when i tried to create a user my password don't show or its Blank or you can say its none
My django custom user return blank or none as password after creating a user but I can't find any problem I am new at this I've done my research but it's hopeless so help me Here is my models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyUserManager(BaseUserManager): def create_user(self, username, email, first_name, last_name, date_of_birth, gender, password=None): if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not email: raise ValueError('Users must have an email address') if not gender: raise ValueError("Users must have a gender") if not date_of_birth: raise ValueError("You Must Enter your date of birth") user = self.model( username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, gender=gender, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, first_name, last_name, date_of_birth, gender, password=None): user = self.create_user( username, email, first_name, last_name, date_of_birth, gender, ) user.set_password(password) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() gender_choices = [ ("male", "Male"), ("female", "Female"), ("others", "Others") ] gender = models.CharField(max_length=50, choices=gender_choices) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD … -
Is it possible to combine two input image upload fields and save the data in 2 different fields of related models in the backend?
Is it possible to combine two image upload fields, one field is to upload one primary image and other upload field is to upload multiple images and then send the post data to two different fields in the backend. suppose, in the backend we have a image field in Post model and images field in postimages model which is in a foreign key relation with post. So when the user uploads the images through a single upload field in the frontend, Can I somehow send the data and save it in their corresponding fields in the backend? Or is there a better way to achieve this? Thanks -
Deploying REACT app and Django as a backend in Ubuntu(Apache2)
I have already deployed my react and Django app to my test server on different ports. My Django works by using POSTMAN. But the react app fails when I tried to login and send the request to the Django backend server. I have noticed that in the Network Tab, React sends the request, not on the proper address of the backend server. Here is an example. React APP(Frontend): IP: 192.20.0.10:3000 Django APP(Backend) IP: 192.20.0.10:8000/api/auth/login API: /api/auth/login React Browser Network Tab Request URL: 192.20.0.10:3000/192.20.0.10:8000/api/auth/login *as Expected the request url must be 192.20.0.10:8000/api/auth/login *It seems that the backend url is appended to the frontend url. So that is why the test fails. Any idea why this happens? Thank you -
how can I create user login using is_staff and is_superuser in Django Rest Framework?
I am a beginner. Here I am creating user login using is_staff and is_superuser that can view other systems that register into the system and can allow and deny them. -
HTML - Python Connection
So I have a website that has a form. I want to be able to connect it to Python so that all the form inputs gets transferred to an SQL Database. I have no clue how to do it tho. I've heard that Flask is easier but I have no clue if Django is easier or harder. Any help would be appreciated. -
DRF xss protection - get user details with a POST request
I'm working on an application which is going to be using DRF for the API and Angular or React on the frontend. I'll be using cookies season authentication that will be protected against XSS by csrf token for the unsafe methods. I was wondering what is happening with the safe methods as GET in cases where I request a piece of really sensitive user information, for example, user details whit phone number or even a home address. As far as I understand HTTPS alone will not protect such information as the attack is performed on an application level rather than being intercepted which makes it human-readable. I can imagen many more cases where we want to defend safe methods, especially in user-driven applications. If an attacker gains access to our authentication cookie and performs a forged GET request to /api/v1/users/:id, which by default will not be protected by csrf token even if we decorate the view with csrf_protect(), he will be able to read the response unless I'm missing something. I went through some articles here and there but didn't find a definitive answer to this problem. My question - can we use POST request in such situations despite we … -
Display a field (or not) according to another field's value
I am working on a small project with Django. But my question is more javascript related. I have a view where I need to choose the destination of a product. Now the product can go to either an external destination or an internal one. What I want to do is to display the destination once I choose the destination type. So if I choose External Destination I want to display only the external destinations... I know this can only be done in JavaScript, but I don't know the last thing about it. -
How to use conditional on Django template?
Im working on my django project. The home page of my project is to show all of my post and category-based post on the bottom after the first part. But my code isnt working and i dont know why. Please help me #first part {% for post in blog_posts %} <div class="card d-inline-flex m-1" style="width: 18rem;"> <a href="{% url 'post-detail' post.pk %}" > <img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap"> </a> <h3>{{post.category}}</h3> <div class="card-body"> <h5 class="card-text text-center">{{ post.post_title }}</h5> <p class="card-text">{{post.post_content|truncatechars:75|safe }}</p> </div> </div> {% endfor %} #second part <h1> Opini </h1> {% for post in blog_posts %} {% if post.category == "Opini" %} #the word Opini is one of my post category <div class="card d-inline-flex m-1" style="width: 18rem;"> <a href="{% url 'post-detail' post.pk %}" > <img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap"> </a> <h3>{{post.category}}</h3> <div class="card-body"> <h5 class="card-text text-center">{{ post.post_title }}</h5> <p class="card-text">{{post.post_content|truncatechars:75|safe }}</p> </div> </div> {% endif %} {% endfor %} {% endfor %} My Models class Category(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name def get_absolute_url(self): return reverse('post_by_category', args=[self.name]) class Post(models.Model): post_title = models.CharField(max_length=50) post_img = models.ImageField(upload_to='postImage/') post_content = RichTextField(blank= True, null = True) category = models.ForeignKey(Category … -
Running the polls app under pythonanywhere
I would like to run the simple polls app from the django official tutorial under pythonanywhere. I went to the disk, downloaded the directory mysite that contains the following: db.sqlite3 manage.py mysite __init__.py urls.py wsgi.py polls __init__.py admin.py apps.py models.py tests.py urls.py views.py then I went to the pythonanywhere dashboard, clicked on "All Web apps", then on "Add a new web app", then I chose "manual configuration", "Python 3.8" and "Django", and finally I got a configuration window in which three pieces of information can be entered: "Source code", "Working directory" and "WSGI configuration file" and it contains a button "Reload xxx.pythonanywhere.com". I guess that I have to provide the right paths and then click the button to have the polls application activated and running under the xxx.pythonanywhere.com URL. But what are these paths? I have tried many combinations and always get only the default "Hello, World! This is the default welcome page for a PythonAnywhere hosted web application." In django tutorials it says one has to use manage.py to run the server, but this doesn't work under pythonanywhere. What do I have to do to get the polls app running under pythonanywhere? -
How run instascan on django local server? no https
I have a simple web page that i use to scan qr code in web page: {% extends 'myapp/base3.html' %} {% load staticfiles %} {% block content %} <html> <script type="text/javascript" src="{% static 'adapter.min.js' %}"></script> <script type="text/javascript" src="{% static 'vue.min.js' %}"></script> <script type="text/javascript" src="{% static 'instascan.min.js' %}"></script> <body> <div id="app"> <div class="row"> <div class="col-lg-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Scanner Badge</h3></div> </div> </div> <div class="col-lg-12"> <div class="preview-container"> <video id="preview"></video> </div> </div> <div class="preview-container"> <video id="preview"> </video> </div> <div class="panel panel-primary"> <section class="scans"> <ul v-if="scans.length === 0"> <li class="empty">QRCode in Camera</li> </ul> <table> <a v-for="scan in scans" :key="scan.date" :title="scan.content" :href="'{{ url }}' + scan.content"> <h1>SEND</h1> </a> </table> </section> </div> </body> <script type="text/javascript" src="{% static 'app.js' %}"></script> </html> {% endblock %} it work very well on local server using crome://flags trust unsecure and insert server ip address; but i need to load instascan on android tablet browser. There is a way to bypass certificate check and run instascan with no https server? Or, alternatively, is there any browser that allows you to load instascan without checking the certificates? -
Why is BaseDeleteView is throwing an Attribute error saying object has no attribute render_to_response?
I am trying to implement BaseDeleteview, but getting this erroe message -> 'DeletePostView' object has no attribute 'render_to_response', I did not use DeleteView mainly beacuse it expects a confirmation template and I am using bootraps's modal (like a pop up) for confirmation. I have found much similar question here -> BaseDeleteView throws AttributeError (render_to_response missing) class DeletePostView(SuccessMessageMixin, BaseDeleteView): model = Post context_object_name = 'remove_post_confirm_object' # template_name = "posts/delete_confirm_post.html" success_url = reverse_lazy('users:profile') success_message = 'Post has been deleted SuccessFully!' Error Tranceback: Traceback (most recent call last): File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/views/generic/detail.py", line 108, in get return self.render_to_response(context) Exception Type: AttributeError at /post/2020/10/10/wertyuio/remove Exception Value: 'DeletePostView' object has no attribute 'render_to_response' -
How follow toggle work in django and how to deal with exception such as RelatedObjectDoesNotExist?
Well I am trying to add follow toggle and right now that is showing me an error the error traceback is given below. I dont understand how can i get two user from detail view. first user is the one who is going to follow someone profile and the second user whose profile is going to be follow. Im and trying that thing with the following code. views.py class UserProfileDetailView(DetailView): model = UserProfile template_name = "profiles/userprofile_detail.html" def get_context_data(self,*args, **kwargs): context = super().get_context_data(*args,**kwargs) is_following = False if self.object.user in self.request.user.userprofile.follower.all(): is_following = True context["is_following"] = is_following return context urls.py urlpatterns = [ # path('user',UserProfileCreateView.as_view(template_name = 'profiles/userprofile.html'),name='home') # path('user/',userprofile,name = 'home'), path('user-profile/',UserProfileFollowToggle.as_view(),name = 'toggle'), path('<str:username>/',UserProfileDetailView.as_view(),name = 'detail'), ] userprofile_detail.html {% extends 'base.html' %} {% block content %} <p style="text-align: center;"><img src="{{ object.user.userprofile.avatar.url }}" width = "50%"></p> {{ request.user.userprofile.follower.all }}<br> {{object.user.userprofile }} {% if object.user in request.user.userprofile.follower.all %} Following {% endif %} <p>{% include 'profiles/snippets/follow_toggle.html' with username=user.username is_following=is_following %}</p> <h2>{{ object.username }}</h2> /{{is_following}} {% endblock content %} snippets/follow_toggle.html <form class='form' method='POST' action="{% url 'profiles:toggle'%}"> {% csrf_token %} <input type='hidden' name='username' value="{% if username %}{{ username }}{% else %}hello{% endif %}"> <button class='btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}'>{% if is_following %}Unfollow … -
TypeError: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. when trying to makemigrations in Django
I have created a custom user model to replace the username with an email and want to use it with Djoser and React. But when I try to make the migrations I get this error (more details below): TypeError: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user def create_superuser(self, email, password, name, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') serializers.py from djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'email', 'name', 'password') urls.py urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] I´m getting this error when I try to makemigrations: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked … -
Django get pk in decorator
I would like to know how I can get the pk of an object inside my decorator. views.py @count_view def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) decorators.py def count_view(function): def wrap(request, *args, **kwargs): pk = args print(pk) If I print args at the decorator it returns the pk of the object but as some kind of list: ('e42cbde4-787c-46a3-973f-7bd0e6ef0012',) instead of of a single string, which is what I want. -
Djnago - order_by mantomany using related names
I have following models class Model_1(models.Model): .. class Model_2(models.Model): many_items= models.ManyToManyField(Model_1, through='MyThroughModel', related_name='related_name_1') class Model_3(models.Model): one_item = models.OneToOneField(Model_2, related_name='relate_name_2', null=True, on_delete=models.CASCADE) rating = models.SmallIntegerField(_("Rating"), choices=SCORE_CHOICES) I want to order_records by the rating field in Model_3 I tried this myQryset = Model_1.objects.filter(...).order_by(...) ##This returns two records which is fine myQryset.order_by('relate_name_1__relate_name_2__rating').distinct() ## This returns two records but they are same(duplicates). I think I am doing something wrong but don't know what. Please help -
Save and Rounding the range in TimeField Formset in Views Django
I have following code to save and rounding the range of TimeField in Views Django: begin1 = datetime.datetime.strptime('01:00', '%H:%M').time() end1 = datetime.datetime.strptime('02:00', '%H:%M').time() begin2 = datetime.datetime.strptime('02:00', '%H:%M').time() end2 = datetime.datetime.strptime('03:00', '%H:%M').time() import datetime if formset.is_valid(): for item in formset: if formset.mytime > begin1 and formset.mytime < end1: # formset.mytime = item.cleaned_data['mytime'] formset.mytime = '01:00' if formset.mytime > begin2 and formset.mytime < end2: # formset.mytime = item.cleaned_data['mytime'] formset.mytime = '02:00' formset.save() So for example, if user input the mytime: 01:52 then rounding to the lowest hour and would save as 01:00. But it wouldn't save to the database. What's the wrong with above code? Thank in advanced for your help. -
Django counting hits using a decorator
I would like to count my object views using a decorator like so: def count_view(function): def wrap(request, *args): pk = args user = get_user_model().objects.get(pk=request.user.pk) hit_objects = Hit.objects.filter(viewer=user, object_id=pk) if hit_objects: return function(request) else: new_hit = Hit.objects.create(viewer=user, object_id=pk) new_hit.save() return function(request) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap where my models.py look like this: hit_post_models = models.Q(app_label='App', model='model1') | \ models.Q(app_label='App', model='model2') | \ models.Q(app_label='App', model='model3') class Hit(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=hit_post_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') viewer = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) this is how my decorator gets placed: @count_view def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) ... But I always falling into the following error: django.db.utils.IntegrityError: (1048, "Column 'content_type_id' cannot be null") -
Is it correct to use multi viewsets for a model?
I have a model which its fields must be filled by both user and admin the key issue is that user need to fill some fields by API request and admin need to fill the others in Django admin panel, I dont want user can allow to POST data to fill some fields but they would be able to see all feilds in GET request. I think this is possible with different routes and viewset. but as I'm newbie in Python/Django I'm not sure what is the best practice(s) for this porpuse. -
what 's the point of adding 'path('accounts/',include('django.contrib.auth.urls'))' to the urls.py file of the django project?
Folks i've just started learning Django and can't get my head around using 'path('accounts/',include('django.contrib.auth.urls'))' in the urls.py file of the django project. Here's my root urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), path('accounts/',include('accounts.urls',namespace='accounts')), path('accounts/',include('django.contrib.auth.urls')), path('test/',views.TestPage.as_view(),name='test'), path('thanks',views.ThanksPage.as_view(),name='thanks'), path("posts/", include("posts.urls", namespace="posts")), path("groups/",include("groups.urls", namespace="groups")), ] and here's my urls.py of the accounts app: urlpatterns = [ path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'), name="login"), path('logout/',auth_views.LogoutView.as_view(), name="logout"), path('signup/',views.SignUp.as_view(),name='signup'), ] From above, it's obvious that the accounts app is using LoginView and LogoutView for login and logout functionalities. (SignUp view uses UserCreationForm). I also removed 'path('accounts/',include('django.contrib.auth.urls'))' and tried running the server. Apparently, everything seems to work just fine (logging in, logging out and signing up). So what exactly we get by including that in the urls.py ?