Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is better to use Class of Def in views
I have a question that bothers me. What is better to use in django views? Classes or defs? And if both, so when using it? When to deviate from a given method. -
Django models for creating multiple variations of t-shirts
I'm creating an ecommerce store that sells T-shirts, hoodies, mugs, shot glasses, etc. For the t-shirts and hoodies there are sizes and sometimes color associated with each product. I'm trying to add multiple variations for each product. Here's my model.py code: class Category(models.Model): name = models.CharField(max_length = 255, db_index=True, null=True, blank=True) slug = models.SlugField(max_length=255, unique=True, default='') class Meta: verbose_name_plural = 'categories'\ def get_absolute_url(self): return reverse('main:category_list', args=[self.slug]) def __str__(self): return self.name class Attribute(models.Model): name = models.CharField(max_length = 255, default='') def __str__(self): return self.name class ProductAttribute(models.Model): attribute = models.ManyToManyField(Attribute, through='Product') value = models.CharField(max_length = 255, null=True, blank=True) def __str__(self): return self.value class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length = 255, default='') description = models.TextField(blank=True) image = models.ImageField(upload_to='products/', null=True, blank=True) slug = models.SlugField(max_length = 255, default='') price = models.DecimalField(max_digits=4,decimal_places=2) has_attributes = models.BooleanField(default=False) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE, null=True, blank=True) value = models.ForeignKey(ProductAttribute, on_delete=models.CASCADE, null=True, blank=True) class Meta: ordering=(['name']) def get_absolute_url(self): return reverse('main:product_detail', args=[self.slug]) def __str__(self): return self.name The way it appears right now in my admin interface there is a name, attribute, value, and price (only named relevant fields for clarity). If I add a product like such: "t-shirt_1, size, sm, 17.98", then the next item I need to add … -
Hi everyone, i'm using django and trying to display a picture from my database, but am unable to
Most of the code I use is from this article: (copied from https://www.etutorialspoint.com/index.php/356-how-to-display-image-from-database-in-django) This is my code: My model("ingredient") uses: title = models.CharField(max_length=50, primary_key=True) pictureLink = models.ImageField(upload_to="media") The pictureLink I provided in my database is: C:\Users"Me"\Desktop"project"\image\leaves.png My views.py contains: def say_hello(request): allimages = Ingredient.objects.all() return render(request, 'hello.html',{'images' : allimages}) My HTML code is the following: {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="{{ingredient.pictureLink.url}}" width="120"/></td> </tr> {% endfor %} In settings.py I put the following: BASE_DIR = Path(file).resolve().parent.parent MEDIA_ROOT = os.path.join(BASE_DIR, 'image') MEDIA_URL = '/image/' Does anyone know where i'm making a mistake? I'm a beginner with Django, so all feedback is appreciated! -
How to best pass converted values of a Django model to context?
I have a model Poller that has a bunch of integer fields. I have a function convert_thousands that converts integer figures into short strings like so: convert_thousands(1300000) # Returns '1,3 m' etc. How to best convert alle of the integer fields and pass them into the context? Right now I'm doing it one by one by one..: Foo = convert_thousands(poller.integerfield_one) Bar = convert_thousands(poller.integerfield_two) [..] context = { 'poller': poller, 'Foo': Foo, 'Bar': Bar [..] } Desired outcome would look s.th. like [..] context = { 'poller': poller, 'converted_strings': converted_strings } and render by {{ converted_strings.integerfield_one }} -
How to get Django to redirect to the requested page with the LoginRequiredMixin after logging in?
Background: I have an inventory application that scrapes through our VM and storage environments to index things for my team to have some quick references without having to log into vCenter/Storage systems directly to get info. Since it's dealing with some potentially sensitive info, I put authentication on it by way of using the LoginRequiredMixin in my Views classes. The authentication part has been in for a while and it works without issues. The part where I get stuck on is I implemented the next parameter in the login form, and it shows up in the URL when it prompts to login. I have a different view class for each kind of thing I'm tracking. Goal: When someone clicks on a link that requires authentication (basically every page except the main page), it redirects them to the page they want after requiring them to login. I've seen a few other questions, but the recommendations mentioned haven't worked in my case for whatever reason. I've tried various implements of the redirect_field_name but it still ends up trying to redirect to /accounts/profile if I don't have it overridden in the settings page. I don't have the login_url field set, but the login … -
Django School management system
I want to develop a School management system using Flutter as frontend and django as backend. I'm pretty confused about some things: How do I construct my models so that, students and teachers will be specific to a particular school (so i can have up to 10 schools without having conflicts getting data from the database)? What is the best site to host my app? -
Directs messages in django
I followed a tutorial that shows how to send DMs. there is a way to start a new conversation. but the problem is that with each new conversation it sends 'hello guys'. I want the user to be able to put the message he wants. here is the function new_conversation views.py def new_conversation(request, username): user_sender = request.user message_body = 'Hello guys !' try: user_receiver = User.objects.get(username=username) except Exception as e: return redirect('search-inbox') if user_sender != user_receiver: Message.send_message(user_sender, user_receiver, message_body) return redirect('inbox') how to use a method to input the message ? And also i would like to know what the "except Exception as e" is for, i think that except only would have been enough -
How to force one and only one of two fields to be required in Django?
So here is a Django model example: from django.db import models from django.core.exceptions import ValidationError class MyModel(models.Model): field1 = models.CharField(null=True) field2 = models.CharField(null=True) def clean(self): if self.field1 and self.field2: raise ValidationError( 'Please select only field1 OR field2, not both.') elif self.field1 is None and self.field2 is None: raise ValidationError( 'Please select field1 or field2.') What I want to achieve is to force an admin of my app to choose one and only one field from two which are available. The problem is that my code prevents well against adding new object with both fields chosen, but it does not prevent against adding new object with no fields chosen; the second part works only while admin wants to edit the object without neither field1 nor field2, but it is possible to add it in the first place, which I wish to prevent against. Any ideas how can I fix this? -
How do I create a dependent dropdown form in Django
I've searched far and wide for an answer to this question with no success. I would like to create a simple dependent dropdown form in Django. The first field is to be a 'workout' that is to be selected and the second field should be of models.PositiveIntergerField() with some validators in it coming from the django.core.validators module. I would like this integer to be dependent on the amount of 'exercises' within the chosen 'workout' (exercise has a foreign key to workout). Once a user selects a workout, the amount of exercises is dependent on how many exercises are actually under that workout. So far, I have been able to get the first field but not the integer field. Below are the forms.py, views.py, model.py, and routine.html of my application. forms.py - have it set to where a user can only see the workouts & exercises they have created from django import forms from .models import Workout, Exercise, Routine class RoutineForm(forms.ModelForm): """creates a form for a routine""" def __init__(self, *args, user=None, **kwargs): super().__init__(*args, **kwargs) self.fields['workout'].queryset = Workout.objects.filter(owner=user) class Meta: model = Routine fields = ['workout'] labels = {'workout': '',} views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models … -
Django: div class alert alert-danger does not work properly
My forms.py: class SignUpForm(forms.ModelForm): name = forms.CharField(label="name", required=True, widget=forms.TextInput()) email = forms.CharField(label="email", required=True, widget=forms.TextInput()) password = forms.CharField(label="password", widget=forms.PasswordInput(), required=True) confirm_password = forms.CharField(label="password", widget=forms.PasswordInput(), required=True) def clean(self): cleaned_data = super(SignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: self.add_error('confirm_password', "Password and confirm password do not match") return cleaned_data class Meta: model = get_user_model() fields = ('name', 'email', 'password') My html file: {% block content %} <form method="post"> <div class="sign-card"> <h3>Signup</h3> {% csrf_token %} <div class="input-div"> <label for="{{ form.name.id_for_label }}">Username:</label> {{ form.name }} </div> <div class="input-div"> <label for="{{ form.email.id_for_label }}">Email:</label> {{ form.email }} </div> <div class="input-div"> <label for="{{ form.password.id_for_label }}">Password:</label> {{ form.password }} </div> <div class="input-div"> <label for="{{ form.password.id_for_label }}">Confirm Password:</label> {{ form.confirm_password }} </div> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} <button type="submit" class="btn">Sign up</button> <p>Already have account? <a href="{% url 'login' %}">Log In</a></p> </div> </form> {% endblock %} My views.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('name') password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') user = authenticate(username=username, password=password, email=email) login(request, user) return redirect('index') else: form … -
Filter multiple generic related fields from the same model in djang rest framework
I have two models that correlate each other with GenericRelation(). class Translation(models.Model): """ Model that stores all translations """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.CharField(max_length=50, null=True, blank=True) content_object = GenericForeignKey() lang = models.CharField(max_length=5, db_index=True) field = models.CharField(max_length=255, db_index=True, null=True) translation = models.TextField(blank=True, null=True) class Meta: ordering = ['lang', 'field'] unique_together = (('content_type', 'object_id', 'lang', 'field'),) class Tags(models.Model, Translatable): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) DISEASE = 0 TYPE = [(DISEASE, 'disease')] type = models.PositiveSmallIntegerField(choices=TYPE) name = GenericRelation(Translation) description = GenericRelation(Translation) I am trying to create and filter two fields that have generic relation with the model Translation. class TranslationSerializer(serializers.ModelSerializer): """ Translation serializer to be nested into other serializers that needs to display their translation. """ class Meta: model = Translation fields = "__all__" class TagsSerializer(WritableNestedModelSerializer): name = TranslationSerializer(required=False, many=True) description = TranslationSerializer(required=False, many=True) class Meta: model = Tags fields = ['id', 'type', 'name','description'] def create(self, validate_data): """ Create nested translation. content_type and object_id are added dynamically. """ names = validate_data.pop('name') description = validate_data.pop('description') tags = Tags.objects.create(**validate_data) for n in names: model = self.Meta.model content_type = ContentType.objects.get_for_model(model) n['content_type'] = content_type.id n['object_id'] = tags tags.name.create(**n) for desc in description: model = self.Meta.model content_type = ContentType.objects.get_for_model(model) desc['content_type'] = content_type.id n['object_id'] = … -
Django Rest Framework, How to CREATE or UPDATE object that has a nested serializer as one of its fields
I have two models Product and Variant as follows models.py class Product(models.Model): GENDER = [ ('M', 'male'), ('F', 'female'), ('U', 'unisex'), ] store = models.ForeignKey( Store, on_delete=models.CASCADE, related_name='products') name = models.CharField(max_length=80) slug = models.SlugField(max_length=200, unique=True, blank=True, null=True) description = models.TextField() brand = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) gender = models.CharField(max_length=20, choices=GENDER) image_1 = models.URLField() image_2 = models.URLField() category = models.ForeignKey( 'Category', related_name="products", on_delete=models.CASCADE, null=True, blank=True) return_policy = models.IntegerField(null=True, blank=True) in_warehouse = models.BooleanField(default=False) is_approved = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) is_disabled = models.BooleanField(default=False) is_deleted = models.BooleanField(default=True) score = models.IntegerField(default=0) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name class Variant(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="variants", null=True, blank=True) is_default = models.BooleanField(default=False) price = models.FloatField() old_price = models.FloatField(blank=True, null=True) quantity = models.IntegerField() image = models.URLField() is_deleted = models.BooleanField(default=True) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(null=True, blank=True) def __str__(self): return self.product.name + " variant" I would like to CREATE a product while passing a list of variants so it can automatically create the variants with the product as follows serializer.py class VariantSerializer(serializers.ModelSerializer): image = serializers.ImageField() class Meta: model = Variant fields = ['product', 'is_default', 'price', 'old_price', 'quantity', 'size', 'shoe_size', 'color', 'image'] class ProductSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) image_1 = serializers.ImageField() image_2 … -
Inherit Django choice class to extend it?
I have a field in my models.py that accepts choices determined in a class: from apps.users.constants import UserChoices class User(models.Model): choices = models.CharField(max_length=10, blank=True, choices=UserChoices.choices(), default=UserChoices.PUBLIC) The choice class is this: from django.utils.translation import ugettext_lazy as _ class UserChoices: PRIVATE_USER = "private_user" PUBLIC_USER = "public_user" @classmethod def choices(cls): return ( (cls.PRIVATE_USER, _("Private User)), (cls.PUBLIC_USER, _("Public User"), ) My doubt is how can I inherit this UserChoices class to another choice class, in order to extend it with another options. I tried the following: class ExtendedChoices(UserChoices): OTHER_CHOICE = "other_choice" @classmethod def choices(cls): return ( UserChoices.choices(), (cls.OTHER_CHOICE, _("Other choice")), ) But it gives me a migration error: steps.StepVisibility.gender: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Obviously this example is simplified, the actual code has 40+ choices on the original class and 20+ in the extended one. -
Error running WSGI application , ModuleNotFoundError: No module named 'mysite'. Also Not able to find Static files
I'm trying to deploy my website using pythonanywhere. I've given the correct path in wsgi file which is as follows (see code below). Still I'm Getting No module found error (as title of the post). Also it's not able to find Static files ,however they are at correct location. Wsgi file code { path = '/home/divyanshu964/portfolio/Personal_portfolio/' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Personal_portfolio.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() } Help?? Thanks:) -
my css of update page not loading correctly but other page are working very fine
When I try to render template passing argument with primary key or ID CSS not loading as expected but when I try to render it simply with a request without passing id arg it loads perfectly. viewsy.py def update_lead(request,pk): leads = Lead.objects.get(id = pk) followup = Followup.objects.all agent = Agent.objects.all source = Source.objects.all print(f"the leads are {leads}") context = {"lead":leads,"followup":followup,"agent":agent,"source":source} return render(request,"home/update_lead.html",context) This is how looks at the frontend when I try passing id with my view it is not loading the css which is expepcted it is showing error but if we just remove the use of pk then the css will be loading and it is supposed to look like here is my templates code {% extends 'base.html' %} {% block body %} <div class="container"> <h2>Create Lead</h2> <form action="creat_handle_lead" method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Name</label> <input type="text" class="form-control" id="inputEmail4" required name="name" value="{{lead.name}}"> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Subject</label> <input type="text" class="form-control" id="inputPassword4" name="subject" required value="{{lead.subject}}"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputAddress">Email</label> <input type="email" class="form-control" id="inputAddress" name="email" placeholder="abc@email.com" value="{{lead.email}}"> </div> <div class="form-group col-md-6"> <label for="inputAddress2">Contact Number</label> <input type="number" class="form-control" id="inputAddress2" name="number"value = "{{lead.number}}" placeholder="99XX80XXXX"> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> … -
django postgresql cumulative sum not view
I am trying to make a party ledger. which details will show by a date search result. I have a column name balance which will display cumulative data by the date search. The balance field is a decimal field. I am trying the following in views.py def partyDetails(request,pk): form = DateRangeForm() search = [] until = [] cumbalance = 0.00 if request.method == 'POST': form = DateRangeForm(request.POST or None) if form.is_valid(): search = PurchasePayment.objects.filter(vendor=pk,date__range=( form.cleaned_data['start_date'], form.cleaned_data['end_date'] )) for balancet in search: cumbalance += Decimal(balancet.balance) else: return redirect('party_ledger') return render(request, 'purchase/party_details.html', {'dateform':form, 'party':search,'name':pk, 'cumbalance':cumbalance}) But I am getting error unsupported operand type(s) for += If I try cumbalance += [balancet.balance] then get [Decimal('200000.00'), Decimal('-200000.00')] MY Models.py are given bellow class PurchasePayment(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) invoice = models.CharField(max_length=20) vendor = models.CharField(max_length=50) amount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) discount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) payment = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) balance = models.DecimalField(max_digits=9, decimal_places=2) remarks = models.TextField(blank=True) extra = models.CharField(max_length=100, blank=True) def __str__(self): return self.vendor My HTML <tbody> {% for data in party %} {% for cum in cumbalance %} <tr> <td >{{data.date}}</td> <td >{{data.invoice}}</td> <td >{{data.amount}}</td> <td >{{data.discount}}</td> <td >{{data.payment}}</td> <td >{{cum}}</td> </tr> {% endfor %} {% endfor %} </tbody> How can … -
How to use {{ url '' }} in HTML with a variable for the url reference
I'm working on a project to develop a wiki. I have a page with the list of entries, and I would like each of the entries to be clickable and redirect to the appropriate page. HTML <ul> {% for entry in entries %} <li><a href="{% url 'entry' %}">{{ entry }}</a></li> {% endfor %} </ul> The problem I'm facing is that I'm not sure how to put a variable inside my {% %} to get the href to point to the correct link. I'm not sure if it's helpful but here's the url parameterization as well: urlpatterns = [ path("", views.index, name="index"), path("<str:entry>", views.markdown, name="entry"), path("error", views.error, name="error") ] -
Best approach for tracking POST requests to a set of endpoints in a Django app
There are a few mission critical endpoints in my Django application. I would like to store all POST requests to these endpoints in the database, so we can track these requests. I was thinking of creating a table in the db and creating a middleware that will write a record to this table if the response returns a 200 status code. Does this seems like the best approach? Is there a better approach (e.g. handle this at the view layer, use an existing third-party package, something else entirely)? -
Django Cookies not setting up in browser but working in postman - Django Rest Framework
Hi all I am facing issue with setting cookies to browser. I have hosted my backend to heroku with url http://xxxxxxxxx.herokuapp.com/ and my front end is in local host. http://127.0.0.1:5501. If I try login with django running at my local host 127.0.0.1:8000 then it's working and setting cookies in browser but if I try with heroku one, It's not setting cookies in browser but if try with postman It's working fine. I am unable to figure out this issue. I have already added allowed origins in my backend. Please help me. cors setting ALLOWED_HOSTS = ['127.0.0.1','http://dfit-web.herokuapp.com'] CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' #will be used in enforce_csrf or validating csrf token ACCESS_CONTROL_ALLOW_HEADERS = True CORS_ALLOW_HEADERS = ('content-disposition', 'accept-encoding', 'content-type', 'accept', 'origin','x-csrftoken') # CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:5501", "http://localhost:5501", ] views.py class LoginView(APIView): def post(self,request,format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) response.set_cookie( key = "tokenvalidate", value = data["access"][0:len(data['access'])//2], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = False, samesite = … -
how to request url of that model detail views in search result
I am searching in three model and all model has different detail views and but i am unable to figure out how to tell django to locate the view acc to their model this is my view for seaching in models def search_item(request): results = [] search_item = request.GET.get("search") if search_item: q = Q(title__icontains=search_item) | Q(written_by__icontains=search_item) for model in (crypto, News, Movie): results.extend(model.objects.filter(q)) return render(request, "result.html", {"results": results}) and for that template {% for result in results %} <a class="blog-card" href=""> <div class="card col-4" style="width: 18rem;"> <img src="{{ result.title_image.url }}" class="card-img-top" width="100%" height="200px"> <div class="card-body"> <h5 class="card-title text-center" style="color:black">{{ result.title|truncatewords:7 }}</h5> <p class="card-text text-center" style="color:black">{{ result.info|truncatewords:10 }}</p> <p class="number text-center" style="color: black;"> Wriiten By:<strong> {{ result.written_by }}</strong></p> <p class="last text-center" style="color: black;"> Last update:<strong> {{ result.joined_date }}</strong></p> </div> </div> </a> {% endfor %} and all the model has different detail views, so how to do that urls.py path('crypto/<slug:title>/',views.ttt_read,name="ttt_read"), path('news/<slug:title>/',views.news_read,name="news_read"), path('movie/<slug:title>/',views.movie_read,name="movie_read"), path('penmen/search/',views.search_item,name='search') any help and suggestion will be appreciated -
How to get the BooleanField of a model which is True if and only one can be true at all in Django?
I have the following model which has two boolean fields. Due to my logic, they won't be both true at anytime. How can I get the field which is True in a simple straight forward way? class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) def __str__(self): return f'Vote by {self.user}' This is how I'm doing it right now: voted_for = Vote.objects.get(poller_id=poller_id, user=request.user) is_true = voted_for.poller_choice_one_vote is_also_true = voted_for.poller_choice_two_vote if is_true: voted_for = voted_for.poller_choice_one_vote elif is_also_true: voted_for = voted_for.poller_choice_two_vote else: pass -
Djongo/PyMongo keeps creating new DB connections for Django REST framework API requests
I'm experiencing an issue with djongo when used with Django REST framework where it initiates a new connection with my MongoDB at every request except for the very first one after starting the webserver. This means the first request to my Django API is fast (~80 ms) but all the following requests are significantly slower (~800 ms) because they all initiate a new connection. When profiling the requests I can see that pymongo\pool.py:950(_create_connection) and pymongo\pool.py:1263(connect) are present in each request except for the first one, which I assume means the first request uses the pre-initiated DB connection, but all the others have to create a new connection, hence why it's so slow. I'm also seeing huge spikes of connections in my MongoDB dashboard, there should be only 1 connection, but when I'm testing this it suddenly gets up to 50+ connections, and even when I shut down the webserver, the connections only drop by one and plenty of zombie connections remain that only die after some timeout. Here are the profiling results for the first and second request. I can't figure out if it's an issue with django, djongo, pymongo or djangorestframework. For the installation and configuration, I've followed the … -
django.db.utils.ProgrammingError: constraint already exists
so i am trying to make my custom migration file to make partitions for my tables ,i have create a custom CreatePartitionedModel to do the work for me however i keep having a a db.utils.ProgrammingError saying that i have duplication in my constraints: django.db.utils.ProgrammingError: constraint "summary_result_id_d5ba54ba_fk_token_id" for relation "summary" already exists My custom CreateModel : class CreatePartitionedModel(CreateModel): def __init__(self, name, fields, partition_sql='LIST(lang)', **kwargs): self.partition_sql = partition_sql super().__init__(name, fields, **kwargs) def database_forwards(self, app_label, schema_editor, from_state, to_state): collector = type(schema_editor)( schema_editor.connection, collect_sql=True, atomic=False ) with collector: super().database_forwards( app_label, collector, from_state, to_state ) collected_sql = collector.collected_sql schema_editor.deferred_sql.extend( collector.deferred_sql ) model = to_state.apps.get_model(app_label, self.name) create_table = 'CREATE TABLE %s' % schema_editor.quote_name( model._meta.db_table ) all_langs = ['en','fr','ar','es','da','de','it','ja','nl','pl','pt','ru','zh'] langs_partition = "" for sql in collected_sql: if str(sql).startswith(create_table): for lang in all_langs: langs_partition+=f"create table {self.options['db_table']}_{lang} partition of {self.options['db_table']} for values in ('{lang}');" primary_keys = ",primary key (id ,lang ),unique ( lang, id))" sql = sql.replace("serial NOT NULL PRIMARY KEY","serial NOT NULL") sql = '%s %s PARTITION BY %s; %s' % (sql.rstrip(');'), primary_keys,self.partition_sql, langs_partition) schema_editor.execute(sql) and this is my migration file and the table that i have problems in: CreatePartitionedModel( name='Summary', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('base', models.CharField(max_length=255)), ('pattern', models.CharField(max_length=255)), ('lang', models.CharField(max_length=255)), ('frequency', models.IntegerField()), ('relevance', models.FloatField(null=True)), ('count', … -
How to search for substring in array of JSON Field?
I'm using a JSONField provided by Django and I store this type of data in that field: [ { "number": 1, "text": "This text is about dogs" }, { "number": 2, "text": "Only cats in this text here" }, { "number": 3, "text": "However, this text does also contain dogs" }, ] What I'm trying to achieve is some sort of substring match - ie, if a person searches for the string "dog", the result should return something like: { "number": 1, "text": "This text is about dogs" }, { "number": 3, "text": "However, this text does also contain dogs" }, Looking at the Django docs, it seems possible to query for JSON fields, as such Model.objects.filter(field__text__contains='dogs') However, contains only works for single dictionary values, not when there is an array of dictionaries. Any tips? Either through the Django ORM or through Postgres straight up. -
How To Fix TemplateDoesNotExist at /agents/ agents/agents_list.html, leads/agent_list.html
How To Fix I Saw A Directory and everything is right but i still get same error TemplateDoesNotExist at /agents/ agents/agents_list.html, leads/agent_list.html Code class AgentListView(LoginRequiredMixin, generic.ListView): template_name = "agents/agents_list.html" def get_queryset(self): return Agent.objects.all()