Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Downloading a FileField with a View
I have a table which presents order information - attached to each order is a file. This file's file path displays as a link in the table already, but I am unable to download by clicking it. I would like to be able to click this link and have the proper .docx download. I am referencing: how to download a filefield file in django view but I really don't understand how this solution is working. Is no URL needed? How does the view know which file to pick? I opened a previous question and got marked as a duplicate and pointed to this link, but I really don't understand the solution that was given here. Do I need to somehow pass the pk of the order or something? Any help would be greatly appreciated. Below is my code. models.py class Orders(models.Model): ... order_file = models.FileField(upload_to='web_unit', null=True, blank=True) ... def __str__(self): return self.reference index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> .... </thead> <tbody> {% for order in orders %} <tr> <td> <!-- Update book buttons --> <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' order.pk %}"> <span class="fa fa-pencil"></span> … -
Django CSRF Verification Failed when using WSGIDaemonProcess with multiple processes
My Django version is 2.2 and I've configured httpd.conf to start a process pool like so: WSGIDaemonProcess my_app processes=6 threads=12 display-name=%{GROUP} home=/tmp maximum-requests=1000 inactivity-timeout=1800 request-timeout=500 python-path=${MY_ENV_VAR} With this setup, I would get Forbidden 403 errors with CSRF verification failed message when I do a POST request. If I keep refreshing the page, when I get lucky, my POST request would succeed. Now I'm guessing this is because the request might have landed onto the Django process that has the "right cache". To test the above theory, if I change the httpd.conf to have only 1 pool process like below, I do not get the 403 error. WSGIDaemonProcess my_app processes=1 threads=12 display-name=%{GROUP} home=/tmp maximum-requests=1000 inactivity-timeout=1800 request-timeout=500 python-path=${MY_ENV_VAR} I have followed the CSRF specific instructions on Django documentation and tried both scenarios when CSRF_USE_SESSIONS is set to True or False What is the recommended approach to configuring Django if I intend to spin up a pool for wsgi processes each of which would run my Django app? -
I am trying to implement the django-simple-referral
I am trying to implement the django-simple-referral. I have written all the necessary required codes according to the documentation provided by django-simple-referral. But after registration is done I am getting the error "'Settings' object has no attribute 'PINAX_REFERRALS_CODE_GENERATOR_CALLBACK'". Please help me with this issue -
Python pip install mysqlclient
So I downloaded Python 32 bits 1st, then I did python -m pip install mysqlclient.I needed Visual C++ 2015, but I had them cuz my text editors is VSCode.I uninstalled VSCode, installed Visual Studio Build Tools, and I am getting this errors whenever I do python -m pip install mysqlclient.One, cl.exe wasnt added to my path, so I did, but it still says error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\cl.exe' failed with exit status 2 so I downloaded the wheel package for windows, as some other stackoverflow answer said.Whenever I run it, I get I tried downloading Python 64 bits downloading the wheels, adding cl.exe to path. Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/4d/38/c5f8bac9c50f3042c8f05615f84206f77f03db79781db841898fde1bb284/mysqlclient-1.4.4.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Program Files (x86)\Python\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Patrik\\AppData\\Local\\Temp\\pip-install-0vmm7fdx\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\Patrik\\AppData\\Local\\Temp\\pip-install-0vmm7fdx\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Patrik\AppData\Local\Temp\pip-wheel-o3ba369p' --python-tag cp37 cwd: C:\Users\Patrik\AppData\Local\Temp\pip-install-0vmm7fdx\mysqlclient\ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb … -
Adding multiple instances of a ForeignKey
I have a simple Person class and a Club class that should contain lots of Person instances: from django.db import models class Person(models.Model): name = models.CharField(max_length=200) class Club(models.Model): name = models.CharField(max_length=200) persons = models.ForeignKey(Person, on_delete=models.CASCADE) How do I add more than one Person to the persons attribute? I want to build a database and then save it as follows: club = Club(name='some_club') club.person.add(Person(name='Alex')) club.person.add(Person(name='John')) club.save() # etc. ... -
unable to specify custom Django Model from nested app as AUTH_USER_MODEL
I am unable to specify a custom AUTH_USER_MODEL if that model is in a nested application. Here is some project structure: ├── project │ ├── settings.py │ ├── my_parent_app │ │ ├── __init__.py │ │ ├── apps.py │ │ └── my_child_app │ │ ├── __init__.py │ │ ├── apps.py │ │ └── models.py and here is some code: project/my_parent_app/my_child_app/models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_a_nice_user = models.BooleanField(default=False) project/settings.py: INSTALLED_APPS = [ 'my_parent_app', 'my_parent_app.my_child_app', ] AUTH_USER_MODEL = 'my_parent_app.my_child_app.User' When I try to do anything, I get this error: ValueError: Invalid model reference 'my_parent_app.my_child_app.User'. String model references must be of the form 'app_label.ModelName'. This is a very similar to this question. But how can I solve this without resorting to making my_child_app a separate top-level app? -
How to serve static files in Django application running inside Kubernetes
I have a small application built in Django. it serves as a frontend and it's being installed in one of out K8S clusters. I'm using helm to deploy the charts and I fail to serve the static files of Django correctly. Iv'e searched in multiple locations, but I ended up with inability to find one that will fix my problem. That's my ingress file: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: orion-toolbelt namespace: {{ .Values.global.namespace }} annotations: # ingress.kubernetes.io/secure-backends: "false" # nginx.ingress.kubernetes.io/secure-backends: "false" ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/rewrite-target: / ingress.kubernetes.io/force-ssl-redirect: "false" nginx.ingress.kubernetes.io/force-ssl-redirect: "false" ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/ssl-redirect: "false" ingress.kubernetes.io/ingress.allow-http: "true" nginx.ingress.kubernetes.io/ingress.allow-http: "true" nginx.ingress.kubernetes.io/proxy-body-size: 500m spec: rules: - http: paths: - path: /orion-toolbelt backend: serviceName: orion-toolbelt servicePort: {{ .Values.service.port }} the static file location in django is kept default e.g. STATIC_URL = "/static" the user ended up with inability to access the static files that way.. what should I do next? -
How do I close my camera frame after reading/deciding a qr code with pyzbar?
I've been working on this QR code scanner and so far I've gotten everything to work out; The camera works and the frame shows up. pyzbar decodes the QR codes I show it. regex slices the string I need within the decoded data. Text of the data is shown within the frame. Models are updated accordingly. and lastly I update my list for the time the QR was detected The Problem is I actually want the frame to close when a single QR code is detected, decoded and all of the above process is completed. What actually happens is after the frame is open it constantly and after it detects a QR code, it actually logs multiple (around 15) instances of a QR being detected after like 2 seconds. Also the frame is still up and I can still detect Images. The frame closes, only after pressing the waitkey which is 27 or 'Esc' I've tried adding this: for obj in decodedObjects: id = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data)) cv2.putText(frame, str(id[0]), (50, 50), font, 3, (255, 255, 255), 2) attendee = get_object_or_404(Attendee, pk=str(id[0])) attendee.present = True attendee.timestamp = timezone.now() attendee.time_log.append(attendee.timestamp) attendee.save() if id is not None: cv2.destroyAllWindows() break but obviously that won't work … -
How to restrict access to DetailView depending on user permission AND MODEL ATTRIBUTE VALUE?
I'd like to restrict access to some detail article pages that have an attribute is_private=True . They can be displayed in article list, but only users who have a permission view_private_articles must be able to access it. models.py: class Article(models.Model): title = models.CharField( max_length=150, ) is_private = models.BooleanField( default=False, ) views.py: class ArticleListView(LoginRequiredMixin,ListView): model = Article template_name = 'article_list.html' context_object_name = 'article_objects_list' login_url = 'login' class Meta: permissions = [ ("view_private_articles", "Can view private articles"), ] def __str__(self): return self.value class ArticleDetailView( LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Article context_object_name = 'article_object' template_name = 'detail/article_detail.html' login_url = 'login' permission_required = 'view_private_articles' Problem is, as you could notice, that approach, described here can only restrict users who don't have view_private_articles permission to view ALL ARTICLES (not only with is_private=True attribute). So how to restrict that users to view only articles with attribute is_private=True? -
Display Django TextField in Template (Django 2+)
I am trying to display some content in my database to a template, my model is this below and am trying to access only about inside About_us so as it can be displayed in the template. ''' class About_us(models.Model): welcome_to= models.TextField(max_length=None) about = models.TextField(max_length=None) vision_mission = models.TextField(max_length=None) organization_structure = models.TextField(max_length=None) ''' in my views file this is what i have ''' def about(request): content = About_us._meta.get_field('about').db_column return render(request, 'aboutenos.html', {'content': content}) ''' But the text in the database doesn't show it only shows "None" <p> {{ content.content }} </p> -
Why does the Django Test Client Post Request on a CreateView Fail to Redirect?
My django.test Client returns a response with status code, 200, when I made a post request instead of redirecting with a status code, 302. I am using Django 2.2.4 with Python 3.7.3. No login is required (as addressed by Why does Django Redirect Test Fail?) neither does setting the follow and secure parameters to True (as addressed by Django test client POST command not registering through 301 redirect) I noticed that the same problem affects my update view. It doesn't redirect when I call the Django Test Client with a put method. (I didn't include this code to avoid verbosity). Finally, I noticed that the page redirect works when I python manage.py runserver and then visit the page to create a new Book instance. Here's the test: from django.test import TestCase, Client from django.urls import reverse ... class TestDashboardViews(TestCase): def setUp(self): self.client = Client() self.book_list_url = reverse("dashboard-home") self.book_create_url = reverse("dashboard-upload-book") self.another_demo_book_kwargs = { "title": "Demo Title", "author": "Demo Author", "subject": "Another Demo Subject", "details": "Another Demo Details", "file": "path/to/another/demo/file" } ... def test_book_create_view_using_post_method(self): response = self.client.post(self.book_create_url, self.another_demo_book_kwargs) self.assertRedirects(response, self.book_list_url) ... Here's the affected view: class BookCreateView(CreateView): model = Book fields = ['title', 'author', 'subject', 'details', 'file'] success_url = reverse_lazy("dashboard-home") Here's … -
Images not showing on site python/django
I can not see the images/images show up as broken on my site. I checked other questions to this but none have solved my issue. Here is everything I have tried 1) Installed Pillow: imported it in my models.py 2) Settings.py has : MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' 3) Pictures: currently in my "media" folder which sits in my main project directory 4) app/urls.py has: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and imported settings 5) Template has: {% load static %} and {{ post.image.url }} 6) Collected static 7) Made migrations 8) Ran server settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'profiles/static/') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('post/<id>/', views.post, name='post'), .... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models from django.conf import settings from PIL import Image class Profile(models.Model): title = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(max_length=500, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) def __str__(self): return f'{self.user.username} Profile' class Post(models.Model): title = models.CharField(max_length=200) post = models.TextField(max_length=100, blank=True) image = models.ImageField(default='default.jpg', upload_to='picsinposts') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title {% … -
using QuerySet to fetch data
I am trying to create a rest api which gives the weather data for a particular city and n days. I've created a model which specifies all the required fields. I've populated the database using management commands. I've tried using Q method to query the database. but I am making error somewhere and I am unable to identify it. #views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import weatherdata from .serializers import weatherdataserializer from django.http import Http404 from django.db.models import Q # Create your views here. class weatherList(APIView): def get(self, request): weather = weatherdata.objects.all() serializer = weatherdataserializer(weather, many=True) return Response(serializer.data) def post(self, request): serializer = weatherdataserializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class weatherDetail(APIView): def get_queryset(self,*args , **kwargs): queryset_list = weatherdata.objects.all() query = self.request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(city_name__icontains = query) | Q(city_id__icontains = query) ).distinct() return queryset_list #serialisers.py from rest_framework import serializers from .models import weatherdata class weatherdataserializer(serializers.ModelSerializer): class Meta: model = weatherdata # fields = '__all__' fields = ( 'city_name', 'city_id', 'latitude', 'longitude', 'dt_txt', 'temp', 'temp_min', 'temp_max', 'pressure', 'sea_level', 'grnd_level', 'humidity', 'main', 'description', 'clouds', 'wind_speed', 'wind_degree', ) #models.py from … -
How to send zip file as an attachments to an email Django
I wanted to send a zip file as an attachment. email_object = EmailMessage(subject='subject', from_email="email", to=["to_email"]) email_object.attach_file('zipped_folder') email_object.send() -
Automatically setting image depending on the post category in Django
I need a code that will automatically set the photo assigned to the post depending on its category. Initially, I thought about changing the default attribute but I have no idea how to implement it. here is my model: class Post(models.Model): CATEGORY_CHOICES = ( ('Django', 'Django'), ('Python', 'Python'), ('C++', 'C++'), ('Graphics', 'Graphics'), ('Text Editor', 'TextEditor'), ('Spreadsheet', 'Spreadsheet'), ('DataBase', 'DataBase'), ('Web Design', 'WebDesign'), ) title = models.CharField(max_length=50, unique=True) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default_post_pic.jpg, upload_to='post_pics') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 200 or img.width > 200: output_size = (200, 200) img.thumbnail(output_size) img.save(self.image.path) -
AttributeError: module 'posts.views' has no attribute 'edit'
I am trying to import the views created from my views.py file to my urls.py file for my django project. After doing so, the terminal displays an attribute error. I am following a tutorial that says it works and I do not know what to do I've tried everything. I've also checked stack overflow messages. Nothing has helped. posts/views.py from django.shortcuts import render, redirect, get_object_or_404 from .forms import PostForm from .models import Post from django.views.generic import ListView, DetailView # Create your views here. class IndexView(ListView): template_name = 'posts/index.html' context_object_name = 'post_list' def get_queryset(self): return Post.objects.all() class PostDetailView(DetailView): model = Post template_name = 'posts/post-detail.html' def postview(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() return redirect('index') form = PostForm() return render(request, 'posts/post.html', {'form': form}) def edit(request, pk, template_name='posts/edit.html'): post = get_object_or_404(Post, pk=pk) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return redirect('index') return render(request, template_name, {'form': form}) def delete(request, pk, template_name='posts/confirm_delete,html'): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': post.delete() return redirect('index') return render(request, template_name, {'object': post}) posts/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.PostDetailView.as_view(), name='detail'), path('edit/<int:pk>/', views.edit, name='edit'), path('post/', views.postview, name='post'), path('delete/<int:pk>/', views.delete, name='delete'), ] The website is … -
How to send an unknown number of filter values to DRF with React? GET or POST?
I am building a filtering system where you can filter products by brand and category. The user selects the filters in a React Application and this triggers a request to the backend API (Django Rest Framework - DRF) that is either GET or Post. Ideally Django would receive the filter names as value it can iterate over. I am quite lost on how to achieve this. A GET request would be possible. But in order for DRF to work with the request it needs to have a uri-format as such: http://127.0.0.1:8000/filter/?categories=proviant&categories=multipower&brands=kellogs I could then use a view like this to grab the values. class ProductFilterListView(APIView): def get(self, request): for el in request.GET.getlist('categories'): print(el) return Response('') This is quite a challenge since axios (library for making JS requests) does not have an option to format the url according to the requirements of DRF. So this feels very wrong and very manual and is hardly a "good" solution (?) The other way would be to use a post request. But then again, I have never used a post request for something that does not have a serializer or a form on the Django side. So, I would not know how to validate … -
Design correct relations of modes in Django
Please help to correct design the next things. Need to have to teams list of stings which are connected to the list of companies. After this I want to use them to user model. I did it in next way : class CustomCompany(models.Model): company_name = models.CharField(max_length=30, default="None", unique=True ) class CustomTeam(models.Model): team_name = models.CharField(max_length=30) company_name = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, related_name='company_name+', to_field='id', ) class CustomUser(AbstractUser): def _get_self_company(self): return self.company phone = models.CharField(max_length=20, blank=True) company = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, default='None', to_field='company_name', related_name='company' ) team = models.ForeignKey(CustomTeam, on_delete=models.CASCADE, to_field='team_name', related_name='team_name+', limit_choices_to={"company_name__id":_get_self_company}, ) Not sure if it's correct, but the main issue in it, that I should specify unique team model, but it shouldn't be. users.CustomUser.team: (fields.E311) 'CustomTeam.team_name' must set unique=True because it is referenced by a foreign key. Help please to understand how to correct do this? -
Mobile Apps with Django BackEnd
Hello? I have an SMS based Django app. I want to create a Mobile app that syncs records to and fro from my Django app database. How can I go about this? Thanks in advance. -
Unknown element errors in VueJS+Django
I added Vue to my Django project using Webpacks. I'm now testing my Vue frontend with some default templates provided by Vue itself. Here is what i tried: App.vue <template> <v-app id="inspire"> <v-navigation-drawer fixed v-model="drawer" app > <v-list dense> <v-list-tile @click=""> <v-list-tile-action> <v-icon>home</v-icon> </v-list-tile-action> <v-list-tile-content> <v-list-tile-title>Home</v-list-tile-title> </v-list-tile-content> </v-list-tile> <v-list-tile @click=""> <v-list-tile-action> <v-icon>contact_mail</v-icon> </v-list-tile-action> <v-list-tile-content> <v-list-tile-title>Contact</v-list-tile-title> </v-list-tile-content> </v-list-tile> </v-list> </v-navigation-drawer> <v-toolbar color="indigo" dark fixed app> <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon> <v-toolbar-title>Application</v-toolbar-title> </v-toolbar> <v-content> <v-container fluid fill-height> <v-layout justify-center align-center > <v-tooltip right> <v-btn icon large :href="source" target="_blank" slot="activator"> <v-icon large>code</v-icon> </v-btn> <span>Source</span> </v-tooltip> </v-layout> </v-container> </v-content> <v-footer color="indigo" app> <span class="white--text">&copy; 2017</span> </v-footer> </v-app> </template> main.js import Vue from 'vue' import App from './App' import Vuetify from 'vuetify' Vue.use(Vuetify) Vue.config.productionTip = false export default new Vuetify({ }) /* eslint-disable no-new */ new Vue({ el: '#app', vuetify: new Vuetify(), drawer: false, template: '<App/>', components: { App } }) The problem is that, when opening my localhost, nothing is rendered and i get a lot of errors on my dev tools, such as: [Vue warn]: Property or method "drawer" is not defined on the instance but referenced during render. [Vue warn]: Property or method "source" is not defined on the instance but referenced during … -
Django: Filter for all actions related to the ForeignKey Object
I've got a Model called User which looks like this: class User(AbstractBaseUser, PermissionsMixin): ...some fields... club = models.ForeignKey('schedule.Club', on_delete=models.CASCADE, null=True, blank=True) And for my APP I'm creating History Items, which I want to let my users see if they're logged in. So far I only show History Items that are related to them: class HistoryItems(ListView): model = HistoryItem template_name = 'history/history_items_table.html' context_object_name = 'history_items' def get_context_data(self, **kwargs): history_item_query = HistoryItem.objects.filter(Q(changed_by=self.request.user) | Q(object_id=self.request.user.pk)).select_related('changed_by', 'content_type') return { 'filter_history_form': HistoryFilterForm(), 'history_items': history_items, } So if they get changed or change something themselves they can see that. But now I also want to show them all changes that were done to the Club that they have chosen. So for example if "User1" has "Club1" as ForeignKey, and I change the name of Club1 to Club2 I want the User1 to see that in the history items. My History Model looks like this: class HistoryItem(models.Model): changed_at = models.DateTimeField('Changed At', auto_now_add=True) description = models.TextField('Description', max_length=300) changed_by = models.ForeignKey('users.User', on_delete=models.SET_NULL, related_name="history_items", null=True) action = models.CharField('Action', max_length=50, choices=ACTION_CHOICES) difference = JSONField('Differences', encoder=DjangoJSONEncoder, null=True, blank=True) # Generic object foreign key object_id = models.IntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey('content_type', 'object_id') How would I have to "rebuild" my history_item_query … -
Django - How to list items by their common tags
I'm a django/python beginner working on a basic blog and attempting to list items by their tags. I'm able to add tags to posts from the admin panel, but haven't been able to figure out the proper code that will allow me to display posts by their particular tags. I have tried to implement many solutions found online, but I've just ended up listing every post, no posts, or gotten errors. Here is the relevant part of my models.py: ... class Tag(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') tags = models.ManyToManyField(Tag) updated_on = models.DateTimeField(auto_now=True) content = RichTextUploadingField(config_name="default", null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title views: ... class TagPage(generic.ListView): model = Tag template_name = 'tag_list.html' and urls: urlpatterns = [ ... path('tag/<slug>/', views.TagPage.as_view(), name='tag') ] If anyone has any ideas as to what code is necessary, it would be appreciated. -
Django - auth models in default database, other models replicated in several databases?
I am wondering whether it's possible in Django to run a multi-database project with following definition: All core models (User, Group, Session, Customer, etc.) in the database 'default'. All other models (Order, Invoice, etc.) in multiple databases, where each database belongs to single Customer. ------------ | default | ------------ | User | | Group | | Customer | ------------ / | \ ------------ ------------ ------------ | cust_A | | cust_B | | cust_C | ------------ ------------ ------------ | Order | | Order | | Order | | Invoice | | Invoice | | Invoice | ------------ ------------ ------------ I know I can specify a database for particular model, but that would not work in this case. I need models Order and Invoice to be created in databases cust_A, cust_B, cust_C, while models User, Group and Customer need to be created only in default database. Working with such setup should be possible by manually selecting a database for a QuerySet with .using('db_name'). Is it possible to create such DB structure for Django project? -
Python Django - crispy forms layout
I am trying to edit layout of my form via forms.py. But if I try to set it up nothing happens and the form layout keeps the default layout. Here is my models.py: class AssetReceived(models.Model): asset_user = models.ForeignKey(no_models.MyUser,on_delete=models.CASCADE, related_name='my_user_profile2') asset_received = models.ForeignKey(Asset, on_delete=models.CASCADE) asset_servicetag = models.CharField(blank=True, max_length=7) asset_date = models.DateField(default=datetime.date.today) asset_status = models.ForeignKey(AssetStatus, on_delete=models.CASCADE) asset_note = models.CharField(blank=True, max_length=250) asset_order_type = models.ForeignKey(AssetOrderType, on_delete=models.CASCADE) asset_order_refresh = models.ForeignKey(AssetStoreMaster, on_delete=models.CASCADE, blank=True, null=True, related_name='sc_refresh') asset_order_install = models.ForeignKey(AssetStoreMaster, on_delete=models.CASCADE, blank=True, null=True, related_name='sc_install') asset_order_deinstall = models.ForeignKey(AssetStoreMaster, on_delete=models.CASCADE, blank=True, null=True, related_name='sc_deinstall') here is my views.py: class ReceivedAssetCreate(generic.CreateView): template_name = 'received_asset/received-asset-new.html' form_class = ReceivedAssetForm def get_success_url(self): return reverse('received_asset:received-asset-new') def post(self, request): form = self.form_class(request.POST) if form.is_valid(): form.save(commit=True) messages.success(request, f'Received asset has been received successfully') return render(request, self.template_name, {"form": form}) here is my forms.py: class ReceivedAssetForm(forms.ModelForm): asset_user = forms.ModelChoiceField(queryset=no_models.MyUser.objects.all(), widget=autocomplete.ModelSelect2()) asset_servicetag = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Service Tag'})) asset_date = forms.DateInput asset_note = forms.CharField(required=False) asset_order_type = forms.ModelChoiceField(queryset=AssetOrderType.objects.all()) asset_order_refresh = forms.ModelChoiceField(queryset=AssetStoreMaster.objects.all(), required=False) asset_order_install = forms.ModelChoiceField(queryset=AssetStoreMaster.objects.all(), required=False) asset_order_deinstall = forms.ModelChoiceField(queryset=AssetStoreMaster.objects.all(), required=False) asset_received = forms.ModelChoiceField(queryset=Asset.objects.all(), widget=autocomplete.ModelSelect2()) asset_status = forms.ModelChoiceField(queryset=AssetStatus.objects.all(),widget=autocomplete.ModelSelect2()) class Meta: model = AssetReceived fields = ['asset_user', 'asset_received', 'asset_servicetag', 'asset_date', 'asset_status', 'asset_note', 'asset_order_type', 'asset_order_refresh', 'asset_order_install', 'asset_order_deinstall'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'asset_user', Row( Column('asset_received', css_class='form-group col-md-6 mb-0'), Column('asset_servicetag', … -
How to implement multiple user types with different roles and permissions in Django?
I'm new to web development using Django Framework and Python programming language and I am tasked to make a mini project that implements the following: Permissions Management; Roles Management; Users Accounts Management; Login and Logout; and Password Reset. What are the appropriate steps for me to accomplish this? I have read about user authentication and permissions and custom user models but the examples that were given were less complicated than what I actually needed. I have to set up an application that implements multiple user accounts wherein each user can have multiple roles and each roles have different permissions. I know that Django has built-in functions to do this but I want to make my own customization as mush as possible. I would like to know if creating Custom User Model extending AbstractBaseUser is the best option there is to accomplish this. Also, I would like to know how to customize the Django built-in admin page, such as replacing or deleting unnecessary fields.