Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add pydantic field validation for django model?
So, I have a django model, let's say, it's field division is as follows: class ModelA(models.Model): f1 = models.CharField(max_length=127) f2 = models.CharField(max_length=127) I want to create a pydantic class, with a field type containing list of these models. Consider the following example: class TestPydanticClass(BaseModel): model_a_values: List[ModelA] f4: int When I am trying to create the TestPydanticClass object, but it throws the following error: RuntimeError: no validator found see `arbitrary_types_allowed` in Config Based upon this, I added arbitrary_types_allowed as True, under the Config class for the model, and it still throws an error. Can someone pls suggest a better method of achieving this? -
How should I design the Django Database Schema for below scenario?
I have been learning Django for a time being. I hope to get some help with Database Schema design. Which type of relationship should I use for the below use cases. I tried to search for similar use cases but non of those meet my specific need (please point out some online resources where I can learn these types of topics with practical use cases). Here is the most simplified concept of the whole problem (models.py) from django.db import models from django.contrib.auth.models import User class Companys(models.Model): # like Google, Amazon name = models.CharField(max_length=30) def __str__(self): return self.name class Persons(models.Model): # like Jon, Toney person = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class WorkHistory(models.Model): # like # Jon: as Developer at Google # Jon: as Manager at Amazon # Toney: as Sr. Team Leader at Amazon # Toney: as Manager at Google position = models.CharField(max_length=30) person = models.ForeignKey(Persons, on_delete=models.CASCADE) # may be ManyToManyField company = models.ForeignKey(Companys, on_delete=models.CASCADE) # may be ManyToManyField def __str__(self): return self.position Here is how I want to query the data afterward: List of people who have worked on google. List of people who have worked on amazon. (written this line also to make the … -
Why is the field value stored as a set?
When the input field value is saved to the db and I retrieve the same value for updating the field, I get the updated field as a set Data when i retrieve from db, <QuerySet [{'id': 21,'book_title': 'pokolo', 'book_category': '0', 'book_type': 'F'}]> Data after updating the retrieved field value, <QuerySet [{'id': 21,'book_title': "('pokolo',)", 'book_category': '0', 'book_type': 'F'}]> The book title is a CharField and is cleaned before sending to the db -
Django Admin Show Row Results As a Group by ForeignKey Object
I am working on a quiz app. So I have Quiz, Question and Answer tables. Also I have TakingQuiz and TakingQuizAnswer tables. For example, I want to show rows as a group by quiz. If I select a quiz, I just want the list of answers for that quiz to appear or same thing for question-answer. Nested inline isn't a solution for me. It works well for edit page, but I want to make this in list pages. Is there any way to do this? Because there are too many results in these pages, and filters and search also working to some extent. For example, when I select question 1 and click it, a new page or accordion menu may open. From this page or menu, I can see the results related to that parent, and I can edit the one I want. This subject isn't clear for me. Because I am a newbie in Django. I found some solutions, but they came too complicated. And also I found so many unanswered questions about this. I didn't add any code because it's a general question, it can be thought of as an article-comment relationship. I am looking for source and … -
How to setup Django and Python telegram bot to deploy to Heroku?
When I deploy my Django app with my bot.py to Heroku there is a conflict because Django does not let the bot receive the calls. Procfile web: python bot.py web: gunicorn tlgrmbot.wsgi the logs show that it keeps looking for the https://herokuappname.com/token not found, because I don´t have urls, and if I only leave the python bot.py in the procfile the bot responds but it does not finds the Database. Does someone knows how to resolve this? -
Django: aggregate or annotate function, flatten JSON and filter data
The solution would be simple and easy, but I am not able to fetch what I want. I am trying to get the summary a summary table that has a foreign key primary key relationship and provides an array of nested JSON data, which is difficult to display in table format in the frontend. So I am trying to flatten it in the backend, add filters and fetch accordingly. The way I am approaching would be wrong, if someone can please help, I am thankful. model.py class Place(models.Model): id = models.IntegerField(primary_key=True) location = models.CharField(max_length=100) class Meta: db_table = 'place' managed=False class Session(models.Model): id = models.IntegerField(primary_key=True) place = models.ForeignKey(Place,related_name='session',on_delete=models.CASCADE, null=True) start = models.DateField(auto_now=True) count = models.IntegerField() num_not_placed = models.IntegerField() class Meta: db_table = 'session' managed=False class Animal(models.Model): id = models.IntegerField(primary_key=True) sess = models.ForeignKey(Session,related_name='details',on_delete=models.CASCADE, null=True) type = models.CharField(max_length=100) is_active = models.BooleanField() length = models.DecimalField(max_digits=6, decimal_places=2) class Meta: db_table = 'animal' managed=False serializers.py class PlaceSerializer(FlexFieldsModelSerializer): length_max = serializers.DecimalField(max_digits=10, decimal_places=2) length_min = serializers.DecimalField(max_digits=10, decimal_places=2) length_avg = serializers.DecimalField(max_digits=10, decimal_places=2) length_std = serializers.DecimalField(max_digits=10, decimal_places=2) is_active_percent = serializers.IntegerField() counts = serializers.IntegerField() Num_of_not_placed = serializers.IntegerField() Date = serializers.DateField() type = serializers.CharField() class Meta: model = Tank fields = ["Date","location","type","is_active_percent","length_max","length_min","length_avg","length_std","Num_of_not_placed","counts"] expandable_fields = { 'session': (SessionSerializer, {'many': True}) } I … -
How to pass data from html to django view
I have the following button: <a href="{% url 'acceptdonation' %}" >Delete</a> I also have this acceptdonation function (in views.py): def acceptdonation(request, pk): #add pk after request deleteitem = Donation.objects.filter(id = pk) deleteitem.delete() return redirect('/dashboard/') I want to pass {{donation.pk}} to the view after the delete button is clicked. The code should delete the data assosiated with the pk given and redirect the user -
Django 'UNIQUE constraint failed' when post same massages
I am building a socialsite. In this site user create group and post messages. I get this error when user put same message in same group or even in other group. **IntegrityError at /posts/new/ UNIQUE constraint failed: posts_post.user_id, posts_post.message Request Method: POST Request URL: http://127.0.0.1:8000/posts/new/ Django Version: 3.2.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: posts_post.user_id, posts_post.message Exception Location: F:\Program Files\envs\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: F:\Program Files\envs\MyDjangoEnv\python.exe** Here is models.py: class Post(models.Model): user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] views.py: class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") ) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): # form_class = forms.PostForm fields … -
CSRF token missing or incorrect . How to resolve this error?
I am new to django. I am creating a website using django. I have provided register and login functionality to my website. Only Problem is after sucessfull login, whenever i reload a browser accidently it asks me this ques about re-submitting details again and then if click on continue , it shows me this error page. csrf token missing or incorrect Please tell me what should i do to avoid this error? -
Django - Sending an Email with attached video
I'm working on a Django project, and I'm trying to send an email with a video attached to it. Currently, I'm able to upload videos and watch them on the local host site and the admin site. I know if I want to send attachments, I'll have to use EmailMessage instead of send_mail but still can't fully figure it out. Here's what I got so far Here's my views.py: from django.core.mail import send_mail, EmailMessage, get_connection def upload_video(request): if request.method == 'POST': title = request.POST['title'] video = request.FILES['fileName'] desc = request.POST['desc'] thumb_nail = request.FILES['thumbnail_img'] content = Videos(title=title,video=video, desc =desc, thumbnail=thumb_nail) content.save() messages.info(request, 'Your Video has been successfully uploaded.') connection = get_connection(use_tls=True, host='smtp.gmail.com', port=587) EmailMessage ('Hello', 'testing', request.user , [request.user], connection=connection).send() return render(request,'upload.html') def display(request): videos = Videos.objects.all() context ={ 'videos':videos, } return render(request,'videos.html',context) Here's my models.py: class Videos(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='videos/') thumbnail = models.ImageField(upload_to='videos/thumbnail/', default='none') desc = models.TextField(max_length=1000, help_text="write a description of your video") price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class Meta: verbose_name = 'video' verbose_name_plural = 'videos' def __str__(self): return self.title Anyone can help with this? -
Django url's apearence
Consider the scenerio where, Iam creating a Django application where a user can SignUp and LogIn and do some stuff. So I created some functions like SignUp LogIn etc. in views.py file of the app. And I map it to corresponding urls in urls.py file. So while running locally, if I go to localhost:8000/SignUp the user will be taken to the SignUp page right! So my question is, how can I get the same thing done but the link be like SignUp/localhost:8000 ? Or simply how can I bring the mapped urls to the beginning of my localhost:8000 link? Is that possible in Django? Sorry if my terminologies are bad... But I need to know this. ThankYou for reading. -
How to add a method to Django class to convert to dictionary
I am making a reporting tool for some SW testing... I have the following model in my models.py file class triage_notes(models.Model): stack_name = models.CharField( max_length=30 ) build_number = models.IntegerField( ) fails = models.IntegerField() jira_ticket = models.CharField( max_length=100 ) notes = models.TextField() bug_type = models.CharField( max_length=50 ) def as_dict(self, *args, **kwargs): return { "id":self.id, "build_number": self.build_number, "fails": self.fails, "jira_ticket": self.jira_ticket, "notes": self.notes, "bug_type": self.bug_type } As you can imagine, the goal is to be able to use this method in the query call in order to present my query as a dictionary... In my view I am attempting to use this method def index_view(request): context = triage_notes.objects.as_dict() print(context) return render(request, 'index.html', context) But I am getting the following error TypeError: as_dict() missing 1 required positional argument: 'self' I would love to understand this process better as being able to implement custom methods for my models would be a great tool in the future. Any recommendations would be greatly appreciated! :) -
Communicate with MQTT broker from Django server
I have a Django server that requires to communicate with an MQTT broker. The Broker has a master and it needs to send updates to the Django server periodically. How do I subscribe to the topic from the server to receive that update from the broker? Can anyone provide an example? I found this package https://pypi.org/project/djangoiot/ but no proper documentation about receiving messages. -
Django Rest Framework, Serializer Level Filter
I have two models named Account and Story. With the help of a models.Manager on Django, I wrote a method that retrieves the stories posted in the last 24 hours. With Django, this method works very well. The problem is that when I create a serializer with Django Rest Framework it pulls all the stories. To prevent this, I wrote a method called get_image_file and used the method I wrote with the help of models.Manager here, but I could not solve the problem. As a result, how do I pull only the stories that were posted in the last 24 with Django Rest Framework, as I did on the Django side? serializers.py from rest_framework import serializers from ..models import Account, Story class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = ['image_file'] def get_image_file(self, obj): #This method doesn't work. DRF pulls all the stories. return obj.get_available_stories() class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = '__all__' stories = StorySerializer(many=True) models.py from django.db import models import datetime def upload_to(instance, filename): username = instance.account.username return '%s/%s/%s' %('stories',username,filename) def upload_pp(instance, filename): return '%s/%s/%s' %('profile_photo', instance.username,filename) class Account(models.Model): username_pk = models.CharField(max_length=122) username = models.CharField(max_length=55, unique=True) profile_photo_id = models.CharField(max_length=155, unique=True) profile_photo = models.ImageField(upload_to=upload_pp, null=True, blank=True) profile_photo_width … -
How to solve 'django.db.utils.OperationalError: fe_sendauth: no password supplied'?
**After I setted local default variates in .env file of django project and got these in setting.py.'django.db.utils.OperationalError: fe_sendauth: no password supplied' this error happended when running server. 1 But when I directly gave database's value in setting.py rather than using os.envrion.get(),server worked.How do solve it if using os.envrion.get() to connect database?** -
How to fix: TypeError: a bytes-like object is required, not 'str' , I get this error when i launch the function in the shell
i am new to the world of python programming. i am trying to simulate an ethereum transaction with the help of ropsten. So I initialized the following function but it always gives me the usual error. from web3 import Web3 def sendTransaction(message): w3 = Web3(Web3.HTTPProvider('My Ropsten address')) address = ''<---My address privateKey = ''<---My privatekey nonce = w3.eth.getTransactionCount(address) gasPrice = w3.eth.gasPrice value = w3.toWei(0, 'ether') signedTx = w3.eth.account.signTransaction(dict( nonce = nonce, gasPrice = gasPrice, gas = 10000, to = '0x0000000000000000000000000000000000000000', value = value, data = message.encode('utf-8'), ), privateKey) tx = w3.eth.sendTransaction(signedTx.rawTransaction) txId = w3.toHex(tx) return txId Can someone help me? thank you -
Mock Django GenericForeignKey
I'm trying to test a QuerySet of a model with the Django GenericForeignKey structure and would like to mock the multiple models it connects to. However when I try to substantiate the Flag model (one with the GenericForeignKey) with one of the mocked models, a TypeError is raised: TypeError: Flag() got an unexpected keyword argument 'content_object' I tried the code below with the content_object line commented out and that works. However part of the tests later on need that attribute, so ignoring it is not a viable solution. #models.py class Flag(TimeStampedModel): text = models.TextField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() #tests.py ... def setUp(self): self.quantity = 10 text = ['foo', 'bar', 'baz', 'qux'] for object_ in [mock.Mock(spec=ModelType1), mock.Mock(spec=ModelType2), mock.Mock(spec=ModelType3)]: for i in range(self.quantity): object_.pk = i f = Flag.objects.create( text=random.choice(text), content_type=ContentType.objects.get_for_model(object_.__class__), object_id=object_.pk, content_object = object_ ) I tried moving that line out of the create function and trying to set it afterwards however that seems to trigger errors with an object's state. f.content_type = object_ f.save() ... File ".../python3.9/site-packages/django/contrib/contenttypes/fields.py", line 164, in get_content_type return ContentType.objects.db_manager(obj._state.db).get_for_model( File "...Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py", line 630, in __getattr__ raise AttributeError("Mock object has no attribute %r" % name) AttributeError: Mock object has no attribute … -
Saleor deployment failure while Heroku one click deployment
I just wanted to try out Saleor a bit and I just used Heroku button's one click option for deploying all three of them at once. Except for the storefont though. The other two were quite successful and now I can access to my saleor core through my dashboard app. Speaking of Storefront deployment failure, I noticed some db error when seeing the build log of heroku on the web console. And I suspect it might be related to some dummy data. When I read documents on saleor deployment on Saleor website, they said "populatedb" should not be done to the production mode without clarifying the "why". And I think those two(my storefront deployment failure and that remark on db dummy data) have to do with each other? I manually deleted the dummy db data on the dashboard page, but still the storefront deployment through heroku failed. What should I do? Here's my last lines of log: Detected both "build" and "heroku-postbuild" scripts Running heroku-postbuild > saleor-site@3.0.0-a.0 heroku-postbuild /tmp/build_4b72e375 > npm run build > saleor-site@3.0.0-a.0 build /tmp/build_4b72e375 > next build warn - React 17.0.1 or newer will be required to leverage all of the upcoming features in Next.js 11. Read … -
how to check which version of graph api is called in Python
Facebook Graph API version 3.3 is ending on 3rd, August 2021. I am unable to see the versioned graph API calls on the APP dashboard(might be Facebook removed it). Facebook-SDK version is 3.1.0 In my code: self.fb_graph = facebook.GraphAPI(version='7.0') posts = self.fb_graph.get_connections(id=page_id, connection_name='feed', fields=fields, since=date_range, until=date_range, access_token=page_access_token) I get the data using this. But when I use code self.fb_graph = facebook.GraphAPI(version='3.2'). Even version 3.2 is no more but I am getting data using this too. I am unable to get the Facebook graph API calls version. How can I get the version number of API calls either using code or on any dashboard? -
Pass same dynamic data (user type) to all render request in django
I am creating my first web app using django and I have a custom model which has the user type of each user stored and I want the menu options off my html to be customized based on the user type. I am implementing that by using the if django template tag butfor that I require the user type of the user requesting the page to be passed whenever I call the render function. So is there any method through which this data is sent automatically to all the requests? -
Urls in css is not working after upload static files to aws s3 bucket
I making a blog posting web site and also check different cors configurations for aws but any of this can solve this issue.Issue is urls in css files like @import url(fonts.css); background-image: url("paper.gif"); and like these things is not working.And also in console I got a error like this net::ERR_ABORTED 403 (Forbidden) so any of font awesome icons are also not working.Do you have any suggestion let me know. -
how to use terraform with private subnet for ecs fargate and public subnets for load balancer and secret manager
I am using Terraform for AWS, I am not sure what I am doing wrong with my ECS Fargate and VPC configuration but I keep getting this message when i monitor the ECS Service Logs, which keep getting stopped. ResourceInitializationError: unable to pull secrets or registry auth: execution resource retrieval failed: unable to retrieve secret from asm: service call has been retried 1 time(s): failed to fetch secret arn:aws:secretsmanager... I have configured my VPC with two public subnets and two private subnets (private subnets have NAT Gateway) ECS Service was configured to use only the private subnets while the load balancer use the public subnets. I have used Secret Manager to store my PostgreSQL secrets and in the code i am retrieving them like this: resource "aws_ecs_task_definition" "task_definition" { family = "ecs-td" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] cpu = 1024 memory = 2048 execution_role_arn = data.aws_iam_role.fargate.arn container_definitions = jsonencode([ { "name" : "ecs-container", "image" : "${data.aws_ecr_repository.image.repository_url}", "cpu" : 1024, "memory" : 2048, "essential" : true, "portMappings" : [ { containerPort = 8000 } ], "secrets" : [ { "name": "POSTGRES_NAME", "ValueFrom": "arn:aws:secretsmanager:${var.REGION}:${var.ACCOUNT_ID}:secret:${var.POSTGRES_NAME}" }, ... Also, I have updated the security groups to allow necessary traffics, then in IAM Role, … -
how to authenticate users using django knox?
I 've this serializer for loginuser : class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Invalid Details.") and my login view as follows : class LoginAPI(generics.GenericAPIView): serializer_class = LoginUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "token": AuthToken.objects.create(user)[1] , "user": UserSerializer(user, context=self.get_serializer_context()).data }) now when i try to make a get request with auth permission for a specific view providing the generated token with it i always get a 404 status code with "credentials isn't provided " . e.g my view : class ExampleListAPIView(generics.ListAPIView): serializer_class = ExampleSerializer permission_classes = [IsAuthenticated,] -
Query.get raising Object matching query does not exist Error with Try & except as well
models.py class Inventory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,blank=True) product = models.ManyToManyField(Product, blank=True) class Product(models.Model): name = models.CharField(max_length=50) description = models.TextField(default='Hidden') image = models.ImageField(upload_to='images/', blank=True, null=True) interest = models.IntegerField(default=0, blank=True) price = models.IntegerField(default=0, blank=True) capital = models.IntegerField(default=1, blank=True) years = models.IntegerField(default=0, blank=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name views.py def inventory(request): b = request.user.id # user_id=12 inv1 = Inventory.objects.all() try: userdb = inv1.get(user_id__exact=b) inv1.get(user_id__exact=b) context = {} return render(request, 'redcube/inventory.html', context) except: userdb = inv1.get(user_id__exact=b) products = userdb.product.all() bal = 0 for p in products: print(p.price, '=p.price') bal = bal + p.price context = {'inv1': inv1, 'userdb': userdb, 'products': products, 'bal': bal} return render(request, 'redcube/inventory.html', context) context = {'inv1':inv1} return render(request, 'redcube/inventory.html', context) inventory.html {% extends 'basic.html' %} {% load static %} {% block content %} <link href="{% static 'bootstrap.min.css' %}" rel="stylesheet"> <style> .center { margin: auto; width: 50%; padding: 10px; } </style> <div class = "w-100 p-auto" style = "width:500px; margin: 0 auto;"> <div class="center"> <div class="container"> <div class="card" style="width: 50rem;"> <div class="center"> <div class = "text-center user-block"> <h1 class="center">Inventory</h1> {% if products %} <h2>Balance <span class="text-info">{{bal}}</span> Tcoins </h2> {% else %} <h2 class="text-danger">No items</h2> {% endif %} </div> </div> </div> </div> </div> </div> {% csrf_token %} {% if user.is_authenticated … -
django.db model not found 'ForeignKey'
class Customer(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=200) locality= models.CharField(max_length=200) city = models.CharField(max_length=50) zipcode = models.IntegerField() state = models.CharField(choices=STATE_CHOICES, max_length=50) This is a part of my code i have correctly imported models but unable to find the error... error message == AttributeError: module 'django.db.models' has no attribute 'Foreignkey'