Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ValueError: "" must be a "" instance
I am trying to save some data into the database with a form but am getting the exception ValueError: Cannot assign "<ShoppingCartOrderItem: 1 of The Crucifixion>": "Review.product" must be a "Product" instance. I think I understand the issue I am just unsure on how to solve it. Basically I have products which are displayed if the user has ordered the item, they then can choose to leave a review. In my form in the select options I am returning a query set so that they only have the orders that they have ordered displayed. Models: class ShoppingCartOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) rating = models.DecimalField(max_digits=2, decimal_places=1, validators=[MinValueValidator(Decimal('0.1'))]) comment = models.TextField(validators=[MinLengthValidator(10)]) date = models.DateField(auto_now=True) Views: class MyOrdersView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): try: order = ShoppingCartOrder.objects.filter(user=self.request.user, ordered=True) form = ReviewForm(user=self.request.user) context = { 'object': order, 'form': form } return render(request, 'my_site/my_orders.html', context) except ObjectDoesNotExist: messages.warning(request, 'You do not have any orders') return redirect('all_products') def post (self, request, *args, **kwargs): form = ReviewForm(request.POST, user=self.request.user) if form.is_valid(): form = ReviewForm( product = form.cleaned_data['product'], rating = form.cleaned_data['rating'], comment = form.cleaned_data['comment'] ) form.save() return … -
How Do I order a Django model by name?
I have got a list of products from different retailers. I am trying to sort the list to try and group all products that are the same but have different retailers together. I am trying to sort the model by 'product', so that it is presented in order in the Django admin panel, and so that I can carry out commands on a product group at once. How should I go about doing this? Model: class RetailerProduct(models.Model): url = models.CharField(max_length=300,null=True,blank=True) price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) difference = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) available = models.BooleanField(default=False) _id = models.AutoField(primary_key=True, editable=False) product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='sources') def __str__(self): return self.retailer.name + " - " + self.product.name I have tried using: class Meta: ordering = ('product',) But it does not work. -
Django - modify a field value in filter()
I want to modify some_date_field value while filtering. Like using models.Lookup or models.Transform but I dont want to make a raw sql expression. Just modify model's field value Smth like this: class SomeModel(models.Model): some_date_field = models.DateField() def replace_year(value): return value.replace(year=2021) SomeModel.objects.filter( # replace_year(some_date_field)__gte= ... ) Is it possible? -
Custom authentication with djoser using django 3.1
Im having problems making my backend (takes either phone number or email address for login) work with djoser for login. It seems to be only loging in the superuser account hen i want it to take either the phone number or email address. ps: the backend is not from django rest framework but i created a custom authentication from vanilla django.(i created the full project before the api just in case this might be problem) Im new to APIs and Django i hope this is a relevant question. heres my code, let me know if you need more thanks My settings: DJOSER = { 'USER_CREATE_PASSWORD_RETYPE':True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'SEND_CONFIRMATION_EMAIL':True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE':True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL':True, 'SERIALIZERS': { 'user_create': 'rafiki.serializers.UserCreateSerializer', 'user': 'rafiki.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } my auth model: class CustomUserManager(BaseUserManager): """ Custom user model manager where Email_Address is the unique identifiers for authentication instead of usernames. """ def create_user(self, Email_Address, password, **extra_fields): """ Create and save a User with the given Email_Address and password. """ if not Email_Address: raise ValueError(_('The Email_Address must be set')) Email_Address = self.normalize_email(Email_Address) user = self.model(Email_Address=Email_Address, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, Email_Address, password, **extra_fields): """ Create and save a SuperUser with the given Email_Address and … -
How to filter related objects of related objects in Django?
Imagine a data model where: class Album(models): name = models.CharField class Song(models): albums = models.ManyToManyField(related_name="albums") class Word(models): songs= models.ManyToManyField(related_name="songs") category = model.Charfield() # can be "friendly", "expletive", etc. I.e. an album has many songs and a song can be on several albums. Then a song consists of many words and the same word can be in multiple songs. I'd like to construct a queryset consisting of all words where the category is "friendly", and which belong to all songs of an album. -
Django / Postgres - Sum aggregate function duplicates results when grouping by other annotations
The Django Sum() aggregation method produces buggy results when combined with multiple annotations that usually results in duplicated data when a row of data can fit into multiple categories Take the following for example: class Item(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField(blank=True, null=True) class ItemLink(models.Model): id = models.BigAutoField(primary_key=True) parent_item = models.ForeignKey(Item, blank=False, related_name='parent_item_links') child_item = models.ForeignKey(Item, blank=False, related_name='child_item_links') class Aggregate(models.Model): id = models.BigAutoField(primary_key=True) item_id = models.ForeignKey(Item, blank=False) data = models.FloatField(blank=True, null=True) These 3 tables describe an item, the relationship items have to other items, and some aggregate table that has data associated to a particular item. If I were to sum the aggregate data for an item and group by any parent relationships it has, I would receive duplicate results. For example: [{ name: parent_1, id: 1 }, { name: parent_2, id: 2 }, { name: child_1, data: 1.0, (via aggregate) id: 3 }] if I were to query against this data set I would expect to get data: 1 for both the parent objects, but when I group by the items name, I get 2. Aggregate.objects.annotate('item_name': F('item__parent_item_links__parent_item__name')).annotate(agg_value=Sum('data')).filter('item_id__is': 3).values_list('item_name', 'agg_value') would give you [{ item_name: parent_1, agg_value: 2.0, }, { item_name: parent_2, agg_value: 2.0, }] where I'd expect it to … -
Modeling complex relationship between Django models based on another model's value
I am trying to model a Recipe that contains a series of Ingredients. In these ingredients, the price field is dependent on the value of another model (Supplier's location). For example, my Recipe could contain: Water, Beef and Salt. Each ingredient has a price, which depends on the user's location. I.e. if my user is from Texas, the price of the beef and water may change and therefore the total price of the recipe will change. Right now I'm using the following approach: class Product(models.Model): name = models.CharField(_('Name'), max_length=255, help_text=_('Product name')) price = models.FloatField(_('Sale price'), default=0) supplier = models.ForeignKey(Supplier, blank=True, null=True, related_name='supplier_products', on_delete=models.CASCADE) class IngredientRecipe(models.Model): product_name = models.CharField(_('Name'), max_length=255, help_text=_('Product name'), blank=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients') quantity = models.FloatField(_('Quantity')) class Recipe(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user_recipes') title = models.CharField(_('Recipe title'), max_length=255, help_text=_('Recipe. Example: american chicken salad'), blank=True) I'm using this models along with a serializer to show the price corresponding to the selected location: class VerySimpleRecipeSerializer(serializers.ModelSerializer): cost = serializers.SerializerMethodField(read_only=True) class Meta: model = Recipe fields = ['id', 'title', 'cost',] def get_cost(self, obj): ingredients_names = obj.ingredients.values('product_name', 'quantity') total_price = 0 try: location_id = self.context['request'].query_params.get('location', None) products = Product.objects.annotate(min_price=Min('price')).filter( Q(supplier__location_id=location_id) & Q(name__in=[x.get('product_name', None) for x in ingredients_names]), is_active=True, min_price__lte=F('price')).order_by() except … -
Django Object filter expected id (int) but get str
I make Django blog project and I've implemented a function to filter posts by their tag. There is a possibility to select a certain tag and to see all posts with this specific one. But I have trouble when I want to filter all posts by this tag. I get an error that Django expects int number but not str. How to solve this problem? This is my code models.py class Tag(models.Model): name = models.CharField(max_length=200, null=True) slug = models.SlugField(max_length=250, unique=True, editable=False) class ProjectPost(models.Model): tag = models.ForeignKey(Tag, on_delete=models.PROTECT) url.py urlpatterns = [ ... path("projects/", views.projects, name='projects'), path('projects/<slug:tag>/',views.projects, name='projects_tag'), ] views.py def projects(request, tag=None): if tag is not None: ProjectPost.objects.filter(tag=tag) else: posts = ProjectPost.objects.all() tags = Tag.objects.all() context = {'posts':posts, 'tags':tags} return render(request, 'website/projects.html', context) THis is error ValueError at /projects/romania/ Field 'id' expected a number but got 'romania'. Request Method: GET Request URL: http://127.0.0.1:8000/projects/romania/ Django Version: 3.2.5 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'romania'. Exception Location: /home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/db/models/fields/__init__.py, line 1825, in get_prep_value Python Executable: /home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/bin/python Python Version: 3.8.5 Python Path: ['/home/cristian/Desktop/GreatEcology my project/ecosite/ecowebsite', '/home/cristian/Anaconda3/lib/python38.zip', '/home/cristian/Anaconda3/lib/python3.8', '/home/cristian/Anaconda3/lib/python3.8/lib-dynload', '/home/cristian/Desktop/GreatEcology my ' 'project/ecosite/venvecosite/lib/python3.8/site-packages'] Server time: Wed, 21 Jul 2021 14:36:51 +0000 -
Django filter() takes longer than full query
I am trying to write a view with the following query in Django on SQL Server (Table has ~2M rows): queryset = DeliveryDetails.objects.filter(backOrdered_gt=0).annotate( customerCode=F('deliveryId__customerCode'), deliveryNumber=F('deliveryId__deliveryNumber'), deliveryDate=F('deliveryId__deliveryDate'), canceled=F('deliveryId__canceled'), discountPer=F('deliveryId__discount') / 100, ordered=Case( When(canceled='C', then=F('orderedQuantity') * -1), default=F('orderedQuantity') ), orderedTotal=Case( When(canceled='C', then=F('orderedQuantity') * -1 * F('price') * (1 - F('discountPer'))), default=F('orderedQuantity') * F('price') * (1 - F('discountPer')) ), backOrdered=Case( When(canceled='C', then=F('quantityBacked') * -1), default=F('quantityBacked') ), backOrderedTotal=Case( When(canceled='C', then=F('quantityBacked') * -1 * F('price') * (1 - F('discountPer'))), default=F('quantityBacked') * F('price') * (1 - F('discountPer')) ) ) However, this query takes over a minute to run and returns ~173k entries. However, when I exclude the filter() method, it takes 3 seconds to run despite returning the full 2M entries. When I tried running the filter on its own (without annotate) as such: DeliveryDetails.objects.filter(quantityBacked__gt=0) It still takes an extremely long time to load. What is the reason behind this and what would be a potential solution? Here are the models for reference: class Deliveries(models.Model): deliveryId = models.IntegerField(db_column='id', primary_key=True) deliveryNumber = models.IntegerField(db_column='num', blank=True, null=True) deliveryType = models.CharField(db_column='type', max_length=1, blank=True, null=True) canceled = models.CharField(db_column='canceled', max_length=1, blank=True, null=True) deliveryDate = models.DateTimeField(db_column='date', blank=True, null=True) customerCode = models.CharField(db_column='customerCode', max_length=15, blank=True, null=True) customerName = models.CharField(db_column='customerName', max_length=100, blank=True, null=True) discount = models.DecimalField(db_column='discount', … -
Group and display products by category and brand in Django
I'm new to Django and I'm currently having troubles creating a very simple list of products, grouped by categories and brands. Here's the expected result: - Category 1 + Brand A * Product 1 * Product 2 + Brand B * Product 3 * Product 4 - Category 2 + Brand A * Product 5 * Product 6 + Brand C * Product 7 * Product 8 Here's my models.py from django.db import models class Brand(models.Model): brand = models.CharField(max_length=200) country = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=200, blank=True, null=True) url = models.URLField(max_length=300) def __str__(self): return self.brand class Category(models.Model): category_id = models.CharField(max_length=200, default="cat") name = models.CharField(max_length=200) def __str__(self): return self.category_id class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) desc = models.CharField(max_length=200, blank=True, null=True) img = models.CharField(max_length=200) url = models.URLField(max_length=300, blank=True, null=True) def __str__(self): return f"{self.brand} - {self.name} - {self.category}" My views.py def product_list(request): products = Product.objects.all() categories = Category.objects.all() brands = Brand.objects.all() context = { 'products': products, 'categories': categories, 'brands': brands } return render(request, "product/product-list.html", context) And here's the closest I could get to achieve the expected result in my product-list.html <ul> {% for category in categories %} <li>{{ category }}</li> <ul> {% for brand in … -
Django model with historycal change
How can i show model historical changes and show them and can modify? for example class MM(models.Model): chnge1=model.ForeignKey('self') changeText = models.TextField(max_length=200) -
django multi-database switch login problem
I am a newbie to django, I am currently trying to make a project, the content is two beverage store apps, and then you must choose which database to use when logging in to the interface, and the database structure of these two beverage stores All the same, I don’t know if I should use router to do this? Or how should I deal with this problem, I hope someone can help me with this problem -
Django collectstatic generates different files on deployment than in development
When I run my Django app locally using runserver it works perfectly fine. Today I started deploying the app to our staging env running on Windows Server 2012. Debug mode is off, I have an "app" configured in IIS called 'static', where the settings point at. After running collectstatic on the server and starting the site, the dashboard looks alot different. Every view which has a search bar has too much margin, same for the filter window. I don't have any of these issues locally. While inspecting the pages using chrome dev tools and comparing local with live, I found out that the live version has set the margin of a div in question to margin=0 0 0 30px while locally it has margin=0 local: live: I'm actually baffled, I have no clue how this is happening. Please help! -
Chaining multiple filters() in Django having different lists
I've been trying to use two different filter conditions having 2 different set of lists. Here, filter(condt.1) is working and filter(condt.2) is working; but when I use filter(condt.1).filter(condt.2) it's working differently i.e. not working in the way I had assumed. Here is my situation: This one is working properly: posts = Post.objects.filter(author__profile__in=[logged_in_user.id]) This one is also working properly: posts = Post.objects.filter(author__profile__followers__in=[logged_in_user.id]) But I am not getting the way to combine these two filters in one. Here is what I've tried: logged_in_user = request.user posts = Post.objects.filter(author__profile__in=[logged_in_user.id]).filter(author__profile__followers__in=[logged_in_user.id]) -
Django request.user not working when using auth_user_model in models.py
I am using the User model (which is a custom one) in my models.py by import settings and getting it through the AUTH_USER_MODEL but it seems like in my views that the request.user is not recognize as an instance of the user class. Here is the model from django.db import models from django.conf import settings from django.utils import timezone User = settings.AUTH_USER_MODEL class Site(models.Model): name = models.CharField( max_length=100, ) slug = models.SlugField(max_length=20) admin = models.ForeignKey( User, related_name="administrators", on_delete=models.SET_NULL, blank=True, null=True, ) people = models.ManyToManyField(User) def __str__(self): return self.name HERE is the logic in the views def create_site(request): user = request.user print(user) form = CreateSiteForm( request.POST or None, initial={ "admin": user, }, ) if form.is_valid(): form.save() return redirect("projects") context = { "form": form, } return render(request, "tracking/create-site.html", context) Here is the error from the terminal return self.is_bound and not self.errors File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\forms.py", line 170, in errors self.full_clean() File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\forms.py", line 374, in full_clean self._post_clean() File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\models.py", line 408, in _post_clean self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude) File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\models.py", line 63, in construct_instance f.save_form_data(instance, cleaned_data[f.name]) File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\fields\__init__.py", line 910, in save_form_data setattr(instance, self.name, data) File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__ raise ValueError( ValueError: Cannot assign "'papis'": "Site.admin" must be a "User" instance. … -
Run python code after certain SweetAlert button is clicked - Django
I am creating a donation web application that allows donors to donate food and supplies. I have a SweetAlert (Down Bellow), and when a user clicks the ok button, I want to run a python-django code like redirecting the user to another page. I am not sure if I need to use a view or if I can do it strictly in my javascript. Sweet Alert javascript: function showAlert() { swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } I am not sure if I need to include my view, please tell me if I need to and I can update my question. Thank you to everyone who helps. -
How would I structure a single page application that takes an input, fetches data from the back end, then renders it to the front end with routers?
Example: https://redditmetis.com/ Issue I've been having trouble trying to structure a recent SPA I started. Like the above example, I need to accept an input, make a few API calls in the back-end, manipulate the data then render it the front-end. I'm currently going for a Django + React stack, since I'm pretty familiar with them. I can't really imagine how this would look like from a surface view, I've worked with API's before but I can't wrap my head around how the client and the server would interact with each other to make it all connect. What I have so far After looking into it, I think I need React Routers, similar to the example website provided. In my Django server, I plan on making separate API calls and running an algorithm to organize and sift through the received response, then pushing the product to the client. I'm still figuring out how to set that up, since most API calls are made on componentdidmount which only executes at the start of the DOM. This isn't much, but its a start. If anyone has pointers on how to start, I'd appreciate it, thanks. -
how to get complaint details of all the users in django except the user logged in
I am creating a system where users can log in and enter complaints, view and edit them as well and also view complaints of other users on a different page. I have already created a page where they can view their own complaints but i don't know how to let them view other users complaints. Can someone please tell me what to type into the views.py and the template? Do i also need to make a new form for this? The page is to look like this: models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE class Profile(models.Model): user = models.OneToOneField(User,null= True , blank = True, on_delete= models.CASCADE) profile_pic = models.ImageField(default = "msi.jpg", null = True, blank= True, upload_to= 'static/profileimages') first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name … -
Django - get multiple objects by related_query_name
I have the following Model at my models.py to store genre information for specific objects at my Database like Movies for example: class Genre(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=referential_genre_models, on_delete=models.CASCADE, verbose_name=_("Content Type")) object_id = models.CharField(max_length=36, verbose_name=_("Object ID")) content_object = GenericForeignKey('content_type', 'object_id') name = models.CharField(verbose_name=_("Genre"), blank=True, null=True, editable=False, max_length=50) date_added = models.DateTimeField(auto_now_add=True, verbose_name=_("Date Added")) At my Movies model class I have the following field to connect the two models with each other: genre_relation = GenericRelation(Genre, related_query_name='genre_relation') At my views.py I now want to query onto specific Movies of genre "Comendy" and "Family" for example, but I don't get back any results: movie_genre_assets = Movies.objects.get_queryset().filter(Q(genre_relation__name="Comedy") | Q(genre_relation__name="Family")).order_by('release_date') Can smb. help? -
create fields according to a number in another field in django
I have 3 tables(Subjects, Sectors , Zones), one subject has many sectors and one sector has many zones my auestion is how should i implent my models and views and serializers in sort of returning a json file indicating the name of the subject and the number of sectors and the number of zones in every sector. I tried this : class Subject(models.Model): name = models.CharField(max_length=200) host = models.CharField(max_length=200, primary_key=True) nb_sectors = models.IntegerField(null=True) def __str__(self): return self.name class Sector(models.Model): name = models.CharField(max_length=200) task = models.ForeignKey(Subject ,on_delete=models.CASCADE) nb_zones = models.IntegerField(null=True) def __str__(self): return self.name class Zone(models.Model): name = models.CharField(max_length=200) sector = models.ForeignKey(Sector ,on_delete=models.CASCADE) status= ChoiceField(choices) def __str__(self): return self.name -
How to create migration dropping the table in Django 1.11?
After I removed some functionality from Django 1.11, I want to create the migration removing the corresponding entities in the database. How can I do that? For example, I removed the model named AB_Testing. I see the migration in ./apps/specific_app/migrations/0003_ab_testing.py How to create the migration reverting it back? -
How to automatically choose model fields in django after calculation?
class Home(models.Model): home_type = models.CharField(max_length=255) home_square = models.PositiveIntegerField(default=0) def __str__(self): return self.home_type Example output : Small home (type) = 60m2 (Home Square) // Medium home (type) = 90m2 (Home Square) // Big home (type) = 200m2 (Home Square) class Property(models.Model): name = models.CharField(max_length=255) width = models.PositiveIntegerField(default=0) length = models.PositiveIntegerField(default=0) property_type = models.OneToOneField(Box,null=True,blank=True, on_delete=models.SET_NULL) def __str__(self):` return self.property_name @property def property_square(self): property_square = self.product_length * self.product_width return property_square How can I assign a property type from Home model automatically to Property model according to property_square after calculation? if property_square < 60 than choose property type from Home model as a Small Home. if property_square >60 <90 than choose property type from Home model as a Medium Home. -
Navigating to different page instead of Ajax call
I am trying to save a form via ajax as I don't want to reload the page. It is working not completely but it is updating the data except the image or video or any upload file we give. but after updating it is coming back to the ajax page but the url is diiferent and success message is coming on that page. I am sharing some of the logic but if more information is required, please let me know . js code : $(document).ready(function() { $('#contentdataform').submit(function(e) { e.preventDefault(); $.ajax({ // create an AJAX call... data: $(this).serialize(), type: 'POST', url: 'updatecontent', success: function() { mess("Success"); //mess is a function to generate a disappearing message box. }, }); return false; }); }); function updatecontentform(){ console.log('starting'); document.getElementById('contentdataform').submit(); } views.py @csrf_exempt def updatecontent(request): print("--------------------") if request.method == "POST": id = request.session['content_id'] fm = ContentForm(request.POST, instance= Content.objects.get(pk = id)) print("fm") print(fm) if fm.is_valid: print("valid form") form = fm.save(commit=False) form.save() else: print("Not Valid") return JsonResponse("Success", safe= False) the output should be the message on the same page but it is reflecting on the new page with url '127.0.0.1:8000/updatecontent' -
How Do I Add and Email Attendees An Invite In Django (Google Calendar Integration)
I'm creating a booking app with Django that allows people to book a session but I've run into an issue where the API won't allow me to add attendees. The error that I keep getting is: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/02g427gf151ggdmcas2pui1suo%40group.calendar.google.com/events?alt=json returned "Service accounts cannot invite attendees without Domain-Wide Delegation of Authority.". Details: "[{'domain': 'calendar', 'reason': 'forbiddenForServiceAccounts', 'message': 'Service accounts cannot invite attendees without Domain-Wide Delegation of Authority.'} I've tried deploying the app and using Google Workspace to delegate authority but that doesn't seem to work. I have a virtual environment and below is the code for the app: views.py from django.shortcuts import render import datetime from .calendar_API import * import stripe # Create your views here. def home(request): tomorrow = datetime.date.today() + datetime.timedelta(days=1) month_from_now = datetime.date.today() + datetime.timedelta(days=30) if request.method == "POST": subject = request.POST.get('subject') desc = request.POST.get("desc") date = request.POST.get("daterange") email = request.POST.get("email") date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') hour_later = date + timedelta(minutes=60) hour_later = hour_later.isoformat() date = date.isoformat() def create_event(): service = build_service() # start_datetime = datetime.datetime.now(tz=pytz.utc) event = ( service.events() .insert( calendarId="02g427gf151ggdmcas2pui1suo@group.calendar.google.com", body={ "summary": subject, "description": desc, "start": { "dateTime": date, "timeZone":"Europe/London" }, "end": { "dateTime": hour_later, "timeZone":"Europe/London" }, "attendees": [ { "email":email } ], # … -
How to filter a field using another field of the same class in django models
I need to get the "description" value sorted by "name" from the same models django class in "def description_split(self)": class storeItem(models.Model): name = models.CharField(max_length=200, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, help_text="example: 37500.50") description = models.TextField(max_length=250, blank=False, default=False, help_text='Use"." to separate ' 'points. 250 words max', verbose_name="Points description") def __unicode__(self): return self.name def description_split(self): splitting = self.description.split('.') result = ''.join(splitting) return result How can I achieve that?