Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
How to get the self variable inside the etag_func and last_modified_func functions Django
I am using the django http condition to set the last_modified and e_tag headers. Here is my set up: def my_last_modified(request, *args, **kwargs): return None def get_etag_key(request, *args, **kwargs): return None class ProductsListAPIView(ListAPIView): queryset = Product.objects.active() # I want to get this value in the functions serializer_class = ProductSerializer @condition(etag_func=get_etag_key, last_modified_func=my_last_modified) def get(self, *args, **kwargs): return super(ProductsListAPIView, self).get(*args, **kwargs) What I want to do is get this variable queryset from the main class in the get_etag_key and my_last_modified functions. Is there any way to go about this? -
Do i need to use django-s forms when taking only a number and the id as a hidden value?
I am building an e-commerce like website with Django and trying to implement some Ajax. Now i am creating the guest cart and I want to take the amount of the product , its id and add it to the session. My question is do i need to use Django-s forms if i am only taking a number and the id as a hidden field ? . Or is it always better to use Django-s forms because of their security? -
Sphinx column error: "requested parameter unknown"
I have a filterable table on my django site that I have added a column to. However, after plugging in the code grabbing the data, I now receive this error when refreshing the page: DataTables warning: table id=table - Requested unknown parameter 'pname' for row 0, column 9. For more information about this error, please see http://datatables.net/tn/4 My site has two databases. The initial is a sphinx database, then it updates with the postgres database via databases.update() in a second settings file. I added the column to both postgres and sphinx. I have confirmed it is in sphinx by looking at the sphinx mysql database (naturally I also have checked the postgres, and the column can be pulled up in other areas). I added it by stopping sphinx, adding the column as an "rt_attr_string" in the .conf file, clearing the data inside of "var/lib/sphinxsearch/data", and restarting sphinx. The code that connects to the table is: app/conf.py USER_TABLE_COLUMNS = [ dict( name = "column1", orderable = False, ), dict( name = "newcolumn", orderable=False, ) ] (Please keep in mind that I have removed extra columns/renamed it for simplicity) Inside of views.py: class ListView(appViewBase): template_name = "app/list.html" @method_decorator(login_required) @method_decorator(permission_required("sig.app.view", raise_exception=True)) def dispatch(self, … -
Twilio REST Exception HTTP 429 error: Unable to create record: Too many requests
I have created an app in Django. Using Twilio Verify API (free trial) for OTP. Problem:- It's working fine but when a user try to get the OTP multiple times, Twilio creates an exception "HTTP 429 error: Unable to create record: Too many requests". After this I was not able to use this for the whole day even for different mobile number or device. How to bypass this issue and precisely what is the reason behind this issue? -
get() returned more than one Model -- it returned 4! - but only 1 Model in db
In a Django view, I'm getting a MultipleObjectsReturned error using a get_or_create. Many questions have been asked about this, but those people seem to be using this construct wrongly. I think that I'm using it correctly, but please correct me if I'm wrong. I have the following model: class MyModel(models.Model): field1 = models.ForeignKey('app.OtherModel', on_delete=models.SET_NULL, null=True) field2 = models.CharField(max_length=50, blank=True, null=True) field3 = models.JSONField() field4 = models.JSONField() updated = models.DateTimeField(_('Date updated'), auto_now=True) created = models.DateTimeField(_('Date created'), default=timezone.now) ... class Meta: ordering = ('-created',) constraints = [ models.UniqueConstraint(fields=['field1', 'field2'], name='unique_model'), ] And this code in my view: o, created = MyModel.objects.get_or_create(field1=value1, field2='value2', defaults={'field3': '...', 'field4': '...'}) So the get is performed on the two fields that are in the UniqueConstraint, the other fields are listed in the defaults part (in case the create is required). The MultipleObjectsReturned is thrown on that last line, when Django performs the get part of the get_or_create, but only in some rare cases - most of the time this construct works well. The view is actually a handler for AWS's SNS event messages for SES, handling delivery delays, bounces and complaints. In theory it should not happen that this view is called exactly twice, causing a race-condition. … -
django csrf_token verification with python requests module
I want to send post request using python requests module. Since, I use Django for backend server. So, I need verify csrf_token for post method. I know that i have option to stop csrf_token verification using Django built in decorators. But, i don't want to do that for cross site protection. My Django Sample Code: from django.http import HttpResponse from django.middleware.csrf import get_token def pv(v, s): print(f"----------Value of {s}-------") print(f"Type= {type(v)}") print() print(v) print() def index(request): pv(request.COOKIES,"HttpRequest.COOKIES") pv(request.headers,"HttpRequest.headers") token = get_token(request) # I think, Here have some worng. But What? return HttpResponse("Hello World") index() is work for both get and post reequest. Though i don't use redirect() for post method in sample code. Here is my get and post request code using python requests module: import requests import time def pv(obj, s): print(f"-----Value of {s} --------") print(type(obj)) print(obj) print() url = "http://192.168.0.102:8000/home/" data = {"a":"5", "b":4} d = requests.get(url) time.sleep(2) requests.post(url, cookies=d.cookies, data=data) # For Test pv(d.headers, "d.headers") pv(d.cookies['csrftoken'], "d.cookies") get request work properly and return me csrf_token.when i use this toke with post method. Django server give me Forbidden (CSRF token missing or incorrect.): /home/ error and post request doesn't work properly. How can i verify csrf_token? -
Django Model Use Text Choices From Another Model
In my Django model, I want to use the text choices from another model, but I don't want to use it as a foreign key, because I want the whole list of weekdays before any Day object exists. If I use it as a foreign key, I will need to create Day object first. Can anyone help to solve this? class Day(models.Model): class Weekdays(models.TextChoices): MONDAY = "Monday" TUESDAY = "Tuesday" WEDNESDAY = "Wednesday" THURSDAY = "Thursday" FRIDAY = "Friday" SATURDAY = "Saturday" SUNDAY = "Sunday" store = models.ForeignKey(Store, on_delete=models.DO_NOTHING) weekday = models.CharField(max_length=9, choices=Weekdays.choices) class School(models.Model): weekday = ??? -
Django - Altering list view based on link that is pressed
I have a navbar above my products on my fake e commerce website that I am building. I render this view through list view. In this navbar I have a search area that works fine, and want to add the ability to filter the results based on what is pressed. For example, I have styles: realism, portrait, etc in the navbar. When I click on realism I want the results to change to all realism paintings that are in the DB. My question is what would be the best way to accomplish this? Could I alter the original list view? Or would I just need to create an entirely new view based on the specific queries I need? Any help is greatly appreciated! Also attached will be a picture to show you what I mean in case my explanation wasn't the best. view: class AllProductView(ListView): template_name = 'my_site/all_products.html' model = Product ordering=['id'] paginate_by = 9 context_object_name = 'products'