Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reordering Initial Migration calculations
Every time I try to migrate my initial migration, right after makemigrations, I get errors like : django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'Project.Class'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) The reason I think this happens is because the order of model operations in the 0001_initial.py migration is incorrect. Operations with classes which inherit from others are added before their parents'. After I reorder the operations, it works: Process finished with exit code 0. Cool! But how do I make makemigrations work without doing this every time? Thanks! ps. I tried reordering the import order of my models in the model's __init__.py but it didn't work. -
I'm using django-extra-views to have 2 forms on 1 page. How should I handle custom logic in form_valid?
Here is my views.py code class AttackItemInline(InlineFormSetFactory): model = AttackItem fields = ['attack_used','attack_image'] factory_kwargs = {'extra': 1} class AttackImageCreateView(CreateWithInlinesView): model = AttackImage inlines = [AttackItemInline] template_name = 'engine/attack_image_create.html' fields = ['title','image','source_url'] def form_valid(self, form): f = form.save(commit=False) f.creator = self.request.user f.hidden_data_found = attacks.spa(f.image) f.save() class AttackItemCreateView(CreateView): model = AttackItem template_name = 'engine/attack_item_create.html' def form_valid(self, form): f = form.save(commit=False) f.creator = self.request.user f.save() As you can see I have 2 forms and only 1 form valid. I don't know how to deal with that. Here is my frontend code: {% extends 'base.html' %} {% block content %} <div class="col-md-4 col-md-offset-4 downdown whitebox"> <form method="post" action="{% url 'attack_image_create' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form }} {% for formset in inlines %} {{ formset }} {% endfor %} <input type="submit" value="Submit" /> </form> </div> {% endblock %} How should I be handling custom logic? Like saving the f.creator, saving finding and saving f.hidden_data_found, etc. Link to package: https://github.com/AndrewIngram/django-extra-views -
Django Template: Iterate over a Dictionary of Lists of Dictionaries
I'm having a rough time wrapping my mind around iterating through a context_dict in django. It's a complicated dictionary that I don't have much control over. context_dict = { 'circuitIds_found': # First property (not dynamic) { 'output_123.csv': # csv file where search results were found (dynamic) [ { 'PATH_NAME': '80.L1XX.802084..ABC', 'SERVICE_CATEGORY': 'ETHERNET', 'UNIQUE_FLOW_ID': '80.L1XX.802084..ABC', }, { 'PATH_NAME': '80.L1XX.806000..ABC', 'SERVICE_CATEGORY': 'ETHERNET', 'UNIQUE_FLOW_ID': '80.L1XX.806000..ABC', } ], 'output_456.csv': # another csv file where search results were found (dynamic) [ { 'PATH_NAME': '80.L1XX.123456..ABC', 'SERVICE_CATEGORY': 'ETHERNET', 'UNIQUE_FLOW_ID': '80.L1XX.123456..ABC', } ], 'circuitIds_not_found': [] . # Second property (not dynamic) } I render in views.py: ... return render(request, 'mainApp/index.html', context=context_dict) And then attempt to do nested template for loops: {% for key, value_list in search_results_match.items %} {{ key.unique_flow_id }} <ul> {% for key, value in value_list.items %} <li>{{ key }} : {{ value }}</li> {% endfor %} </ul> {% endfor %} The end goal is to have a rendered list as follows, but the above templating, and everything else I've tried is just not working out..... 80.L1XX.802084..ABC PATH_NAME: 80.L1XX.802084..ABC SERVICE_CATEGORY: ETHERNET 80.L1XX.806000..ABC PATH_NAME: 80.L1XX.806000..ABC SERVICE_CATEGORY: ETHERNET 80.L1XX.123456..ABC PATH_NAME: 80.L1XX.123456..ABC SERVICE_CATEGORY: ETHERNET -
Django Model Form Require Boolean Field To Be Checked True To Submit Form
I would like a boolean field to be required to true in order for the form to be submitted and to throw an error to agree to the terms. Best way to do this? -
Alternative for Elaphe library after upgrading to python 3?
trying to update to python 3+ on my django project but in order to produce some barcodes we are currently using Elaphe (https://pypi.org/project/elaphe/). We use it to produce both QRcodes and Barcodes. I was wondering what everyone else is using that is Django 1.8 compatible and Python 3+ -
Rendering a view on multiple template
So i am trying to render a function on multiple page. This function is rendering the total of task an user has still undone. my views.py context = { "lists": lists, "reccurence": reccurence, "thedate": thedate, "searchform": searchform, "list_count": list_count, "task_count": task_count, } return render(request, "todo/list_lists.html", context) So I thought, maybe I could add more page so it will also render my model on list_detail etc., but it does not work, only working on list_lists.html -
Django Custom Field Validation
I have a validation function in my forms.py that needs to meet the following conditions.Here is my code. The def clean_time frame has to check the following in the database: 1. Timeframe 2. Student 3. Date So if i pick timeframe 9 am for student john smith. You cant logg the same time frame for the student on the same day. How do i make that happen ? Thanks forms.py class K8Points_ClassroomForm(forms.ModelForm): class Meta: model = K8Points fields = ('student_name', 'behavior','academic', 'time_frame','date','day','week_of','class_name') def clean_time_frame(self): time_frame = self.cleaned_data.get('time_frame') date = self.cleaned_data.get('date') student_name = self.cleaned_data.get('student_name') if (time_frame == ""): raise forms.ValidationError('Field can not be left blank !') for instance in K8Points.objects.all(): if instance.time_frame == time_frame: raise forms.ValidationError('This timeframe was already logged !' + time_frame) return time_frame -
Django - Filter by non-existing foreign key
My two models look like this: class Sentence(models.Model): language = models.ForeignKey('Language') class TranslatedSentence(models.Model): sentence = models.ForeignKey(Sentence, related_name='translated_to') language_to = models.ForeignKey('Language') I can filter by sentences that have been translated to a specific language: Sentence.objects.filter(translated_to__language_to__name='Spanish') My question is: How can I filter all sentences that have not been translated to a given language? -
Django Admin custom form - Foreign key field as searchable instead on dropdown
class modelA(Base): account = models.ForeignKey… user = models.ForeignKey… class modelB(Base): user = models.ForeignKey… amount = models….. class modelC(Base): modelA = models.ForeignKey(modelA) modelB = models.ForeignKey(modelC) class formA(forms.ModelForm): account = forms.ModelChoiceField(queryset=Account.objects.all()) user = forms.ModelChoiceField(queryset=User.objects.all()) amount = CustomField….. def save() … class formAAdmin(admin.ModelAdmin): form = formA raw_id_fields = (‘account’) // Cannot use account as it does not belong to modelC. Account is shown as a dropdown but I want it as a popup where we can search. I am getting this error when I added account in raw_id_fields. : (admin:E002) the value of ‘raw_id_fields[0]’ referes to account which is not an attribute of ‘modelC’ . Since account is not part of the modelC, it just displayes it as a dropdown. How can I make it show search for account? -
Simpe upload image button in django
I am new in Django, so do not be mad, i just do not know how to add a button which will upload a file to the specific post in my model. So the problem is how to get the identifier of each post from my model without go to specific url, only in page with all posts My model: class Post(models.Model): title = models.CharField(max_length=20, db_index=True) slug = models.SlugField(max_length=50, unique=True) project_image = models.ImageField(upload_to='images/', blank=True) technologists = models.ManyToManyField('ImageTag', blank=True, related_name='tags') description = models.CharField(max_length=200, blank=True) programme_language = models.CharField(max_length=40, blank=True) update_time = models.CharField(max_length=40, blank=True) link = models.URLField() def __str__(self): return self.title def get_absolute_url(self): """Gettign the absolute url of index.html""" return reverse('project_detail_url', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('project_edit_url', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('project_delete_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): """Complement the method save of django Model""" # if not self.id: # self.slug = gen_slug(self.title) if not self.slug: self.slug = gen_slug(self.title) if self.slug: checker = self.slug.strip() if checker: pass else: self.slug = gen_slug(self.title) super().save(*args, **kwargs) my main html pattern which extend base html pattern and which contain each post detail from my model: {% extends 'base.html' %} {% block content %} {% for post in posts %} <div class="post-wrap"> <div class="title_and_image"> <h2>{{ post.title }}</h2> … -
Django ModelSelect2MultipleWidget FormView won't display initial data
I am using django_select2.forms.ModelSelect2MultipleWidget, forms.Form, FormView. I have 3 tables: Job, HelpText, JobHelpText. From a Job detail page, I want to direct to the Form view (autocomplete multiple select widget), and for that input to have the initial data of all other Jobs associated with that Help Text. What is working: I can autocomplete search for jobs. It only gives access to jobs without help text (like desired). Python print statement is even showing the correct initial data. What won't work: The initial data won't pre-fill in the input box. class Foo(models.Model): job_name = models.CharField(max_length=200, blank=False, null=False) env = models.CharField(max_length=200, blank=False, null=False) ... def __str__(self): return self.job_name class HelpText(models.Model): name = models.CharField(unique=True, max_length=255) ... def __str__(self): return self.name class FooHelpText(models.Model): foo = models.OneToOneField(Autosys, on_delete=models.CASCADE,) help_text = models.ForeignKey(HelpText, on_delete=models.DO_NOTHING, ) ... def __str__(self): return str(self.foo) class ManageFooJobs(AdminCapableJSMixin, django_select2.forms.ModelSelect2MultipleWidget): """ only show foo jobs that have no help text """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = models.Foo.objects.filter(foohelptext__isnull=True) search_fields = [ 'job_name__icontains', ] class ManageJobsForm(forms.Form): """ add or remove jobs """ foo_jobs = forms.MultipleChoiceField( widget=widgets.ManageFooJobs(), required=False, ) class ManageJobsView(LoginRequiredMixin, BootstrapFormMixin, FormView): """ able to add and remove jobs from a help text """ form_class = forms.ManageJobsForm def get_initial(self, *args, **kwargs): initial … -
Add vue js to existing web app (written in django) using docker
I have an existing web app that is written in Django. The app is currently in a Docker container. I have also integrated django REST framework Problem: I am a new developer, therefore I do not know how to add vue js to my existing web app. Attempted solutions: I have spent a few days searching online and although I found a number of tutorials online, none of them solved my specific problem. My tutor told me that I need to add a container that uses vue to my existing situation...that is going to require moving the docker-compose fly and make some changes to the paths in it –– which sounds pretty straight forward, but after attempting to make the addition and changes, this task has turned out to be not so simple. Not asking for someone to give me a step by step answer, rather I would appreciate any tips, suggestions that will help me get going in the right direction to solve my problem. -
Access dynamically created model django
I was working on a Django app which requires creating tables dynamically. def dcreatedb(request): attrs = { 'name': models.CharField(max_length=20), '__module__': 'data.models' } model = type('books', (models.Model,), attrs) with connection.schema_editor() as schema_editor: schema_editor.create_model(model) return HttpResponse('done') The above dcreatedb view creates a model dynamically. But I need to access the same model in some other view but the view is not in the models.py file in the app and created dynamically by the dcreatedb view. def dinsertdb(request): # access the book model and do some work return HttpResponse('work done') for instance let us suppose a model named books is created by the dcreatedb view dynamically, and now I want to access the same model in the dinsertdb view.(Both the dcreatedb model and the dinsertdb models are in the same views.py file under the same app.) How can this be done? Thanks -
Unable to loop through an object in JavaScript
I’m a bit lacking of knowledge in JS. I am accessing some data through an API and retrieving it as JSON. This data is getting into JS very nicely. But I do not really understand with which type object I’m dealing with. I cannot determine the length and also the other loop methods do not work. But I can access the object elements like an array with REValues[0] – first element. '''function drawTable() { debugger; var REValues = {{ json|safe }}; var data = new google.visualization.DataTable(); data.addColumn('number', 'ID'); data.addColumn('string', 'Stadt'); data.addColumn('string', 'Bezirk'); data.addColumn('number', 'Einkaufswert'); data.addColumn('number', 'Fläche'); data.addColumn('number', 'Miete'); for (var REValue in REValues) { debugger; }''' enter image description here -
Django PermissionDenied empty page in production
I have a Django app that is not displaying permission denied exceptions correctly. The project has a custom 403.html template that displays perfectly fine locally and used to work on production but at some point stopped working and I am having a heck of a time tracking down why. The app is served using Apache and Nginx. 403.html extends base.html and should show the normal site styling, menus, etc with the passed in exception message displayed. On production though, every single PermissionDenied raised shows a blank white page stating: "You don't have permission to access /some/path on this server." The Nginx access log shows a single 403 request to the route in question and nothing in the error log. The Apache access log also shows a 403 GET request to the given route. The error log shows the expected PermissionDenied exception. As part of debugging I have tried changing the default permission_denied view that comes included in django. If I change the view to return HttpResponse('test'), the permission denied response still shows a white page, but it does show the given text, 'test'. But if I try the following instead: log.info('a') resp = render(request, '403.html', context={'exception': str(exception)} log.info('b') return HttpResponse(resp) … -
I am getting an error when I am updating the post. It displays in the comment section but not update the post
I am new in Django. I am making Simple Blog site. But I am getting an error when I am updating the post. It displays in the comment section but not update the post. Here is the Code in; View.py from django.db.models import Count, Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render, get_object_or_404, redirect, reverse from .forms import CommentForm, PostForm from .models import Post, Author from marketing.models import Signup def get_author(user): qs = Author.objects.filter(user=user) if qs.exists(): return qs[0] return None def search(request): queryset = Post.objects.all() quary = request.GET.get('q') if quary: queryset = queryset.filter( Q(title__icontains=quary) | Q(overview__icontains=quary) ).distinct() context = { 'queryset' : queryset } return render(request, 'search_results.html', context) def get_category_count(): queryset = Post \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset def index(request): featured = Post.objects.filter(featured=True) latest = Post.objects.order_by('-timestamp')[0:3] if request.method == 'POST': email = request.POST['email'] new_signup = Signup() new_signup.email = email new_signup.save() context = { 'object_list': featured, 'latest': latest } return render(request, 'index.html', context) def blog(request): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:5] post_list = Post.objects.all() paginator = Paginator(post_list, 4) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context = { 'queryset' : paginated_queryset, 'most_recent' … -
Django - 'NoneType' object has no attribute 'threads'
Hello guys so I am trying to add a category system for posts by following a tutorial on this website https://djangopy.org/how-to/how-to-implement-categories-in-django/ (I changed my code up a little) I get this error 'NoneType' object has no attribute 'threads' every time I try and go to the category page to view the posts inside that category. models.py: from django.db import models from django.urls import reverse from django.utils.text import slugify class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): value = self.name self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Thread(models.Model): ... category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE, related_name='threads') ... def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] ... views.py: from django.shortcuts import render, HttpResponseRedirect from django.contrib import messages from .models import Category, Thread from .forms import SubmitScamNumber def show_category_view(request, hierarchy=None): category_slug = hierarchy.split('/') category_queryset = list(Category.objects.all()) all_slugs = [ x.slug for … -
Django multiple models , multiple fields lookup in autofield coloumn
I have two models BOQ and DPR boq model choicestype=(('start','start'),('finish','finish')) class boqmodel(models.Model): code = models.IntegerField() building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) duration = models.IntegerField() linkactivity = models.CharField(max_length=300,null=True,blank=True) linktype = models.CharField(choices=choicestype,max_length=300,null=True,blank=True) linkduration = models.IntegerField(default=0) plannedstart = models.DateField(null=True,blank=True) plannedfinish = models.DateField(null=True,blank=True) actualstart = models.DateField(null=True,blank=True) actualfinish = models.DateField(null=True,blank=True) DPR class dprmodel(models.Model): Date=models.DateField() Contractor=models.CharField(max_length=300) Building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) Level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) Activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) Subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) Status=models.CharField(choices=choicestype,max_length=300) Labor=models.IntegerField() Both the models have Building,Level,Activity,Sub Activity as common fields. My entry in BOQ code=1 building=A-1 Level=L-1 Activity=Activity-1 Subactivity-Subactivity-1 duration=2 linkactivity=null linktype=null linkduration=null planned start=01-01-2019(as linkactivity=null) plannedfinish=03-01-2019(planned start+duration) MY DPR Entry Date :10-1-2019 contractor :A building=A-1 Level=L-1 Activity=Activity-A Subactivity=Subactivity-A Status =Start Labor=2 I need to populate the Actual start date in boqmodel such that if boqmodel.building = dprmodel.building and boqmodel.level = dprmodel.level and boqmodel.activity = dprmodel.activity and boqmodel.subactivity = dprmodel.subactivity and dpr.status=start. If the above condition exists then boq.actualstart=dpr.date I am thinking of creating a new field in two models by joining the building,level,activity and subactivity .Then i can join two models using the newly created fields. Any help would be appreciated. -
Django Insert Data Into Fields QuerySet
I have two views, K8Points & K8PointsClassroom. K8Points you select your classroom, hit submit and it runs the query on another view called K8PointsClassroom. My Issue: The for loop runs and populates my student names on the html page, however when you click on the level up button under the student name, you get a pop up box. Screen shots attached. What i want is the fields to automatically be populated with the correct data. Class room and Student Name inside the popup window. How do i do that ? Can i do it off the for loop ? Thanks HTML {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy K8Points_ClassroomForm %} {% load static %} {% block content %} <br> <h2>{% load static %} <img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> My Classroom</h2> <br> <br> <form action="/points/k8_points_classroom" method="POST"> {% csrf_token %} <!-- Start Date --> <div class="container"> <div class="container"> <div class='row'> <div class="col-4"> <p> Recording Data as User : {{user.username}} </p> <p><b> Classroom : {{class_name}} </b></p> </div> </div> <div class='row'> <div class = "col-2"> {{form.date|as_crispy_field }} </div> <div class = "col-2"> {{form.week_of|as_crispy_field }} </div> <div class = "col-2"> {{form.day|as_crispy_field }} </div> </div> </div> </form> <div class="jumbotron" align="middle"> … -
Filtering Django Simple-History by created/creator
I've created a simple Django data model that is using Django Simple-History for auditing: from django.db import models from simple_history.models import HistoricalRecords class AuditedModel(models.Model): history = HistoricalRecords(inherit=True) In the interest of DRY, I'm trying to leverage Simple-History's history_date & history_user attributes in place of adding created_at and created_by attributes. I've added a couple of properties to simplify accessing the history for these attributes as follows: @property def created_date(self): return self.history.earliest().history_date @property def created_by(self): return self.history.earliest().history_user This works fine when I'm working with an instance. Now, I'm running into issues when I try to filter querysets by history_date or history_user. For example, I can filter for objects created in the last 24hrs by doing this: queryset = AuditedModel.objects.all() queryset.filter( uuid__in=AuditedModel.history.annotate( created_date=Min('history_date'), ).filter( created_date__gte=timezone.now() - relativedelta(days=1) ).values_list( 'uuid', flat=True ) ) But, I'm unable to figure out how to filter the AuditedModel by more than one attribute. Ultimately, I'd like to get a queryset with new instances that were created by a specific user. Something like: queryset.filter( uuid__in=AuditedModel.history.annotate( created_date=Min('history_date'), ).filter( created_date__gte=timezone.now() - relativedelta(days=1) ).values_list( 'uuid', flat=True ), history__history_user=request.user ) This doesn't work as history can't be resolved, but it illustrates (I hope) what I'm trying to get at. Has anyone out there … -
Django prefetch_related but table not directly related
I have the following models set up. I'd like to get a queryset of Category objects and prefetch OrderLine objects but the problem is that they're not directly related but matched up through product__category. I'm thinking Subquery might work? class Category(models.Model): name = models.CharField(...) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', ...) name = models.CharField(...) price = models.DecimalField(...) class OrderLine(models.Model): product = models.ForeignKey(Product, related_name='orderlines', ...) I've tried the following but for each Category it will prefetch Product objects and for each Product it will prefetch OrderLine objects. from django.db.models import Prefetch categories = ( Category.objects.prefetch_related(Prefetch( 'products__orderlines', queryset=OrderLine.objects.filter(...) )) ) I've also tried with 'orderlines' but as expected get an error: AttributeError: Cannot find 'orderlines' on Category object, 'orderlines' is an invalid parameter to prefetch_related() -
Annotate queryset with percentage grouped by date
Suppose I have the following model: class Order(models.Model): category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, default=DEFAULT_CHOICE) created_at = models.DateTimeField(auto_now_add=True) I need to annotate an Order queryset with the percentage of each category grouped by month (based on the created_at field). I managed to write a query to count every Order grouped by month: orders_per_month = (Order.objects .annotate(month=TruncMonth('created_at')) .values('month') .annotate(count=Count('id')) .order_by('month') .values('month', 'count') ) Changing just the last .values() to .values('month', 'category', 'count'), I can get the count grouped by both category and month. Is it possible to get the percentage of each category grouped by month using Django's ORM? For example, if I had the following data: MONTH | CATEGORY Jan | 'A' Jan | 'B' Feb | 'A' I would like to get something similar to this: [ (Jan, 'A', 0.5), (Jan, 'B', 0.5), (Feb, 'A', 1), ] Thanks in advance. -
Error while embedding Amazon QuickSight dashboards with Django
I am trying to embed QuickSight dashboards into my django application. I followed all of the steps regarding embedding detailed in the following documentation: https://docs.aws.amazon.com/en_us/quicksight/latest/user/embedded-dashboards-setup.html Using the AWS CLI, I am able to assume an IAM role I created, register a user into my QS account, and get the dashboard embed url, and view the dashboard in a web browser. However, when trying to mimic the same behavior inside the application using the Python SDK, it yields the following: "We can't display this page (Not authorized)." We have whitelisted our domain within Quicksight, and tested it on 2 different servers. The user who is logged into the django app and is trying to view the dashboard already is in the QS account with the necessary permissions to view the dashboard. But still getting "We can't display this page (Not authorized)." Use of the Python SDK is below: def viewDashboard(request): import boto3 sts = boto3.client('sts') assumed_role_object = sts.assume_role( RoleArn="arn:aws:iam::********4324:role/QuickSightEmbed", RoleSessionName=email ) # From the response that contains the assumed role, get the temporary # credentials that can be used to make subsequent API calls credentials = assumed_role_object['Credentials'] # Use the temporary credentials that AssumeRole returns to make a # connection to … -
Django TestCase for group permissions?
I have a TestCase for some views, but I am also trying to incorporate tests for my post admin group. They have permissions to post.change_post and post.delete_post. Here is a little code snippet, from django.test import TestCase, Client from django.urls import reverse from fixtureless.factory import create from .models import Post class TestPostViews(TestCase): def setUp(self): super().setUp() self.user = get_user_model().objects.create(username='test_user') self.form = create(Post, {'title': 'test_title'}) self.client = Client() def test_update_post(self): """ Test UpdateView updates users post """ self.client.force_login(user=self.user) response = self.client.put(reverse('post:update', kwargs={'pk': self.form.pk}), {'title': 'testing'}) self.assertEqual(response.status_code, 200) # reloads a models value from the database self.form.refresh_from_db() self.assertEqual(self.form.title, 'test_title') def test_delete_confirm_page(self): """ Test DeleteView takes user to confirmation page """ self.client.force_login(user=self.user) response = self.client.get(reverse('post:delete', kwargs={'pk': self.form.pk})) self.assertContains(response, 'delete') def test_delete_post(self): """ Test DeleteView deletes a post """ self.client.force_login(user=self.user) response = self.client.post(reverse('post:delete', kwargs={'pk': self.form.pk})) self.assertRedirects(response, reverse('post:list')) self.assertFalse(Post.objects.filter(pk=self.form.pk).exists()) Any tips on this? Should I create a separate TestCase, or is there a way to add this in the initial setUp() method? -
Django class based views and taggit
# models for post class Post(models.Model): STATUS_CHOICE = [ ('draft', "Draft"), ('published', "Published") ] title = models.CharField(max_length=250) slug = models.SlugField(max_length=300, unique_for_date="publish") author = models.ForeignKey(User, related_name="blog_posts", on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICE, default="draft") class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.publish.strftime('%Y'), self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) # For Tagging Features tags = TaggableManager(blank=True) # Class Based views for the Post Create and adding tags for the Post dynamically # This is the Class Based View for Adding the Post and class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'body', 'status', 'tags'] def form_valid(self, form): form.instance.author = self.request.user form.instance.slug = slugify(form.instance.title) return super().form_valid(form) def AfterPostPosting(sender, instance, created, **kwargs): if created: if instance.tags.all().count()<=0: instance.tags.add(""+slugify(instance.slug)) instance.save_m2m() vars(instance) print(instance.tags.all().count()) print(instance.tags.all()) print(instance.slug) print(vars(instance)) post_save.connect(AfterPostPosting, sender=Post) ''' Blockquote Question : I added the tags by the slug field if user has not added the tags and I am adding the tags using Django's post_save signal but it is adding the tags to the 'Tag' model but not into the 'Post' model. But when i used the statement as "post_object.tags.all().count()" after adding the tags using post_save signal then it is showing me …