Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How can I have two identical many to many field with different name in django?
When ever I run the following migrate it gives me an error saying: ValueError: Cannot alter field matchpayments.PaymentsData.players into matchpayments.PaymentsData.players - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) Is there any way I can have two identical many to many without any error. class PaymentsData(models.Model): match = models.CharField(max_length=30) amount = models.DecimalField(default = 0, max_digits = 5, decimal_places = 2) players = models.ManyToManyField(Profile) playerspaid = models.ManyToManyField(Profile, related_name='paid') datespent = models.DateField('Date Spent') -
.create() method inside nested serializer not working
I created a nested serializer as you can see below. Now initially i got the error that I need to either override .create() method or use read_only (but I don't want to do that, I need to enter data). This is my solution but it doesn't seem to want to work. When I run it, it gives me the error not null constraint failed: order_unit price Ideas would be most welcomed. Thanks The models: class Order(models.Model): code = models.IntegerField code_year = models.IntegerField date_registered = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(Customer, related_name='customer_orders', null=True, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name='orders', null=True, on_delete=models.CASCADE) class Order_unit(models.Model): order = models.ForeignKey(Order, related_name='orderunits', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='orderunits_products', null=True, on_delete=models.CASCADE) amount = models.IntegerField price = models.IntegerField The serializer: class OrderUnitSerializer(serializers.ModelSerializer): price = serializers.SerializerMethodField('get_price') order = serializers.SerializerMethodField('get_id') product = serializers.SerializerMethodField('get_product') class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] def get_price(self, instance): return instance.amount * instance.product.default_price def get_id(self, instance): return instance.order.id def get_product(self, instance): return instance.product.id class OrderSerializer(serializers.ModelSerializer): orderunits = OrderUnitSerializer(many=True) class Meta: model = Order fields = [ 'id', 'code', 'code_year', 'date_registered', 'customer', 'creator', 'orderunits' ] def create(self, validated_data): orderunits_data = validated_data.pop('orderunits') order = Order.objects.create(**validated_data) for orderunit_data in orderunits_data: Order_unit.objects.create(order=order, **orderunit_data) return order -
Add a Class for labels in the Custom Django Form
I am trying to add a class for label in a custom django form. I am able to add class to the input but for the labels I have been struggling for a while: Here is the model class Info(models.Model): businessName = models.CharField(max_length=100) Here is the form: class infoForm(ModelForm): class Meta: model = Info fields = ['businessName'] widgets={ 'businessName':forms.TextInput(attrs={"class": 'form-control'}), } labels = { 'businessName': 'Business Name', } My question: How to add the class form-label inside the label of every input? -
Django - How to give one object multiple relational objects and how to create them?
I have a MusicAlbum which might have not just one genre related to it. Within my import process I have the following function defined to first get the genre and second, create a relation between the MusicAlbum and the Genre: def pull_genre(object_id): genre_list = [] split_content = [meta.strip() for meta in genre_value.split(',')] genre_list.append(split_content) for genre in genre_list: new_genre, create = object_id.genre_relation.get_or_create( name=genre, object_id=object_id, ) Problem now is that the following gets written to my Database: ['Rock', 'Metal'] But what I want is not a list stored inside my database, instead I want to have separate objects at my DB. One for Rock the other for Metal, what I'm doing wrong here? -
Django Login Form Displaying Incorrectly
My basic login page works fine when I go through the login link directly. It correctly applies the class 'form-control' to the input. The strange issue arrives if I try to visit a page that I need to be logged in for to view, it will redirect to the login page(as expected) but then for some reason it decides to not apply my attributes to the form. I am unsure as to why this is happening, maybe due to the redirect to the page instead of an actual visitation. I've attached screen shots to show exactly what I mean. When inspecting the html I can clearly see the attributes are not applying when it seems to be a redirect to the login page. Why does it behave in this way? What would be the best way to fix this? Any help is greatly appreciated! basic view for the login page class MyAuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget = forms.widgets.TextInput(attrs={ 'class': 'form-control' }) self.fields['password'].widget = forms.widgets.PasswordInput(attrs={ 'class': 'form-control' }) -
AttributeError: module 'delivery.models.order_timelocation' has no attribute '_meta'
I'm new into django and I'm trying to do some one to many relationships. In my project I have the following models: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField() date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) class orderTimelocation(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_timelocation'), longitude = models.DecimalField(decimal_places=8, max_digits=12) latitude = models.DecimalField(decimal_places=8, max_digits=12) class timeInterval(models.Model): start = models.DateTimeField() end = models.DateTimeField() order_timelocation = models.ForeignKey(orderTimelocation, related_name='time_interval', on_delete=models.CASCADE) and the following serializers: class OrderSerializer(serializers.ModelSerializer): orderTimeLocations = orderTimelocationSerializer(many=True) class Meta: model = Order fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'orderTimeLocations'] class orderTimelocationSerializer(serializers.ModelSerializer): timeintervals = timeIntervalSerializer(many= True) class Meta: model = order_timelocation fields = ('longitude', 'latitude', 'timeintervals') class timeIntervalSerializer(serializers.ModelSerializer): class Meta: model = time_interval fields = ['start', 'end'] I tried to follow the example given in django rest framework documentation on the topic Nested relationships, that I think is the most appropriated for this case, but the following error occurs Traceback (most recent call last): File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line … -
JWT token authentication and autologin with ReactJS SPA and Django dj-rest-auth
I'm working on authentication system for ReactJS single page application and with backend in Django using dj-rest-auth package. The plan was to use JWT token for authentication, but there is one thing that causes my concern, which is CRSF protection. Normally, a user logs in in React, meaning provides email/username + password and the request to /login endpoint and dj-rest-auth LoginView urlpatterns = [ ... path('api/login', LoginView.as_view()), # dj-rest-auth view ... ] LoginView of dj-rest-auth package, when configured to use JWT tokens and disabled Session authentication as default (just JWT) automatically sets response cookies with jwt cookie and jwt refresh cookie (using Set-Cookie): set_jwt_cookies(response, self.access_token, self.refresh_token) which results in setting Secure and httpOnly cookies saved in my browser cookies like that (names of cookies are predefined by me in Django settings): Now - I'm expecting site to work in a way, that even after user closes the page and reopens it, my autologin feature in React would verify, whether user is logged in (or in other words authenticated to view protected page) - so if the user is authenticated - React will redirect to dashboard or some main authenticated page. Autologin feature basically sends request to endpoint /autologin using axios … -
Retrieve one class model data and use in another class model Django
I want to retrieve data of one model class, make it a list of tuples and put as a choices in other model class. Two classes have not any kind of relationship. class Category(models.Model): restaurant = models.ForeignKey(Restaurant, related_name='categories', on_delete=models.CASCADE) name = models.CharField(max_length=128, db_index=True) slug = models.SlugField(max_length=128, unique=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return str(self.name) def get_categories_list(restaurant): clist = list(Category.objects.filter(restaurant=restaurant)) categories = [] for i in range(len(clist)): name = clist[i].name slug = clist[i].slug tup = tuple([slug,name]) categories.append(tup) return categories class Product(models.Model): restaurant = models.ForeignKey(Restaurant, related_name='products', on_delete=models.CASCADE) CATEGORIES = get_categories_list(restaurant) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) category = models.CharField(max_length=200, db_index=True, choices=CATEGORIES) here is some classes from models.py module -
ImportError: libpq.so.5: cannot open shared object file: No such file or directory
(My operating system is fedora 34) I use django with haystack and postgresql. For development purposes I run heroku local command. I use three files for settings: base.py, local.py, pro.py. When I run heroku I use local.py file: from . base import * DEBUG = True SECRET_KEY='secretKey' DATABASES = { 'default': { 'ENGINE':'django.db.backends.sqlite3', 'NAME':os.path.join(BASE_DIR, 'db.sqlite3'), } } if DEBUG: INTERNAL_IPS = ('127.0.0.1', 'localhost',) DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', ] DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } export DJANGO_SETTINGS_MODULE=myshop.settings.local but heroku shows this error: 12:54:14 PM web.1 | File "/home/user/env2/lib64/python3.9/site-packages/django/contrib/postgres/apps.py", line 1, in <module> 12:54:14 PM web.1 | from psycopg2.extras import ( 12:54:14 PM web.1 | File "/home/user/env2/lib64/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> 12:54:14 PM web.1 | from psycopg2._psycopg import ( # noqa 12:54:14 PM web.1 | ImportError: libpq.so.5: cannot open shared object file: No such file or directory 12:54:14 PM web.1 | [2021-07-21 09:54:14 +0000] [7689] [INFO] Worker exiting (pid: 7689) 12:54:14 PM web.1 | [2021-07-21 12:54:14 +0300] [7688] [INFO] Shutting down: Master 12:54:14 PM web.1 | [2021-07-21 12:54:14 +0300] [7688] [INFO] Reason: Worker failed to boot. Postgresql is running: postgresql.service - PostgreSQL database server Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; vend> Active: active … -
Writing SQL query in production server for changing foriegnkey field to m2m in django & aws
I hava a django applcation where there are two models Desination and Package, where Package has a foriegn key field to Destination. Now after many days clients wants it to be m2m. I have to change that and also preserve the data at the same time. My models: class Destination(models.Model): name = models.CharField(max_length=255, unique=True) .................../ class Package(models.Model): # destination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name='package') destinations = models.ManyToManyField(Destination,related_name='packages') ....................../ Here I changed the fk field to m2m with the following way: from __future__ import unicode_literals from django.db import models, migrations def make_many_destinations(apps, schema_editor): """ Adds the Destination object in Package.destination to the many-to-many relationship in Package.destinations """ Package = apps.get_model('packages', 'Package') for abc in Package.objects.all(): abc.destinations.add(abc.destination) class Migration(migrations.Migration): dependencies = [ ('packages', '0006_package_destinations'), ] operations = [ migrations.RunPython(make_many_destinations), ] I did exactly the same as this Django data migration when changing a field to ManyToMany I had to create a custom migration file (above), write a function, and then run migrate. In my local development, it works perfectly. The field is changed to m2m and there are data as well. We are having aws as a production server. I did the commits and did eb deploy, then went to the production database and … -
To import all objects in multiple nested foreign key relationships efficiently in django
Is there an effective way to get all dictionary objects that correspond to the product? This is my django model class Product(models.Model): ... class Ingredient(models.Model): product = FK(Product) middle = FK(Middle) ... class Middle(models.Model): dictionary = FK(Dictionary) ... class Dictionary(models.Model): ... The way I did it. product = Product.objects.get(id=1) ingredients = ProductIngredient.objects.filter(product=product) middles = ProductMiddle.objects.filter(ingredient__in=ingredients) dictionaries = ProductDictionary.objects.filter(middle__in=middles) but I want dictionaries = product.ingredient.middle.dictionary.all() (?) # AttributeError: 'RelatedManager' object has no attribute 'middle' Or Is there a better way? Is there a way to import this data with fewer queries? -
Visual studio code debug tool for python unit test does not show debug tools, when extra library is imported
For pure Django tests, visual studio code easily discovers my tests so i can debug them: class SomethingTest(TestCase): def setUp(self) -> None: return super().setUp() def test_something(self): self.assertEqual(4, 4)``` **But when i add some Django-rest-framework libraries - debug tools disappear:** ```from django.test import TestCase from rest_framework.test import APIClient class BoringTest(TestCase): def setUp(self) -> None: return super().setUp() def test_boring(self): self.assertEqual(4, 4) How can i setup vs code unit-test debug tools so i can use rest_framework? -
Django elasticsearch dsl updating information on object fields multiple levels deep
The problem for me is that the object fields don't get updated for all indexes. In my cases I tested changing the foreign key in product to product_information. The elasticseasrch indexes were updated for every index except for the stock index. Is there a way to solve this issue? @registry.register_document class ProductInformationDocument(Document): brand = fields.ObjectField(properties={ 'name': fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ), }) title = fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ) class Index: name = 'product_information' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = ProductInformation related_models = [Brand] fields = [ 'review_score', 'review_count' ] def get_queryset(self): return super(ProductInformationDocument, self).get_queryset().select_related( 'brand' ) def get_instances_from_related(self, related_instance): return related_instance.product_information_set.all() @registry.register_document class ProductDocument(Document): product_information = fields.ObjectField(doc_class=ProductInformationDocument) category = fields.ObjectField(properties={ 'name': fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ), 'category_code': fields.IntegerField() }) subcategory = fields.ObjectField(properties={ 'name': fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ), 'subcategory_code': fields.IntegerField() }) chunk = fields.ObjectField(properties={ 'name': fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ), 'chunk_code': fields.IntegerField() }) id = fields.IntegerField() ean = fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ) class Index: name = 'products' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Product related_models = [Category, SubCategory, Chunk, ProductInformation] fields = … -
Django - OperationalError after deleting migration files
In the earliest days of my system, before i knew how to utilize django's built-in User model, i had my own class named myUser which i intended to use for the same purpose. i ended up deleting this one and instead using django's User model. all was fine for a while. then i tried to change the id of all my custom models to a UUIDField, and got the syntax wrong, which i unfortunately only realized after i ran makemigrations and migrate. i corrected it, but there was still a bug because the migration file of the wrongly-syntaxed UUIDField still lingered in migrations. that's what i understood from googling for a while, anyway. since i wasn't sure which migration file caused the error, i just deleted the last 5 migration files (in hindsight, not the best idea i've ever had). Unfortunately, one of those migration files were the one which covered the deletion of the myUser model. now, whenever i try to migrate, i get the following error: django.db.utils.OperationalError: no such table: phoneBook_myUser it seems this error is stopping any of my new migrations to go through. i've googled for a while, and it seems my two options are to … -
Django, annotate field with id of many-to-many field's element with lowest parameter
I have the following models: from django.db import models class Topping(models.Model): # ... price = models.IntegerField() class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) I need to get following query: my_query = Pizza.objects.all().annotate( topping_with_min_price="get id of topping with the minimal price") So, how to get that? -
Does anyone have idea how to start with cardconnect/cardpointe payment gateway integration?
Cardpointe is payment gateway i need to integration for my django web application. and I am integrating for the first time. https://developer.cardpointe.com/cardconnect-api