Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i make a query that groups first column and attach any of the rows of second column within each group
I new in sql and I have a postgresql database which has: Table name1 name2 name3 group1 subgroup_A element1 group1 subgroup_B element2 group1 subgroup_C element3 group2 subgroup_D element4 group2 subgroup_E element5 group2 subgroup_F element6 group2 subgroup_G element7 group3 subgroup_H element8 group3 subgroup_I element9 I need to get just 3 rows from db | name1 | name3 :-------|------------ |group1 | element1 (or element2, element3. it doesnt matter) |group2 | element4 (or element5 .. element7. it doesnt matter) |group3 | element8 (or element9. it doesn`t matter) database has more than 300000 rows. I tried to use: select distinct name1 from Table I got | name1 | :-------|------------ |group1 |group2 |group3 but how to add any of the name3 inside each group What is the best way to do this in SQL and in 'django orm'? -
django admin connect two model in creation
I have three models class Voting(Model): id = ... class Candidate(Model): voting = ForeignKey(Voting, on_delete=DO_NOTHING) class Commands(Model): voting = ForeignKey(Voting, on_delete=CASCADE, verbose_name="Votación") candidate = ForeignKey(Candidate, on_delete=CASCADE) And I did this en model admin class CommandInline(admin.TabularInline): model = Commands extra = 1 @admin.register(VotingCandidate) class VotingCandidateAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['voting', "name"]}), ('Mensajes', {'fields': ['default_messages', 'votge_ok_mesage', 'vote_error_mesage', ], 'classes': ['collapse']}), ] inlines = [CommandInline] But when I press Save I get this error: Exception Type: RelatedObjectDoesNotExist Exception Value: Commands has no voting. How I can put in command.voting_id the value of andidate.voting_id in order to can save one Candidate and the cmmands? -
How to add likes to my blog posts using generic relationships in Django
I'm trying to add a like/dislike functionality in Django using generic relationships. Can someone help me? My post model class Post(models.Model): title = models.CharField(max_length=225) post_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) class Meta: ordering = ['-post_date',] def get_absolute_url(self): return reverse('post-detail', args=(str(self.id)),) Thanks in advance! -
Django Channels long running consumer authentication issues
When using django channels, I have a long-running websocket connection. My users may become logged out due to their session expiring while this connection is still active. This causes sporadic behavior where HTTP requests don't work, because they're not authenticated, but the websocket is still sending and receiving data like nothing is wrong. The Django Channels docs say: If you are using a long running consumer, websocket or long-polling HTTP it is possible that the user will be logged out of their session elsewhere while your consumer is running. You can periodically use get_user(scope) to be sure that the user is still logged in. However, this doesn't work. When I call the following code I'm able to see that Django Channels believes the user is still authed. user = async_to_sync(get_user)(self.scope) print(user.is_authenticated) What is the correct way to check if a user is still authenticated in a Django Channels websocket consumer? This GitHub issue touches on the issue but doesn't have a good solution Websocket consumer as follows: class GUIConsumer(WebsocketConsumer): def connect(self): async_to_sync(self.channel_layer.group_add)( GROUP_NAME, self.channel_name) user = self.scope.get('user') if user and user.has_perm('auth.can_access_ui'): self.accept() else: self.accept() self.close() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( GROUP_NAME, self.channel_name) def data(self, event): publisher_type = event.get('publisher') data = event.get('data') … -
Django admin list display with dynamic callable
I have a django project which create lots of reports, and each user has different permissions to view different report. And now I have a admin page which summarize all the user permissions for all reports, and I did it by sth similar to this: class userAdmin(admin.ModelAdmin): def report1_perm(self, user): return user.has_perm('report1') def report2_perm(self, user): return user.has_perm('report2') list_display=['report1_perm', 'report2_perm'] Now instead of having to def a diff method for each report, I want to make callables from the list of reports I have, but I am having trouble to figure out what to pass to the list_display, I have played with setattr or name but they do not seem to work. -
How To Filter By Last 3 Months In Django
What is the best way to filter a DateField by the last 3 months in django. #post_list = Post.objects.filter(release_date=three_months_ago) Here is some relevant info: models.py: class Post(models.Model): release_date = models.DateField(null=True, blank=True, default=None) -
Problem validating modelformset_factory in Django
I have a problem trying to validate a modelform and, after various tests, I think the problem is with the html template in how the information is displayed. I have 2 models: models.py: class bdAccesorios(models.Model): fdClienteAcc=models.CharField(max_length=35) fdProveedorAcc=models.CharField(max_length=60) fdSkuAcc=models.CharField(max_length=30) fdNombreAcc=models.CharField(max_length=60) fdCostoAcc=models.DecimalField(max_digits=8, decimal_places=2) fdUnidadAcc=models.CharField(max_length=30) fdExistenciaAcc=models.IntegerField() fdAuxAcc=models.CharField(max_length=60, default="0") class bdComponentes(models.Model): fdGrupoComp=models.CharField(max_length=30) fdNombreComp=models.CharField(max_length=60) fdSkuComp=models.CharField(max_length=30) fdExistenciaComp=models.DecimalField(max_digits=8, decimal_places=2) fdDesgloseComp=models.ManyToManyField(bdAccesorios, through="bdComponentesDesglose") fdPertenenciaComp=models.ForeignKey(bdUsuariosAux , on_delete=models.CASCADE) fdAuxComp=models.CharField(max_length=60, default="0") and establish a many to many relationship through a third model to class bdComponentesDesglose(models.Model): fdAccesorioCompDes=models.ForeignKey(bdAccesorios, on_delete=models.CASCADE) fdComponenteCompDes=models.ForeignKey(bdComponentes, on_delete=models.CASCADE) fdCantidadCompDes=models.IntegerField(default=1) fdPrecioTotalAcc=models.DecimalField(max_digits=8, decimal_places=2, blank="true", editable="false") To update bdComponentes I combine two forms forms.py: class fmComponente(ModelForm): class Meta: model=bdComponentes fields='__all__' exclude = ('fdAuxComp', 'fdDesgloseComp') labels = { 'fdGrupoComp': 'Grupo', 'fdSkuComp': 'SKU', 'fdNombreComp': 'Nombre', 'fdPertenenciaComp': 'Cliente', 'fdExistenciaComp': 'Existencia', } class fmComponenteDes(ModelForm): class Meta: model=bdComponentesDesglose fields='__all__' exclude = ('fdComponenteCompDes','fdPrecioTotalAcc',) labels = { 'fdAccesorioCompDes': 'Accesorio', 'fdCantidadCompDes': 'Cantidad', } Then I make a view to update the model views.py: def vwComponenteModificar(request,IDComp): vrModificarComp = bdComponentes.objects.get(id=IDComp) vrModificarCompDes = bdComponentesDesglose.objects.filter(fdComponenteCompDes__fdNombreComp=vrModificarComp.fdNombreComp) vrComponenteForm=fmComponente(instance=vrModificarComp) vrComponenteDesModelForm = modelformset_factory(bdComponentesDesglose, extra=0, exclude = ('fdComponenteCompDes','fdPrecioTotalAcc',)) vrComponenteDesForm=vrComponenteDesModelForm(queryset=vrModificarCompDes) if request.method == "POST": vrComponenteForm = fmComponente(request.POST, instance=vrModificarComp) vrComponenteDesForm=vrComponenteDesModelForm(request.POST) if vrComponenteForm.is_valid() and vrComponenteDesForm.is_valid(): ###Here is the problem vrComponenteForm.save() for lpCompDes in vrComponenteDesForm: lpCompDes.save() return redirect('/') return render(request,"DataParagonMain/ComponentesCrear.html",{ 'dtCrearComp': vrComponenteForm, 'dtCrearCompDes': vrComponenteDesForm }) My problem is in my template the view, previously mention, … -
Django homepage on port 8000 not answer
i uploaded a docker-compose with Django and Mysql, and everythings looks okay. docker container ls show both containers running, but Django homepage on port 8000 not answer. I got another one docker-compose with postgres and that works well. What can possibly going on? docker-compose file: version: "3.8" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - '8000:8000' depends_on: - db db: image: mysql:5.7 ports: - '3306:3306' environment: MYSQL_DATABASE: 'djangomysql' MYSQL_USER: 'wendel' MYSQL_PASSWORD: 'wendel12' MYSQL_ROOT_PASSWORD: 'wendel12' -
Crazy number of fields
I want to record 144+ separate pieces of data for every record in my Django database. I think I know that I will need to create a field for each data point but it doesn’t seem very efficient. Is there a more effective way of doing this. It is a scoring system so I need to be able to enter values 1 to 10 as well as x, which counts as 10 and m, which counts as 0. The scores are recorded in groups of 3 or 6 values Any thoughts -
Endless select when two child models of one abstract model in annotation fields
There are two models, which inherit from one abstract model class ProductToStock(models.Model): product = None stock = None qty = models.PositiveSmallIntegerField(db_index=True) price = models.DecimalField(decimal_places=2, max_digits=8, db_index=True) class TireToStock(ProductToStock): product = models.ForeignKey('Tire', related_name='offers', on_delete=models.CASCADE) stock = models.ForeignKey('providers.Stock', related_name='available_tires', on_delete=models.CASCADE) class WheelToStock(ProductToStock): product = models.ForeignKey('Wheel', related_name='offers', on_delete=models.CASCADE) stock = models.ForeignKey('providers.Stock', related_name='available_wheels', on_delete=models.CASCADE) And there is a stock model: class Stock(models.Model): name = models.CharField(max_length=200) I want to select all stocks and get count of tires and wheels on each of them. If I get only one of my counts it's work fine: Stock.objects.annotate( tires_count=Count('available_tires') ) But if I get both counts, I get endless recursive select: Stock.objects.annotate( tires_count=Count('available_tires'), wheels_count=Count('available_wheels'), ) How can I select both counts in one query? -
Django cant return a class based view user id
My goal is to update the view using ajax. when the user enters a value in those 3 fields and save those fields to the database with for this user. I have a user model with 3 text field as follow class Q3Sign(models.Model): title = models.CharField(max_length =255,blank =True) title2 = models.CharField(max_length =255, blank = True) title3 = models.CharField(max_length =255,blank =True) user = models.ForeignKey(User, on_delete=models.CASCADE ) class Meta: db_table = "Q3sign" and my view is as fellow, I am getting the following error when I try to populate the fields. django.db.utils.IntegrityError: NOT NULL constraint failed: Q3sign.user_id class Createcourse(generic.CreateView): model = Q3Sign fields = ['title','title2','title3'] template_name = 'Q3canA/create_course.html' success_url = reverse_lazy('create_course') def create_course(self, request): members = Q3Sign.objects.all() return render (request,'Q3canA/create_course.html' , {'members':members}) def insert(request): member = Q3Sign(title=request.POST['title'], title2=request.POST['title2'], title3=request.POST['title3'], user=request.POST['user.id']) member.save() return redirect('create_course') and here is my html <div class="container"> <h2>Courses</h2> <form method=post> {% csrf_token %} {{ form.as_p}} <input type="submit" value="Create course" /> </form> </div> <form method="post"> {% csrf_token %} <div class="form-inline"> <label>Course 1</label> <input type="text" id="title" name="title" class="form-control"/> </div> <br /> <div class="form-inline"> <label>Course 2</label> <input type="text" id="title2" name="title2" class="form-control"/> <label>Course 3</label> <input type="text" id="title3" name="title3" class="form-control"/> </div> <br /> <div class="col-md-4"></div> <div class="col-md-4 form-group"> <button type="button" class="btn btn-primary form-control" id="submit">Submit</button> … -
Django: AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'
The following error is given to me when i access my localhost:8000/update_item/: "AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'" views.py def updateItem(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order = order, product = product) carrito.js: function updateUserOrder(productId, action){ console.log('Usuario logeado y enviando data...') var url = '/update_item/' fetch (url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId' :productId, 'action' :action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) location.reload() }) } The error is in the following line: data = json.loads(request.data) if i change that line to the following: data = json.loads(request.body) It gives me another error: "JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0)" -
Django crash when upload a big file
I'm trying to send a big file (more than 2.7 GB) with axios to Django: const formData = new FormData() formData.append('myFile', myFile) const config = {...} axios.post(url, formData, config)... Now, it sends all the data, but the memory usage starts growing even before the view starts! def my_vies(request: HttpRequest) -> HttpResponse: print('Starts the view') ... If the file is small the message prints correctly, now with the huge file the server crashes due to memory usage before the print is reached. I've tried to change the upload handler to only use disk in settings.py: FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler'] But had the same result. I don't know whats happening, I can't even try this solution as nothing of the view's code is executed. What I'm missing? Any kind of help would be really appreciated -
How do I change the text "Thanks for spending some quality time with the Web site today." in Django?
When you log out of the Django admin, it displays a string "Thanks for spending some quality time with the Web site today." Can I change that to something else? I was able to change other attributes such as admin.site.site_header = "Whatever" admin.site.site_title = "Whatever" admin.site.index_title = "Whatever" in the urls.py file which worked great so I am guessing this can be changed similarly. Thanks for your help. Tried Google, no dice. -
Dynamically load background image in template
I have a list object as follows: <div role="list" class="w-clearfix w-dyn-items w-row"> {% if latest_post_list %} {% for post in latest_post_list %} {% if post.is_published %} <div role="listitem" class="blog-thumbnail w-dyn-item w-col w-col-4"> <a href="/{{ post.id }}" data-w-id="46150442-4efa-9d36-3a4c-20d527e7a6bc" class="thumbnail-wrapper w-inline-block"> <div class="image-wrapper"> <div style="-webkit-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);-moz-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);-ms-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0)" class="thumbnail-image"></div> <div class="category-tag">{{ post.category }}</div> </div> <div class="thumbnail-text"> <div class="blog-title">{{ post.title}}</div> <div class="preview-text">{{ post.body}}</div> </div> <div class="thumb-details w-clearfix"><img src="" alt="" class="author-img"> <div class="author-title">{{ post.author }}</div> <div class="thumbnail-date">{{ post.pub_date }}</div> </div> </a> </div> {% endif %} {% endfor %} {% else %} </div> <div class="w-dyn-empty"> <p>No items found.</p> </div> {% endif %} </div> The background image is set in stylesheet: background-image: url('https://foo.bar.net/img/background-image.svg'); An image is added to the category model using an Imagefield. class Category(models.Model): created_at = models.DateTimeField('date created') updated_at = models.DateTimeField('date published') title = models.CharField(max_length=255) image = models.ImageField(upload_to='static/images') class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title I would like to have the background image set to be the uploaded category … -
Django Modals, remove non numeric characters from column, CAST as integer then order by
I have database of cards that has a Number field which represents the number of the card in the set. This field is a CharField as some of the cards have their number followed by a symbol to represent different versions of the same card. I would like to order my data using this field however it orders weird due to the field being a string. For example; 1, 10, 100, 101, 102... code: def cards_page(request): card_list = Card.objects.exclude(side='b').extra(select={'int': 'CAST(number AS INTEGER)'}).order_by('int') The code above falls over due to the symbols in this field. I read around that using the below regex code snippet will remove the non numeric characters but cannot seem to get it to work in the select. "REGEXP_REPLACE(number, '[^0-9.]', '')" Is there a way to remove the non numeric character before casting to an integer and ordering by that value? -
DRF. Matching query does not exist
Okay I have been at this for a while and cannot figure it out. Whenever I make a new job post I get the following error jobs.models.Positions.DoesNotExist: Positions matching query does not exist. Business Model: from django.db import models from django_google_maps import fields as map_fields from django.conf import settings User = settings.AUTH_USER_MODEL Company = settings.COMPANY_USER_MODEL class Business(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) business = models.CharField(max_length=50, unique=True) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) about = models.TextField(max_length=1000, null=True) def __str__(self): return self.business Job Model: from django.db import models from django_google_maps import fields as map_fields import uuid as uuid_lib from django.conf import settings User = settings.AUTH_USER_MODEL class Positions(models.Model): position = models.CharField(max_length=100) def __str__(self): return self.position class Job(models.Model): employer = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey('business.Business', related_name='jobs', on_delete=models.CASCADE) position = models.ForeignKey(Positions, on_delete=models.CASCADE) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) job_detail = models.TextField() # TODO: set length full_time = models.BooleanField(default=False) part_time = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address Job Serializer: from rest_framework import serializers, fields from .models import Job, Type, Positions def get_business_model(): return django_apps.get_model(settings.BUSINESS_MODEL, require_ready=False) Business = get_business_model() # Position Serializer class PositionSerializer(serializers.ModelSerializer): class Meta: model = Positions fields = "__all__" class JobSerializer(serializers.ModelSerializer): date_posted = serializers.DateTimeField(read_only=True, … -
Persistent Connections in Django?
I am trying to understand how persistent connections improve performance especially when my application is READ heavy. So, I have a record of 100000 rows and I have indexed the username field. So, I have created an endpoint where I can query using a username and it gives me the temperature. This is just for testing purposes. So, I wrote another script that has a function that creates a loop that runs 1000 times and it makes a request to the endpoint. I was logging the request-response time and saving it in a list and then calculating the total time taken to complete the 1000 requests. First, I tried with the default Django database settings which don't have persistent connections, and every time I benchmarked the time and it logs around 43 seconds for all 1000 requests. Next, I added CONN_MAX_AGE=60 and ran the script multiple times, found out the time increases to 103 seconds every time. Now, if I am not wrong, a persistent connection should have reduced the total time but for some reason, it was way higher than the normal connections which open and close every time a request-response is done. My question is why is this … -
How to make a form for this model that will able user to select choice for each question asked - Django
Im trying to make a form for a quiz that will able user to select choice for each question when presented, so that when i user submits the form it is saves into the user response. Also how would I list the choices taken from the choice model for each given question? what im trying to achieve: display form for each question for a given quiz display all on same page as one form once all questions answered submit into UserResponse model alongside the user that did the quiz My models seem to work correctly as im able to populate them with data and the relations between them seem to be okay. I am new to django so i have been trying to read the documentation and ive done mutliple tutorials but can seem to find a solution. Model for quiz: class Quiz(models.Model): title = models.CharField(max_length=255, unique=True) description = models.CharField(max_length=255, blank=True, unique=False) created = models.DateTimeField(auto_now_add=True, editable=False) slug = models.SlugField() active = models.BooleanField('Is active?', default=True, db_index=True) class Question(models.Model): type = models.IntegerField(choices=TYPES, default=1, verbose_name='Question Type') question_text = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=500, unique=False) quiz = models.ForeignKey(Quiz, on_delete=models.DO_NOTHING) class Choice(models.Model): choice_text = models.CharField(max_length=255) question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name='Question') class QuizTakers(models.Model): user = models.ForeignKey(User, … -
How to connect inbuilt User database to another one in Django?
I am a beginner in Django. I have created a login, logout and register pages for my Django projects. When a user signs in I want them to only the posts that they have made. I am not sure how to make the users that I already have be able to login into their own pages and manage their budgets and etc. Image of code from django.db import models from django.contrib.auth.models import User# user authentication from django.contrib.auth import get_user_model#for connecting the inbuild user database class List(models.Model): user = models.ForeignKey(User) item = models.CharField(max_length=200)#field to type the name of the budget completed = models.BooleanField(default=False)#this needs to be changed later def __str__(self): return self.item + ' | ' + str(self.completed) -
How to mock an mutation argument in Django?
I have a mutation that has a decorator that checks the permissions (scopes) from the user token before s/he goes inside it. The decorator gets the input parameter from the mutate method and extracts the token and verify if the user has one of the allowed scopes. The unit tests don't succeed if I don't remove or mock the requires_scope part from the code. The problem is that I don't know exactly what I have to mock to succeed in the unit tests. Should I mock the input itself? The token? The return of the requires_scopes decorator? mutations.py class MyMutation(graphene.Mutation): success = graphene.Boolean() class Arguments: input = graphene.Argument(IdInput, required=True) @classmethod @requires_scopes(['app:first_test_permission', 'app:second_test_permission']) def mutate(cls, root, info, input): pass decorators.py def get_access_token_from_header(request): """ Obtains the Access Token from the Authorization Header """ header = request.context.META.get('HTTP_AUTHORIZATION', None) header = header.split() token = header[1] return token def requires_scopes(scopes: list): """ Determines if the required scope is present in the Access Token Args: scopes (list): The scopes required to access the resource """ def require_scopes(f): @wraps(f) def decorated(*args, **kwargs): token = get_access_token_from_header(args[2]) decoded = jwt.decode(token, verify=False) if decoded.get("scope"): token_scopes = set(decoded["scope"].split()) required_scopes = set(scopes) if required_scopes.intersection(token_scopes): return f(*args, **kwargs) raise Exception({'message': 'You don\'t have … -
Django Subquery in SQL FROM part
The Django Documentation shows how to create a subquery in the SELECT part of the SQL query, but how to create a subquery in the FROM part? i.e: SELECT ... FROM ( SELECT ... FROM ... WHERE ... GROUP BY ... ) WHERE ... ORDER BY ... Here is a specific example in case this helps, but if you can answer the general question above without this example, please do. If we have the models: class MyModel(models.Model): field1 = models.CharField() other_model = models.ForeignKey(OtherModel) class OtherModel(models.Model): field2 = models.CharField() field3 = models.CharField() active = models.BooleanField() Let's say I want to count for each my_model.field1 value the number of OtherModel.field3 values where there are some instances my_model, other_model with my_model.other_model == other_model and other_model.active == True So I would like to have a subquery where I group by field1 and field3 and count the actives: sub_query = MyModels.values('field1', 'othermodel__field3').annotate(actives=Count(Case(When(othermodel__active=True, then=1)))) And then a main query where I group the results of the first query by field1 and count them per group: main_query = qub_query.values('field1').annotate(active_combinations=Count('field1', filter=Q(actives__gt=0))) But this is interpreted in a different way and does not work like this. -
timestamp field needs default value
Here is the code for my models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Mail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='emails') sender = models.ForeignKey(User, on_delete=models.PROTECT, related_name='sent') recipients = models.ManyToManyField(User, related_name='received') subject = models.CharField(max_length=255, blank=True) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archive = models.BooleanField(default=False) def serialize(self): ... When I run the python manage.py makemigrations, I get this error: You are trying to add a non-nullable field 'sender' to mail without a default; we can't do that (the database needs something to populate existing rows). But I don't want the sender field to be null and I cannot set a default. For testing, I added null=True to the sender field and I get an error for timestamp: You are trying to add the field 'timestamp' with 'auto_now_add=True' to mail without a default; the database needs something to populate existing rows. To get rid of this error, I added a default=time.time() to the timestamp field. I get this error: The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. What is happening? How do I solve these issues? -
Is it possible to filter "Related field" in Django Template?
I am developing an Instagram clone using Django. I wanted to show the latest two comments for each post. As of now, I am only able to show all comments using the below code home.html {% for comment in post.comments.all %} <p>{{ comment.user.username }}: {{ comment.description }}</p> {% endfor %} My models class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_linked = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') description = models.CharField(max_length=500) comment_posted_on = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment by {} on {}".format(self.user.username, self.post_linked.caption) Is there any way I cal display only the Latest two comment for each post? -
Django does not up - docker compose
I'm trying to up a docker-compose with Django and Mysql, but Django does not up. I saw many people asking the same question, and some answers about it, but none works. docker-compose logs show: web_1 | Traceback (most recent call last): web_1 | File "manage.py", line 22, in <module> web_1 | main() web_1 | File "manage.py", line 18, in main web_1 | execute_from_command_line(sys.argv) web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line web_1 | utility.execute() web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 345, in execute web_1 | settings.INSTALLED_APPS web_1 | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ web_1 | self._setup(name) web_1 | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup web_1 | self._wrapped = Settings(settings_module) web_1 | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ web_1 | mod = importlib.import_module(self.SETTINGS_MODULE) web_1 | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module web_1 | return _bootstrap._gcd_import(name[level:], package, level) web_1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import web_1 | File "<frozen importlib._bootstrap>", line 991, in _find_and_load web_1 | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked web_1 | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 779, in exec_module web_1 | File "<frozen importlib._bootstrap_external>", line 916, in get_code web_1 | File "<frozen importlib._bootstrap_external>", line 846, in source_to_code web_1 …