Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SyntaxError: positional argument follows keyword argument in multiple filter elements query
Keep getting below error. File "/app/community/views.py", line 643 app_1 | (Q(roster_id=rid) | Q(roster__parent_id=rid)), app_1 | ^ app_1 | SyntaxError: positional argument follows keyword argument In this line of code inside a view (views.py). CommunityRosterMembers.objects.filter( community_id=cid, (Q(roster_id=rid) | Q(roster__parent_id=rid)), (Q(rsvp_vote=1) | Q(rsvp_vote=2)) ) The model I am using is: class CommunityRosterMembers(models.Model): community = models.ForeignKey('Community', blank=False, null=False, related_name='community_roster_member_ref_set', on_delete=models.CASCADE) roster = models.ForeignKey('roster.Roster', blank=False, null=False, related_name='roster_community_member_ref_set', on_delete=models.CASCADE) flag = models.ForeignKey('CommunityRosterFlags', blank=False, null=False, related_name='community_roster_flag_ref_set', on_delete=models.CASCADE) member = models.ForeignKey('members.MemberInfo', blank=False, null=False, related_name='community_member_roster_ref_set1', on_delete=models.CASCADE) request_by = models.ForeignKey('members.MemberInfo', blank=True, null=True, related_name='community_requester_roster_ref_set', on_delete=models.CASCADE) date_rsvp_requested = models.DateField(default=timezone.now()) date_rsvp_response = models.DateField(default=timezone.now()) rsvp_vote = models.IntegerField(default=0,blank=False)#0 - Pending, 1 - Accepted, 2 - Maybe, 3 - Declined attendance = models.IntegerField(default=0,blank=False)#0 - Pending, 1 - Attended, 2 - Absent, 3 - Missed def __str__(self): return self.roster.title -
Error generation due to settings.py in django
-Created a project in django with 'CustomUser' model derived from 'AbstractUser' in an app 'users' -Below is the settings file snippet. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'crispy_forms', 'users', I get following error while running python manage.py makemigrations command with unsuccessful migration. ValueError: The field authtoken.Token.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. After much trial and error, I have removed 'rest_framework.authtoken' from the Installed app and the migration error disappeared and my site become functional. Problem is I want to user rest_framework and token based authorisation but if I keep 'rest_framework.authtoken' in settings, migration is not taking place. Please help -
Django's view of its models is inconsistent with the actual database
We have a system consisting of a Django server connected to a PostgreSQL database, and some AWS Lambda functions which need to access the database. When an admin saves a model (PremiumUser - contains premium plan information that needs to be read by the Lambdas), we want to set up a schedule of CloudWatch events based on the saved information. Those events then trigger other Lambdas which also need to directly access the database, as the database state may change at any time and they should work off the most recent state of the database. The issue is that Django seems to think it has saved the values, but when the Lambdas read the database the expected values aren't there. We have tried using Django's post_save signal, calling the Lambdas inside the triggered function; we have tried overriding Django's default PremiumUser.save method to perform super(PremiumUser, self).save(*args, **kwargs), and only then call Lambdas (in case the post_save signal was getting triggered too early); and we have tried overriding the PremiumUser.save method and calling super(PremiumUser, self).save(*args, **kwargs) in the context of an atomic transaction (ie with transactions.atomic():). When we call the Lambdas a few seconds after the admin dashboard has updated, they … -
Bootstrap Modal Not Working on Paginated Datatable Django
I have a datatable where for each row there is a button which launches a bootstrap modal window to edit the record. I thought everything was working well, until I noticed that it only works for the first ten (initially visible) records. Beyond that the button doesn't do anything, but I'm not sure why. Could someone please help me clear this up? JS controlling this all the way at the bottom. index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> <th></th> <th style="width:3%;">Reference</th> <th style="width:7%;">Ultimate Consignee</th> <th style="width:5%;">Vessel</th> <th style="width:7%;">Booking #</th> <th style="width:5%;">POL</th> <th style="width:15%;">DOL</th> <th style="width:5%;">POE</th> <th style="width:5%;">Pickup #</th> <th style="width:5%;">Sales Contact</th> <th style="width:5%;">Trucking Co</th> <th style="width:2%;">Total Cases</th> <th style="width:2%;">Total FOB</th> <th style="width:5%;">Freight Forwarder</th> <th style="width:5%;">Proforma</th> </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> </button> </td> <td>{{ order.reference }}</td> <td>{{ order.ultimate_consignee }}</td> <td>{{ order.vessel }}</td> <td>{{ order.booking_no }}</td> <td>{{ order.POL }}</td> <td>{{ order.DOL }}</td> <td>{{ order.POE }}</td> <td>{{ order.pickup_no }}</td> <td>{{ order.sales_contact }}</td> <td>{{ order.trucking_co }}</td> <td>{{ order.total_cases }}</td> <td>{{ order.total_fob }}</td> <td>{{ order.freight_forwarder }}</td> <td> {% if … -
Django Models Processing information using Business Logic
I have been trying to create a basic finance application using Django Frameworks that allows a user to input basic information such as their state, marriage status, etc in order to process the information with my django model, and spit out the processed answers such as the State Tax Rate, Federal Tax Rate, etc. I have had no problem getting the information from the user using my templates, views, forms, and models, but I have been running into trouble when trying to process the information. I have done my research and it seems that the best place to use "business logic" is in the models. However, I just can't seem to process my users information in order to have my model return an updated State tax rate value from my StateTax method in my models.py file. Here is my code below: Models.py: class Financer(models.Model): STATE_CHOICES=( ('AL','Alabama'), ('CA','California'), ('VA','Virginia') State=models.CharField(max_length=10,choices=STATE_CHOICES) StateTaxRate=models.IntegerField(default=0) def StateTax(self): if self.State in no_tax_states: self.StateTaxRate=3 self.save() elif self.State in variable_tax_states: self.StateTaxRate=2 self.save() elif self.State in flat_tax_states: self.StateTaxRate=1 self.save() def __str__(self): return self.State (This is a barebones version of my model in which I am trying to send the State information to my StateTax method in order to process … -
How can I create a view of database models in ascending order?
I have a model which looks like: from django.db import models from django.db.models import Avg # Create your models here. class Course(models.Model): name = models.CharField(max_length=254, default='') description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='images') def average_rating(self): return self.review_set.aggregate(Avg('rating'))['rating__avg'] def __str__(self): return self.name And I would like to create a view that would present each entry in ascending/decending order of it's average rating. I already have other views that do work like: def price_ascend(request): courses=Course.objects.order_by('price') return render(request, "courses.html", {"courses": courses}) However when trying a similar approach with the average rating: def rating_ascend(request): courses=Course.objects.order_by('average_rating') return render(request, "courses.html", {"courses": courses}) I run into this error: Cannot resolve keyword 'average_rating' into field. Choices are: description, id, image, name, orderlineitem, price, review Why doesn't this work? In my HTML I have: {% for course in courses|dictsortreversed:"average_rating" %} {{ course.average_rating | floatformat }} {% endfor %} This works and shows the average rating of each course. This is code where the Review class is defined from django.db import models from courses.models import Course # Create your models here. class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) course = models.ForeignKey(Course) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) … -
Is there a library that allows for auto populating the rows with class instances?
I'm working on a homework question and I have created different instances of how a pizza can be priced based on the size and the type. The issue I'm running into is that while the table view is useful, it isn't what I wanted and I read you can customize it way more in views.py but I don't see anything that can populate a table in a way where it can filter duplicates as in I have 2 cheese pizzas, one is in the large size and one small with their own pricing. Since it doesn't know anything about the headers. If I did use the listdisplay it will still show duplicates. Question I have is that do I have to manually change the logic flow in the HTML file itself? As in if field_name == the same while checking if the content of the td is the same, don't fill, and fill price if the td is empty. Does that mean I have to use some JS code? This just seems like such a common table issue that I think I must be missing something here (someone must have built a library to go specify your headers and row … -
Using wagtailmenus I want to regroup the main menu and seperate out items that have children vs items that don't have children
I'm build a custom main menu for wagtailmenus. When I get all the items, I want to presort the list of items into two groups. Items with children and items without children. I was thinking of using Django's regroup but I'm a little lost as to how to think about this. Here's what I'm thinking right now: {% regroup menu_items by has_children_in_menu as items %} {% if items %} <ul> {% for it in items %} <li>{{ has_children_in_menu.grouper }} # this would be the name of the parent <ul> {% for imenu in has_children_in_menu.list %} <li>{{ imenu.title }}</li> # the child {% endfor %} </ul> </li> {% endfor %} </ul> {% else %} <ul> {% for parent_item in menu_items %} <li>{{ parent_item.title }}</li> {% endfor %} </ul> {% endif %} Does this make sense? Am I crazy? Maybe I'm thinking about this wrong. What suggestions do you have? -
Ajax form submit and errors to appear in template in JSON format (django)
I have a django site: js $("#contactForm").submit(function(event){ event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); //get form action url var form_data = $(this).serialize(); //Encode form elements for submission $.getJSON( post_url , form_data,function( response ) { //iterate json response $.each( response, function(key, val) { $("#msgSubmit").append( val + "<br />"); //append results to element }); }); }); views.py def contact_form(request): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) html <form id="contactForm" method="get" action="{% url 'contact-form' %}"> ... <button type="submit">Submit</button> </form> <div id="msgSubmit"></div> When I submit the form: If there is no validation errors, I get 'true' appearing at #msgSubmit. If there is an error, I get nothing. I want JSON errors to appear at #msgSubmit. -
How to get result with ORM from queryset
I want to get result with ORM of Django. But I cannot get result with ORM. I just tried with 'select_related("field_name")'. but doesn't work.. Actually, I don't know using ORM well haha... and.. This Query is my needs SELECT sol.idx, sol.sol_name, sol.sol_warning, sol.user_num_id, sol.auto_run_server, ur.user_ip, pc.cpu_usage, pc.mem_usage, pc.disk_usage FROM solution AS sol INNER JOIN ems.user AS ur ON sol.user_num_id = ur.user_num INNER JOIN pc_status AS pc ON sol.user_num_id = pc.user_num_id; result row is ... idx, sol_name, sol_warning, user_num_id, auto_run_server, user_ip, cpu_usage, mem_usage, disk_usage so.. I used code is " Solution.objects.select_related('user_num') " But I cannot get same result. here are my python codes. models.py class User(models.Model): user_num = models.IntegerField(primary_key=True, auto_created=True) user_ip = models.CharField(max_length=20) user_name = models.CharField(max_length=10) user_pwd = models.CharField(max_length=10) class Meta: db_table = 'user' class Solution(models.Model): idx = models.IntegerField(primary_key=True, auto_created=True) sol_name = models.CharField(max_length=50) sol_warning = models.IntegerField() user_num = models.ForeignKey(User, on_delete=models.CASCADE) auto_run_server = models.IntegerField() class Meta: db_table = 'solution' class PcStatus(models.Model): pc_idx = models.IntegerField(primary_key=True, auto_created=True) cpu_usage = models.IntegerField(default=0) mem_usage = models.IntegerField(default=0) disk_usage = models.IntegerField(default=0) user_num = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'pc_status' -
how to send a message over websocket at a certain time
I am new to websockets and have just now gotten a working websocket connection in my application. I am trying to have the server check once per minute in the database to find upcoming tournaments, and for each player connected to a websocket that is registered in a tournament starting that minute, send a message that tournament with ID xxxxx is starting now. I have the following tournaments/consumers.py: from channels.generic.websocket import WebsocketConsumer import json class TournamentLobbyConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print("The websocket received a message: '%s'" % message) tournaments/routing.py: from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url('ws/tournaments/$', consumers.TournamentLobbyConsumer), ] tournaments/templates/index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Tournament Lobby</title> </head> <script> var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/tournaments/'); chatSocket.onmessage = function(e) { // var data = JSON.parse(e.data); // var message = data['message']; alert("message received from websocket") }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; </script> {% if tournaments %} <ul> {% for tournament in tournaments %} <li><a href="{% url 'tournament_detail' tournament.id %}"> {{ tournament.name }} {{ tournament.start_time }}</a></li> {% endfor %} </ul> {% else %} <p>No tournaments are available</p> {% … -
coreapi action create, No current document
I'm trying to post using coreapi and Django Rest Framework. I'm following this tutorial, which is based on the official one. Coreapi download the schema in a folder (PATH) which is not the current one, instead of logging some info as in the tutorial. $ coreapi get http://127.0.0.1:8000/schema/ <DownloadedFile 'PATH', open 'rb'> Then: $ coreapi action snippets list No current document. Use `coreapi get` to fetch a document first. And similarly I'm not able to post: $ coreapi credentials add 127.0.0.1 admin:testpass123 --auth basic Added credentials 127.0.0.1 "Basic YWRtaW46d2lsbGlhbTE=" $ coreapi action snippets create --param title="Example" --param co de="print('hello, world')" No current document. Use `coreapi get` to fetch a document first. I've tried to copy the schema file in the current directory in which the "coreapi action" command is executed, but no improvements. -
Join three serializers django
Right now I have a RelatedFileSerializer and a RequirementsSerializer. When I query the RequirementsSerializer, I would like it to return all the relatedfiles, and all the User information (email, first name, last name) for the relatedfiles, in place of the user ID that is being returned from the fire serializer. It properly returns the related files right now, but not the user information... views.py queryset = Controls.objects.filter(requirement_version=requirement) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'first_name', 'last_name') class RelatedFileSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = RelatedFiles fields = ('id', 'control', 'file', 'filename', 'uploaded_by_user', 'organization', 'note', 'uploaded_at') extra_kwargs = { 'uploaded_by_user': {'write_only': True}, 'organization': {'write_only': True}, } class RequirementsSerializer(serializers.ModelSerializer): relatedfiles_set = RelatedFileSerializer(many=True, read_only=True) class Meta: model = Controls fields = ('id', 'sorting_id', 'relatedfiles_set', 'requirement') -
Markdown is optional but my project already has Markdown 2.6 installed, get prepocessor error
I have Markdown 2.6 installed on my project and it is not feasible to update to version 3.0+ at this time. I see that Markdown 3.0+ is required, but because I have 2.6 it still successfully imports? As a result, in compat.py it successfully imports Markdown, however it breaks on line 213 because the highlight markdown preprocessor now uses register instead of add. The error is: Exception Type: AttributeError Exception Value: 'OrderedDict' object has no attribute 'register' Exception Location: /docker_venv/lib/python3.6/site-packages/rest_framework/compat.py in md_filter_add_syntax_highlight, line 213 How can I get around this? Is there a way to disable Markdown? Relevant issues/PRs I found: https://github.com/encode/django-rest-framework/pull/6722 https://github.com/encode/django-rest-framework/pull/6412 Thanks! -
how to pass a variable to a celery task
I want to pass a variable to a celery task, how to do this? From this code(POST method). class ArticleView(APIView): def get(self, request, task_id): task = current_app.AsyncResult(task_id) response_data = {'task_status': task.status,} if task.status == 'SUCCESS': response_data['results'] = task.get() return Response({"HTML-tags": response_data['results']}) def post(self, request): url = request.data.get('URL') print(url) task = demo.delay(url) return Response(task.id) To this: @shared_task def demo(url): page = requests.get(url) tree = html.fromstring(page.content) all_elms = tree.cssselect('*') all_tags = [x.tag for x in all_elms] baba = Counter(all_tags) return baba My attempt was unsuccessful.Error: TypeError: demo() takes 0 positional arguments but 1 was given. -
table "appname_modelname" already exists , migrate doesnt create new table
when i create a new model inside models.py and run : python manage.py makemigrations appname #worked python manage.py migrate #doesnt worked i got this error table "storage_OldModel" already exists i also checked this question Django migrate : doesn't create tables but there wasnt something to help me out this is the traceback please if someone know a solution please let me know -
Using filter_vertical or filter_horizontal for a CharField with choices
I'm searching for a way to use Django's .filter_vertical for a CharField (one that is passed a choices argument) rather than a ManyToManyField. Django's .filter_horizontal/.filter_vertical attributes produce a nice JavaScript "filter" interface in the admin UI: # models.py from django.db import models class Country(models.Model): code = models.SlugField(max_length=2, primary_key=True) name = models.CharField(max_length=64, db_index=True, unique=True) class MyModel(models.Model): countries = models.ManyToManyField(Country, blank=True) # ... other fields here # admin.py from django.contrib import admin @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # ... other attributes here filter_vertical = ("countries",) This generates a form widget like: However, I'd like to use this for a CharField that is passed a list of choices: class MyModel(models.Model): countries = models.CharField( max_length=2, blank=True, choices=[ ("us", "United States"), ("tz", "Tanzania"), # and so on ] ) # ... other fields here This doesn't work as it stands, because .filter_horizontal and .filter_vertical requires that the field be a ManyToManyField. So, to rephrase the question a bit more specifically: since it looks like .filter_vertical and .filter_horizontal use a FilteredSelectMultiple widget for that field, how could I properly use this widget for a CharField? -
writing Django custom model field
I want to write a custom field that shows size of an item. like: "small", "medium", "large", "extra large". It have to be optional like IntegerField. this is what I want it to be. I don't know where and what should I do. -
Transforming HTML table populated by database query into matrix-like summary table
I have an HTML table that contains transaction-style information(date, category, and value) for each row. I would like to change this table from being a simple row-by-row table into a matrix-style summary table, taking in a group by query from my database and displaying the group by parameters as the column and row headers. Query: SELECT MONTH(date) as month, category, value FROM transactions GROUP BY month, category Current Table (using a query without the group by): Month || Category || Value ------------------------------ Jan || Produce || 10 Jan || Poultry || 20 Feb || Poultry || 30 Feb || Poultry || 20 Desired Table: || Jan || Feb ------------------------------ Produce || 10 || 0 Poultry || 20 || 50 I have no trouble reading the data into my table or displaying it, but I have been struggling to figure out how to format or display a table or some alternative HTML object in the matrix-style I have described. This is the HTML code to create my current table. I am using Django as my framework (hence the django syntax {{}} to populate my table). This does not seem like a Django problem to me, so I am not including any … -
django 2.2.5 URL regex in url path
I would like to support the above views in a single view in url ...in my search I came across [this post][1] which is no longer supported and all the tutorials i've found have been outdated, which demonstrate how to accomplish the task in django 1.8.3. In 'products/views.py' I have created a views for products and details. ProductListView will display all products, while ProductDetailView will display a single product detail (title, description, price etc). products/views.py class ProductListView(ListView): queryset = Product.objects.all() template_name = "products/list.html" class ProductDetailView(DetailView): queryset = Product.objects.all() template_name = "products/detail.html" products/urls.py include path to the views for ProductListView and ProductDetailView. ProductListView appears to be correct. ProductDetailView is incorrect! I'm getting the following warnings: WARNINGS: ?: (2_0.W001) Your URL pattern '^products/(?P\d+)/$' [name='details'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ecommerce.py/urls.py is where i've included products and details urls ecommerce/urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from .views import home, about, contact urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('about/', about, name='about'), path('products/', include('products.urls'), name='products'), path('products/', include('products.urls'), name='details'), path('contact/', contact, name='contact'), path('account/', … -
__init__() takes 1 positional argument but 2 were given. I'm getting this error in my django code
Views.py content import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from blog.models import Post, Comment from django.utils import timezone from blog.forms import PostForm, CommentForm from django.utils.decorators import method_decorator from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') I'm getting following error:- TypeError at /accounts/login/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 2.2.5 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\Hp\Anaconda3\envs\proenv\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 Python Executable: C:\Users\Hp\Anaconda3\envs\proenv\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Hp\Desktop\myproject\blog_project\mysite', 'C:\Users\Hp\Anaconda3\envs\proenv\python37.zip', 'C:\Users\Hp\Anaconda3\envs\proenv\DLLs', 'C:\Users\Hp\Anaconda3\envs\proenv\lib', 'C:\Users\Hp\Anaconda3\envs\proenv', 'C:\Users\Hp\Anaconda3\envs\proenv\lib\site-packages'] Server time: Tue, 17 Sep 2019 20:11:42 +0000 -
Django cannot serialize into migration file
Hi there i'm having problems when trying to use the command makemigrations with manage.py. The output is the following: Migrations for 'reg': reg\migrations\0012_auto_20190917_1711.py - Remove field Products from tenant - Add field products to tenant - Alter field productos on preaprobado - Alter field tenant_id on preaprobado - Alter field CMS_id on producto - Alter field CMS_id on tenant Traceback errors ValueError: Cannot serialize: <Producto: Basico - ['IPTEL', 'Rocstar', 'Test_DVT']> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/2.2/topics/migrations/#migration-serializing The thing is that the entire app works just fine but for some reason i can't understand i cannot migrate the db. Here is the models.py: class Producto(models.Model): Name = models.CharField(max_length = 50, unique = True) CMS_id = models.PositiveIntegerField(unique = True) def __str__(self): #Toma los tenants que tienen el producto asignado por el nombre y forma una lista de los nombres de los tenants #para que aparezcan al lado del nombre del producto tenants_with_product = Tenant.objects.filter(products__Name = self.Name) tenants_dict = tenants_with_product.in_bulk(field_name = "Name") tenants_list = [] for tenant_name in tenants_dict.keys(): tenants_list.append(tenant_name) return(self.Name + " - " + tenants_list.__str__()) class Tenant(models.Model): Name = models.CharField(max_length = 30, unique = True) Enabled = models.BooleanField(default = False) CMS_id = models.PositiveIntegerField(unique … -
Wagtail: How to override default ImageEmbedHandler?
I've been having some trouble implementing Wagtail CMS on my own Django backend. I'm attempting to use the 'headless' version and render content on my own SPA. As a result, I need to create my own EmbedHandlers so that I can generate URL's to documents and images to a private S3 bucket. Unfortunately, though I've registered my own PrivateS3ImageEmbedHandler, Wagtail is still using the default ImageEmbedHandler to convert the html-like bodies to html. Is there a way for me to set it so that Wagtail uses my custom EmbedHandler over the built in default? Here's my code: from wagtail.core import blocks, hooks from messaging.utils import create_presigned_url class PrivateS3ImageEmbedHandler(EmbedHandler): identifier = "image" @staticmethod def get_model(): return get_user_model() @classmethod def get_instance(cls, attrs): model = cls.get_instance(attrs) print(model) return model.objects.get(id=attrs['id']) @classmethod def expand_db_attributes(cls, attrs): image = cls.get_instance(attrs) print(image) presigned_url = create_presigned_url('empirehealth-mso', image.file) print(presigned_url) return f'<img src="{presigned_url}" alt="it works!"/>' @hooks.register('register_rich_text_features') def register_private_images(features): features.register_embed_type(PrivateS3ImageEmbedHandler) -
primary key 135 has an invalid foreign key: imageApp_webpage.topic_id contains a value 5 that doesn't have a corresponding value in imageApp topic.id
**from django.db import models from django.contrib.auth.models import User class Details(models.Model): name = models.CharField(max_length=264, unique=True) email = models.EmailField(max_length=50, unique=True) url = models.URLField(unique=True) class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # author information portfolio = models.URLField(blank=True) image = models.ImageField(upload_to='CollectionImage/image', blank=True) def __str__(self): return self.user.username** I DON'T UNDERSTAND WHY I'M FACING THIS KIND OF PROBLEM. LIKE: bad_value, referenced_table_name, referenced_column_name django.db.utils.IntegrityError: The row in table 'imageApp_webpage' with primary key '135' has an invalid foreign key: imageApp_webpage.topic_id contains a value ' 5' that does not have a corresponding value in imageApp_topic.id. -
Python warnings to exceptions in Django tests with ignore
I'm attempting to run Django unit tests using: python -We -W ignore:DeprecationWarning -W ignore:UserWarning manage.py test However, this doesn't successfully ignore these warning classes, and instead only respects the -We flag, raising all warnings to exceptions. This is not my desired behavior. How can I run Django tests such that all warnings except DeprecationWarning and UserWarning are raised as exceptions when encountered in a test?