Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form - How to autofill fielf from another
I would like to autofill my Kpi fieldd by extracting its value in the name field For example : here kpi = name.split("-")[6] which equal to CPC string. How can I do that please? class UserCampaigns(models.Model): dsp_choices =( ('Amazon', 'Amazon'), ('Amobee', 'Amobee'), ('AppNexus', 'AppNexus'), ('Digiteka', 'Digiteka'), ('DV 360', 'DV 360'), ) kpi_choices = ( ('CPA', 'CPA'), ('CPC', 'CPC'), ('CPD', 'CPD'), ('CPL', 'CPL'), ('CPM', 'CPM'), ('CPV', 'CPV'), ('CTR', 'CTR'), ('Vsibility', 'Visibility'), ('VTR', 'VTR'), ('LTR', 'LTR'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ForeignKey(CampaignNamingTool, on_delete=models.CASCADE) dsp = models.CharField(max_length=30, choices=dsp_choices) budget = models.DecimalField(max_digits=20, decimal_places=2) kpi = models.CharField(max_length=10) #choices=kpi_choices) start_date = models.DateField() end_date = models.DateField() -
Upload Image using nextJs fail with 415 Unsupported Media Type
I am trying to send a POST request (with an image) to a /api/service/register. Request is sent via fetch api in this way: (formData is an useState) ... const [photo, setPhoto] = useState(null) const onChange = (e) => ( upDatePhoto(e.target.files[0]) ) const onSubmit = async (e) => { e.preventDefault() const body = new FormData() body.append('name', name) body.append('photo', photo) body.append('email', email) body.append('phone', phone) body.append('description', description) try { const res = await fetch('/api/service/register', { method: 'POST', body: body }); ... but i get this error 415 Unsupported Media Type It seems that when I get req.body, I got nothing register.js export default async (req, res) => { ... const apiRes = await fetch(`${API_URL}/ServiceOwners/register/`, { method: 'POST', headers: { 'Authorization': `Bearer ${access}`, }, body: req.body }); ... when i print req.body i get this format ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="name" test test ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="photo" blob:http://localhost:3000/3a6396ef-c0b3-4b7c-8dd5-13f581f0ff59 ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="email" testtest@gmail.com ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="phone" 03 43 55 21 00 ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="description" test ------WebKitFormBoundaryebJPBXTlpiCCQCeA-- I'll show more code if needed. Thanks -
Django form that updates multiple records
I have 2 classes of users who can view a screen that lists all users in my app. The type of user is controlled by a Boolean field on the User model. The screen currently lists out the Users and various details about them (see below). Project Managers should see a read only view of the page where as Administrators should have the ability to edit the Users as well. HTML for the screen. <div class="card-body"> <div class="table-responsive"> <table class="table text-sm mb-0"> <thead> <tr> <th>#</th> <th>Username</th> <th>First Name</th> <th>Last Name</th> <th>Is Contributor?</th> <th>Is Project Manager?</th> <th>Is is_administrator?</th> </tr> </thead> <tbody> {% for user in users %} <tr> <th scope="row">{{ user.id }}</th> <td>{{ user.username }}</td> <td><a class="btn btn-primary" href=" " role="button">{{ user.first_name }}</a></td> <td>{{ user.last_name }}</td> <td>{{ user.is_contributor }}</td> <td>{{ user.is_projectmanager }}</td> <td>{{ user.is_administrator }}</td> <td><a class="btn btn-info" href="" role="button">Edit</a></td> <td><a class="btn btn-danger" href="" role="button">Delete</a></td> </tr> {% endfor %} </tbody> </table> </div> </div> I want to create a version of the screen available to admin users which allows them to view and update users all at once. How can I create a form that updates all the users at once? I'm looking to build something that lists out the users with … -
Send request to Schema Marshmallow + Django
I have a view : class ArticlesListView(APIView): authentication_classes = (JWTAuthentication,) def post(self, request, *args, **kwargs): """Post an Article.""" try: schema = ArticleSchema() article = schema.load( json.loads(request.body)) schema.context = {'request': request} except ValidationError as e: return json_response(e.messages, 400) return json_response(schema.dump(article), 201) which posts, though I wanted to send a request to the ArticleSchema() how can I do this ? Below is the schema : class ArticleSchema(Schema): class Meta(object): model = Article id = fields.Integer() title = fields.String(validate=validate.Length(max=255)) content = fields.String() regions = fields.Method( required=False, serialize="get_regions", deserialize="load_regions" ) @post_load def update_or_create(self, data, *args, **kwargs): print(" args ", args) print(" kwargs ", kwargs) regions = data.pop("regions", "") title = data.pop("title", "") content = data.pop("content", "") user = User.objects.get(id=1) article, _ = Article.objects.update_or_create( id=data.pop("id", None), owner=user, title=title, content=content, defaults=data ) if isinstance(regions, list): article.regions.set(regions) return article -
how do you iterate through two items in a model and display on site using Django?
I have a models.py with the following fields: class ChatStream(models.Model): bot = models.TextField() user = models.TextField() name = models.CharField(max_length=100, null=True) created_date = models.DateTimeField(auto_now_add=True) And I'd like on a website to iterate through "bot" and "user" one at a time, so the site would hypothetically display something like: bot: hello! user: what's up? bot: I'm good user: What's your name bot: bot is my name .... etc. this would keep going... So in my views.py I have def displayDict(request): m = ChatStream.objects.all() return render(request, 'chatStream.html', {"chat": m}) def send(request): message = request.POST.get('userMessage', False) ip = visitor_ip_address(request) response = routes(message, ip) print(ip, "user sent:", message, "bot response:", response) chatItem = ChatStream(bot=response, user=message, name=ip) chatItem.save() return HttpResponseRedirect('/chat/') Then in my template, chat.html I have {% block chatStream %} {% endblock %} And chatStream.html: {% extends 'chat.html' %} {% block chatStream %} {% for a in bot%} {% for b in user%} <p> <b>bot:</b> {{a}} <br> <b>user:</b> {{b}} <br> </p> {% endfor %} <form action="/send/" method = "post">{% csrf_token %} <input type="text" name="userMessage"> <input type="submit" value="Send to smallest_steps bot"> </form> {% endblock %} But this does not work -- no text from the model is displayed on the site. thank you -
django import-export adding an emailValidator adds a new field on export
I have these models: Investment Profile wherein Investment has a foreign key to Profile through email. I'm trying to bulk export but the export adds a duplicate profile__email without any values. Sample result: I noticed its from the added validator in my InvestmentResource: class InvestmentResource(resources.ModelResource): class ValidatingEmailForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row=None, *args, **kwargs): try: validate_email(value) except ValidationError as e: # a quirk of import-export means that the ValidationError # should be re-raised raise ValueError(f"invalid email {e}") try: val = super().clean(value) return value except self.model.DoesNotExist: raise ValueError(f"{self.model.__name__} with value={value} does not exist") email = fields.Field(attribute='profile__email', widget=ValidatingEmailForeignKeyWidget(Profile, field='email'), column_name='profile__email') class Meta: model = Investment clean_model_instances = True import_id_fields = ('id',) fields = ( 'id', 'notes', 'firstname', 'lastname', 'email',) export_order = fields def before_import_row(self, row, row_number=None, **kwargs): self.profile__email = row["profile__email"] self.profile__firstname = row["firstname"] self.profile__lastname = row["lastname"] def after_import_instance(self, instance, new, row_number=None, **kwargs): """ Create any missing Profile entries prior to importing rows. """ try: # print(self.isEmailValid(self.email), file=sys.stderr) profile, created = Profile.objects.get_or_create(email=self.profile__email) profile.firstname = self.profile__firstname profile.lastname = self.profile__lastname profile.save() instance.profile = profile except Exception as e: print(e, file=sys.stderr) If I try to remove the validator and change email in fields to profile__email, the fields exported are what is expected, but when importing, the emails … -
GitHub CI Test Error: relation does not exist. (DRF as BE)
I am working on a project based on Django Rest Framework and I got some CI Test errors when I try to merge my branch to main. Before I merge to main, I have already made some Django Unit Tests and they all can pass locally. (My database is postgres) Here is the error detail: Here is the CI Test Error I have never face this error locally. I tried to re-migration and migrate the database but it still fails in CI test. Dose this because CI test and Django test have different operation logic? Or is it because I have a problem with the processing of the postgres? This is my first question on stackoverflow, appreciate for any reply! -
Render Python seaborn Plot on Django Template
I am trying to render the plot generated by seaborn on Django template. I have the following code in my views.py: def booking_hour_plot(): qs = bookings_today() df = read_frame(qs) plot = sns.countplot(data=df) return plot def render_stats_page(request): #general info user_count = total_users_until_now() cancel_rate = activity_cancel_rate() #activity/booking details activity_set = activities_today() booking_set = bookings_today() plot = booking_hour_plot() return render(request, "stats.html", {'name':'Avonmore Statistics', 'total_user':int(user_count), 'cancel_rate': round(float(cancel_rate), 2), 'booking_count_today': booking_set.count(), 'activity_count_today': activity_set.count(), 'activities_today': activity_set, 'bookings_today': booking_set, 'booking_hour_plot': plot, }) And I have a html template called stats.html that containing the plot. The templates directory and views.py are in the same directory: <li>Real Time Plot: {{booking_hour_plot}}</li> However, the rendered html page is not really showing the plot. It's more like the plot object: enter image description here Any Idea how to put the real plot on the html page, rather than this plot object? -
dlib makes videostream laggy on django
im pretty new in codes and i just start new project using django opencv and dlib. My project have face recognition feature so i use opencv videostream. But i got problem with videostream becomes so laggy everytime i try to call dlib face detector, not only the face detector but whenever i tried to call another dlib's function the videostream still lag. Im using my laptop webcam for the project, is it does also affecting the codes? Can anyone help me? I've been stuck for week and still not found the answer:( -
Strange "on" type being recorded in MySQL database (Navicat Premium) in Django
I have been trying to insert information with an HTML form into my database. However, when I submit, my "gender" and my "website_rating" has been strangely replaced with "on", when it is supposed to be replaced with my website input. Image of the Database: https://i.stack.imgur.com/94d8L.png Here is my models.py # _*_ coding:utf-8 _*_ from __future__ import unicode_literals from django.db import models """ Quick Guide to Model Fields that We Did Not Use: - models.ForeignKey() - models.DateTimeField() - models.IntegerField() - models.IPAddressField() - models.FileField() - models.ImageField() """ # Create your models here. class PersonalInfoResponse(models.Model): # Personal Info Section name = models.CharField(max_length=30, null=True, default="N/A", verbose_name=u"Name") age = models.IntegerField(verbose_name=u"Age", default="N/A", null=True) email = models.CharField(max_length=30, null=True, default="N/A", verbose_name=u"text#@thing.com") gender = models.CharField(max_length=7, null=True, verbose_name=u"gender") # Website Response Section website_rating = models.CharField(max_length=3, verbose_name=u"1-10", null=True) heardof_flag = models.BooleanField(verbose_name=u"truefalse", null=True) heardof = models.CharField(max_length=255, null=True, verbose_name=u"How did you know about the C&C Education Center?") # Misc Section fav_subject = models.CharField(max_length=50, null=True, default="None", verbose_name=u"truefalse") fav_website = models.CharField(max_length=255, null=True, default="N/A", verbose_name=u"What is your favorite part about this website?") website_improve = models.CharField(max_length=255, null=True, default="N/A", verbose_name=u"What is something that this website needs improvement on?") class Meta: verbose_name = u"User Contact Info" verbose_name_plural = verbose_name And here is my views.py from django.shortcuts import render from … -
Django-vimeo 'NoneType' object is not iterable
Model structure is like below: class Video(models.Model): video_header = models.CharField(max_length=350, verbose_name="Video Başlığı", blank=False, null=False) video_description = models.TextField(verbose_name="Video Açıklaması", blank=False, null=False) date_created = models.DateField(auto_now_add=True, verbose_name="Oluşturma Tarihi", blank=False, null=False) video = fields.VimeoField(null=True, blank=True) def __str__(self): return self.video_header class Meta: verbose_name = "Video İçeriği" verbose_name_plural = "Video İçerikleri" When I click on any video object which created in django admin to edit it, get " 'NoneType' object is not iterable " error. But actually there is a object and it is not "None" when I look at database and also checked it in frontend. So it seems like meanless to me. Could you please help me to get through this problem. -
Custom save method with condition in django model
I am trying to do a django project where a user can describe pictures using one or more taggings, as soon as more than one user has entered the same tagging for the same picture, this word or tagging should be saved to the Tag table. I thought I can solve this by adding a custom save method to the Tag model. Would this be the right approach or would I write this logic inside a view? class Tag(models.Model): LANGUAGES = (('en', 'english'), ('de', 'deutsch'), ('fr', 'francais') ) name = models.CharField(max_length=256) language = models.CharField(max_length=256, choices=LANGUAGES) class Tagging(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, blank=True, default='') picture = models.ForeignKey(Pictures, on_delete=models.CASCADE, related_name='taggings', default='') tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) -
Get data from external URL in JSON format with Django REST
I want to do simple Rest API in Django. It's my first approach to Rest in django, but for now it isn't going that bad ;) For now I have a model database with two fields brand and model. With the use of Postman, I can GET, POST and DELETE objects, cool. But what I'm stuck with is -> When I POST an object, first I'd like to check if that model with given brand even exists. I want to check it on specific website: link. (In the URL of that website I can change brand name so it gives me a list of model with given brand) My approach would be, when request.method=='POST' first GET data from website, load it to a model and then somehow compare it with data in POST request. But I don't know how to get to that point :) Is it a good approach or is there a way to directly look at data on the given website? (For me there is no need to give you my code, because there is nothing special in it, but tell me if I'm wrong!) -
How to run a rabbitMQ script in a django rest framework project
So I have a django rest framework project, and what I want to do, is to push into a rabbitMQ queue some values from a file with a python script, and as soon as my django server starts running, I want the project to start consuming the messages available in the queue, and with those values, insert entities in my database. So here is my producer python script: import pika, csv, time url = 'queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') with open('sensor.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter='\n') for row in reader: channel.basic_publish(exchange='', routing_key='hello', body=row[0]) print(row[0]) time.sleep(1) connection.close() This script doesn't belong to the django project, I will run this script outside of it. This is my consumer script: import pika from app.models import Measurement url = 'queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): measurement = Measurement.objects.create(sensor=3, energy_consumption=float(str(body))) measurement.save() channel.basic_consume('hello', callback, auto_ack=True) channel.start_consuming() connection.close() I want to integrate this consumer script inside my django project, so that as soon as I start putting messages in my queue with the procuder script, the consumer script is ready for them, intercepts them and inserts a new entity … -
("Django tried these URL patterns... The empty path didn't match any of these.") How to fix "Page not found (404)" error
I am using the visual studio code for the basic Django project and whenever I try to run the server it gives the error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in startup.urls, Django tried these URL patterns, in this order: login/ admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Whereas I write the code correctly landing app folder views file code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def loginpage (request): return render (request, 'login.html') landing app file urls.py code from django.contrib import admin from django.urls import path from. import views urlpatterns = [ path('login/',views.loginpage, name="login" ), landing app file login.html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <h1> Login </h1> </body> </html> main project urls.py file code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('login/',include('landing.urls')), path('admin/', admin.site.urls), ] Please help me regarding this. -
Google Cloud Django if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): not working
I am working on a Google Cloud Django Project. I am trying to check in settings.py if I am running in Development or Production mode. I added the following block of code to test if the SOFTWARE where the program is running either is on my machine or on Google Cloud Servers. # | settings.py | if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): #code to execute in production else: #code to execute in development I noticed that the if statment is always false, so I decited to debug the os.environ dict. The result of the debug is that the value of the key SERVER_SOFTWARE of the enviroment is equal to gunicorn/20.1.0. As written in the correct answer of this stackoverflow question, when running on production (so on Google Cloud Severs App Engine), the value of SERVER_SOFTWARE should be Google App Engine/X.Y.Z, where X, Y and Z represent the version of Google Cloud. But, as I said, my value, when running on App Engine, is not like that, it is gunicorn/20.1.0. So, how do I make the program know if I am running either in development or production? -
Why DRF IsAuthenticatedOrReadOnly class permission class allowing Post method
I am performing test on Django rest framework, here is my view, class PostList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly,] queryset = Post.postobjects.all() serializer_class = PostSerializer Url pattern like bellow, urlpatterns = [ path('<int:pk>/',PostDetail.as_view(),name="detailcreate"), path('',PostList.as_view(),name="listcreate"), ] Here is my test : def create_post(self): self.test_category = Category.objects.create(category='django') self.test_user = User.objects.create_user(user_name="test_user",password="123456789") data = {"title": "new", "author": 1, "excerpt": "new", "content": "new"} url = reverse('api:listcreate') response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) i ran followiing command: coverage run --omit='*/myvenv/*' manage.py test and get output : Ran 1 test in 0.215s OK as my understanding, as here permission class is [IsAuthenticatedOrReadOnly,] , self.client should not have permission to post and test should Failed. I don't understand what i am missing here. -
Djange NoReverseMatch error - reverse for 'edit' with no arguments not found
In a Django app I am building for a course, I am attempting to pass a parameter from one template to a function in views.py through a url path. The path definition in urls.py contains the parameter name, and the same name is required by the function in views.py. The link in my template points to the correct url path and names a value for the parameter, but I am still receiving a NoReverseMatch error. Weird because I have another url path that requires a parameter and which is working perfectly. entry.html Here is the link to the path called edit in urls.py. I want to pass the value of the variable entryTitle to the url as entry: {% extends "encyclopedia/layout.html" %} {% block title %} {{ entryTitle }} {% endblock %} {% block body %} {{ entry|safe }} <button> <a href="{% url 'edit' entry=entryTitle %}">Edit Entry</a> </button> {% endblock %} urls.py the edit path is the last one defined in urlpatterns from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry"), path("search", views.search, name="search"), path("new", views.new_page, name="new"), path("wiki/edit/<str:entry>", views.edit, name="edit") ] views.py This is the edit function, requiring entry as an argument … -
Django: The Model could not be created because the data didn't validate. error
I'm trying to create an app to import thanks to an uploaded .csv file data to my database. This is my code and when I try to submit a new file I'm getting this error The Dataset could not be created because the data didn't validate. I can't also access the file If I create it in admin because I get this error Dataset matching query does not exist. I think my problem is within the ForeignKey and the OneToOneField that I'm not able to save properly? Or that I'm not actually creating a new Dataset atl all? Only the model File is compiled by the user, while Dataset should be filled from the information in the file and linked to the file and the user automatically . Thank you all for your help! VIEWS @login_required def file_upload(request): data = None if request.method == 'POST': file_form = FileForm(request.POST, request.FILES) data_form = DatasetForm(request.POST, request.FILES) raw_file= request.FILES if file_form.is_valid() or data_form.is_valid(): data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") data_form.instance.user = request.user.profile file_form.instance.user = request.user.profile file_form.instance.filename = raw_file['file_upload'].name Dataset.objects.create( name_user_A = data.iloc[0,1], name_user_B = data.iloc[1,1], [...] ) data_form.save() file_form.save() return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': … -
Revoking Celery task causes Heroku dyno worker timeout
My Django API app has a view class that defines a post and a patch method. The post method creates a reservation resource with a user-defined expiration time and creates a Celery task which changes said resource once the user-defined expiration time has expired. The patch method gives the user the ability to update the expiration time. Changing the expiration time also requires changing the Celery task. In my patch method, I use app.control.revoke(task_id=task_id, terminate=True, signal="SIGKILL") to revoke the existing task, followed by creating a new task with the amended expiration time. All of this works just fine in my local Docker setup. But once I deploy to Heroku the Celery worker appears to be terminated after the execution of the above app.control.revoke(...) causes a request timeout with an H12 error code. 2021-11-21T16:39:35.509103+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=PATCH path="/update-reservation-unauth/30/emailh@email.com/" host=secure-my-spot-api.herokuapp.com request_id=e0a304f8-3901-4ca1-a5eb-ba3dc06df999 fwd="108.21.217.120" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https 2021-11-21T16:39:35.835796+00:00 app[web.1]: [2021-11-21 16:39:35 +0000] [3] [CRITICAL] WORKER TIMEOUT (pid:5) 2021-11-21T16:39:35.836627+00:00 app[web.1]: [2021-11-21 16:39:35 +0000] [5] [INFO] Worker exiting (pid: 5) I would like to emphasise that the timeout cannot possibly be caused by calculation complexity as the Celery task only changes a boolean field on the reservation resource. For reference, … -
Why can't I serve my static files to Django?
Before anyone marks this as a duplicate I have seen all of the other questions on similar topics and tried all of the solutions without effect. My Django application is small and I am happy to serve the static files from the same server In settings.py I have STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have uploaded my application to the server and run python.manage.py collectstatic All of my static files are in the appropriate directories under staticfiles project-root ├── staticfiles │ ├── css │ │ ├── base.css │ ├── js │ │ ├── common.js In my html I have {% load static %} <link href="{% static 'css/base.css' %}" rel="stylesheet"> On loading the page I get the error Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I think this is because it cannot filed the css file Where am I going wrong? Do I need to provide any more information? -
How do I display a img in html (django)
html file: <!DOCTYPE html> <html> <head> <title>Resume Homepage</title> </head> <body> <img src="main_photo.jpg" alt="Image Unable To Be Displayed"> </body> </html> Note the photo is in the same directory as the html file so why wont it display ? I keep just getting 404 errors. I am also near positive the name of the photo file is correct as its very simple how could I mess that up. -
Django admin object already exists, when using Django 4 functional unique constraints
When creating a new object from Django Administration site, I'm getting an error "Tag with this already exists.". I suppose this is related to the contraints put on the model. However, creating a Tag object with code - e.g. Tag.objects.create(...) - works fine. It only fails in Django admin. Any idea why ? Note: I'm using functional unique constraints introducted in Django 4.0 (https://docs.djangoproject.com/en/dev/ref/models/constraints/#django.db.models.UniqueConstraint). I'm wondering if I shoud raise a bug? This is my model: class Tag(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('user')) name = models.CharField(max_length=50, db_index=False, verbose_name=_('name')) slug = models.SlugField(max_length=50, verbose_name=_('slug')) class Meta: ordering = ['name'] # Create an index to make tags unique per user and also an index on lowercase name to prevent inserting duplicate tags with varying case constraints = [models.UniqueConstraint(fields=['user', 'name'], name='unique_tags_per_user'), models.UniqueConstraint(Lower('name'), name='lower_tag_name_idx')] def __str__(self): return self.name This is the admin configuration: @admin.register(Tag) class TagAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'name', 'slug') list_display_links = ['pk'] fields = ('user', 'name', 'slug') list_filter = ('user__email',) search_fields = ('name',) prepopulated_fields = {'slug': ('name',)} -
How to get objects that contain a specific string
I want to retrieve objects that contain a specific string in their CharField. In normal Python without Django, I can do this to check: if "something" in string: pass However, I don't know how to do so using .filter() in Django: posts = Post.objects.filter(field = "string") # how can I do something like 'in' here? I don't just want to get objects that have exactly the value as "string". Please teach me how to retrieve objects that contain a specific string in Django using .filter(). -
Derived (Calculated) Field From Another Model
I have started a simple entry-level django project for practicing, it uses sql-server as the database (mssql-django). How can I have a derived attribute (calculated column) from a different table as a field on my model? Let's say I have this model from django.db import models class Person(models.Model): name = models.CharField(max_length=50) birth_date = models.DateField() class JobTitles(models.Model): job_title = CharField(max_length=20) class Jobs(models.Model): job_id = models.OneToOneField( JobTitles, on_delete=models.CASCADE, ) person_id = models.ForeignKey( Person, on_delete=models.CASCADE, ) job_income_in_usd = models.IntegerField() class Salary(models.Model): person_id = models.ForeignKey( Person, on_delete=models.CASCADE, ) name = 'SELECT name FROM Person WHERE Salary.person_id = Person.id' income_in_euro = 'SELECT job_income_in_usd * 0.89 FROM Jobs INNER JOIN Salary ON Salary.person_id=Jobs.person_id' age = 'SELECT datediff(year, (SELECT birth_date FROM Person WHERE Salary.person_id=Person.id), getdate())' How do I implement the above SELECT codes in Python-Django codes? Related questions: Derived attribute in Django model How to add a calculated field to a Django model Django getting field names from different models Related SQL-Server question: How to create derived attribute?