Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configuration of SSL via Let's Encrypt for Elastic Beanstalk
I want to enable SSL (using Let's Encrypt) for my Django project running on AWS Elastic Beanstalk. tldr: Unfortunately, it seems that when Let's encrypt connects to my website to check for the token instead it gets a 404 error. During secondary validation: Invalid response from http://sub.example.com/.well-known/acme-challenge/Gzo8gzkIEbLmtvGkSDhnNheml9XxNsctHJA3ufA0FYI [107.20.106.65]: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">\n <title>Page not " Now I don't know if this problem is caused by Django configuration, nginx configuration, Elastic Beanstalk, my subdomain, Certbot or anything else... What next steps to debug it should I take? (Of course, the sub.example.com stands for an existing subdomain that I own.) My domain, let's say: example.com was registered through an external domain registrar and then I created a subdomain sub.example.com which points to the EB CNAME (foo-bar-foo-bar.bar-foo.us-east-1.elasticbeanstalk.com.). The site is available via http using both addresses (sub.example.com and foo-bar-foo-bar.bar-foo.us-east-1.elasticbeanstalk.com) and displays the Django welcome page with an image of a green rocket. Here is the script I created to create the project and environment (following the official tutorial): VAR_MYDOMAIN=sub.example.com VAR_NUMBER=7 VAR_PROJECT_DIRNAME=project-foo-$VAR_NUMBER VAR_DJANGO_PROJECT_NAME=project_foo_$VAR_NUMBER VAR_EB_APP_NAME=project_foo_app_$VAR_NUMBER VAR_EB_ENV_NAME=project-foo-env-$VAR_NUMBER VAR_AWS_KEYNAME=aws_keys_name mkdir $VAR_PROJECT_DIRNAME cd $VAR_PROJECT_DIRNAME py -m venv eb-virt source eb-virt/Scripts/activate pip install django==2.1.1 django-admin startproject $VAR_DJANGO_PROJECT_NAME cd $VAR_DJANGO_PROJECT_NAME pip freeze > requirements.txt mkdir .ebextensions echo … -
Djongo - Cannot put my own models in documents
I have the following Python code that I am trying to migrate from mongonaut to the new way of interfacing Django with MongoDB, the djongo package: # CharField for English and Japanese text class LocalizedCharField(models.Model): EN = models.CharField(max_length=128, blank=False, null=False) JP = models.CharField(max_length=128) # CharField for English and Japanese text class LocalizedCharField(models.Model): EN = models.CharField() JP = models.CharField() # Details for a character class CharacterInfo(models.Model): charName = models.CharField(max_length=128, blank=False, null=False) displayName = models.EmbeddedField(LocalizedCharField) nationality = models.EmbeddedField(LocalizedCharField) game = models.EmbeddedField(LocalizedCharField) system = models.EmbeddedField(LocalizedCharField) voice = models.EmbeddedField(LocalizedCharField) graphic = models.EmbeddedField(LocalizedCharField) introduction = models.EmbeddedField(LocalizedCharField) defaultPalIndices = models.CharField(max_length=128) groove = models.DictField() config = models.CharField() moves = models.DictField() charConfig = models.DictField() However, I get the following error when I try to debug my server: ['Field "lawn.LocalizedCharField.id" of model container:"<class \'lawn.models.LocalizedCharField\'>" cannot be of type "<class \'django.db.models.fields.AutoField\'>"'] And it points to the line where displayName is as the culprit, meaning I for some reason can't embed my own field types in other models? What do I have to do to make this work? As said before, up until this point, I was using an outdated custom build of Mongonaut where this worked fine, so I'm unsure what djongo wants. -
Django form comment always returning GET requests, POST request 'Method Not Allowed'
I'm trying to implement a feature where logged in users can comment on a blog post, but I'm a little stuck with the comments appearing on the page. I can type in the comment and submit them. However, this is always returning a GET request. I tried adding method='post' to both the form and button tags, but this resulted in the following: Method Not Allowed (POST): /post/1/ Method Not Allowed: /post/1/ I'm not really sure what the problem is. Any help would be much appreciated. Code snippets below. post_detail.html with comment section: <div class="content-section"> <legend class="border-bottom">Comments:</legend> {% if user.is_authenticated %} <form id="commentForm"> {% csrf_token %} <fieldset class="form-group"> <div class="row"> <!-- <div class="col"></div> --> <div class="col-1 text-right"> <img class="img-comment" src="{{ user.profile.image.url }}"> </div> <div class="col-9"> <textarea type="text" id="commentIn" name="comment" placeholder="Your comment..." required></textarea> </div> <div class="col"></div> </div> <div class="row"> <div class="col-10 text-right"> <button id="commentBtn" name="comment_button" class="btn btn-outline-info" type="submit">Comment</button> </div> <div class="col"></div> </div> <hr> </fieldset> </form> {% endif %} <div id="commentDiv"> {% for cmnt in comments_list %} <img class="img-comment" src="{{cmnt.commentator.profile.image.url }}"> <a class="mr-2" >{{ cmnt.commentator }}</a> <p class="article-content">{{ cmnt.comment }}</p> <hr> {% endfor %} </div> </div> urls.py in blog app urlpatterns = [ path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"), models.py class Post(models.Model): title = models.CharField(max_length=100) content … -
Redirect to POST request after successfully processing another POST request
I have two independent POST requests which I'm trying to process one after another using Django. After first POST request, I'm trying to redirect to another view which is also a POST request and performs another functionality. When redirect happens, second view receives GET instead of POST request. I need to mention that requests represent two independent events and aren't connected but can be performed one after another. Does Django allow this kind of redirects or is there a way to trigger this behaviour? Here's my code: Template code that triggers first POST request: <p>Are you sure you want to proceed?</p> <form action="{% url 'participants-reset'%}" method="post"> {% csrf_token %} <fieldset> <div class="form-group"> <button type="submit" class="btn btn-primary">Yes, match again.</button> </div> </fieldset> </form> views.py def participants_reset(request): #View that handles first POST request if request.method == "POST": Participants.objects.all().delete() messages.success(request, "Santa's list is empty again.") return redirect('match') #Attempt to trigger second POST request through url else: messages.error(request, "Woops. Something went wrong. Please try again.") return redirect('participants') def match_pairs(request): #View that handles second POST request if request.method == "POST": #Another functionality urls.py path('match-pairs/', views.match_pairs, name='match'), path('participants/', views.ParticipantsListView.as_view(), name='participants'), path('participants-reset/', views.participants_reset, name= 'participants-reset'), -
Best way to implement feature where users can submit videos to the website and they will automatically get uploaded to Youtube?
I have website where the frontend (ReactJS) and backend is (Django). I want to add a feature where people can submit clips and these clips will get automatically uploaded to our Youtube channel. My goal is simply to upload the video into YouTube and store the URL of the video in the database with a foreign key to the user that uploaded it. I'm still not sure if I want to keep the original video file or just delete it. So this has been my thinking process so far: 1- To reduce the load on the backend I could just upload videos directly from the frontend. But my guess is that this is not a good idea because for that I would have to expose the Youtube credentials to the public. 2- Then the video will have to be transferred from the Frontend to the Backend and then the backend will have to upload the video to Youtube. Should I use something like Celery so the upload to video to Youtube doesnt block the main django threads? 3- Last option I thought is maybe have the video transferred from the frontend to AWS S3. And then have some sort of … -
Django Iteration through the fields of particular instance of the model
I'm new in django. My goal is to create a dictionary with keys taken from table and values taken from particular instance of the model which amongs the others contains fields we can meet in table. Is any way to iterate through fields of the model's instace to do that? My idea as you see below doesn't work because particular instance represented as i doesn't recognize variable j as his field. Any Idea? my_fields=['car','model','age'] my_dict={} #I would like it to look like my_dict={'car':'Toyota','model':'Corolla','age':2} class Cars(models.Model): car=models.CharField(max_length=40) model=models.CharField(max_length=40) age=models.IntegerField() country=models.CharField(max_length=40) amounts_of_doors=models.IntegerField() #particular instance Object { model: "cars.Car", pk: 1, fields: {'car':'Toyota','model':'Corolla','age':2}} #code I have tried for i in Cars.objects.all(): if i.car=='Toyota: for j in my_fields: my_dict[j]=i.j <==it doesn't work -
I want to add a filter condition for Date Range Filter, what should I do?
Django's DateRangeFilter returns only objects between specified periods. I would like to inquire about the purchase history that exists within a specific period of time. What should I do? -
Django: How to limit ip address or ip range for users?
Is there a way to limit the ip address of the user from which he can access the website? I found an answer that shows how we can get the ip address of the user, and I thought of adding a field on the User model that would contain the address or range from which the user can access the website and then when a request from a user comes, I'd check his IP address and prevent/allow him to access the website. But is there a more elegant way that would require less work? I've found some packages that seem to work with older Django versions, but they don't quite meet my needs. What I would need is basically have the admin be able to limit the ip range for each and every user from the admin panel. Is there a way to do such a thing? Besides the method I have described? -
How to sumbit form from django admin panel
I've already made lots of search but couldn't find the appropriate answer to my question. Is it possible to submit form from template in admin panel? I have a template like this: {% block content %} {% load static %} <form action="find_tr" method="POST"> {% csrf_token %} Enter url: <input type="text" name="url"><br><br> <input type="submit"> </form> {% endblock %} I can submit it from template itself but , what i want is to make it possible through admin panel. For now it looks like this: The same should be possible from admin panel: Is there any way to achieve it? -
Inject code every second run Django template loop
As I have two columns with special formatting, I have a Django loop in my template that I would like to add some unique HTML every 2nd run. I have looked online but cannot find anything that is inline (not a separate for loop). What is the best way to achieve this? -
Docker-Compose RPC Error when composing react-django docker cconatiner
I am trying to make an eCommerce app with React and Django. Every time I try to do docker-compose up from the root directory of the project I get the error: ```failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount825971380/Dockerfile: no such file or directory`` The file structure is as follows: Ecommerce | - client | | - public | | - src | | | - components | | - package.json | | - package-lock.json | | - Dockerfile | - server | | -api | | -ecommerce | | -orders | | -products | | -users | | -Dockerfile | | -manage.py | | -requirements.txt | - docker-compose.yml Both of my dockerfiles are named "Dockerfile". Capital D, only a capital d. No extension. The docker-compose file is "docker-compose.yml" The complete docker-compose: version: "3.2" services: web: build: . command: python ./server/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres client: restart: always command: npm start container_name: front build: . ports: - "3000:3000" client Dockerfile: FROM node:13.12.0-alpine WORKDIR /client COPY package.json package-lock.json ./ RUN npm install RUN npm install react-scripts@3.4.1 … -
Is there a way to use regex in Django's ALLOWED_HOSTS section?
I'm trying to add multiple hosts to the ALLOWED_HOSTS section in django settings instead of the urlsettings. Is there a way to do this? Right now I have: r'/^https:?\/\/my_app.*herokuapp.com/' which isn't working. Trying to add different branches for app previews. Any ideas? -
How do you run a python script (.py) on an uploaded file in django
I have a question regarding handling downloaded files on Django. I have created a form that allows users to upload a file (XML Format). It is then saved in the media folder (MEDIA_URL). I have also created a 'Parser.py', a script that will find stuffs using Element Tree and will insert it to an SQLite database. My question is where do I need to put this 'Parser.py' script so it can parse the uploaded file and insert the data to the database. Is it with the upload button or maybe in the views during the request? -
sqlite3.IntegrityError: UNIQUE constraint failed | When using bulk adding many-to-many relation
I have two models, where one of them has a TreeManyToMany field (a many-to-many field for django-mptt models). class ProductCategory(models.Model): pass class Product(models.Model): categories = TreeManyToManyField('ProductCategory') I'm trying to add categories to the Product objects in bulk by using the through-table, as seen in this thread or this. I do this with a list of pairs: product_id and productcategory_id, which is also what my through-table contains. This yields the following error: sqlite3.IntegrityError: UNIQUE constraint failed: products_product_categories.product_id, products_product_categories.productcategory_id My code looks as follows: def bulk_add_cats(generic_df): # A pandas dataframe where ["product_object"] is the product_id # and ["found_categories"] is the productcategory_id to add to that product. generic_df = generic_df.explode("found_categories") generic_df["product_object"] = generic_df.apply( lambda x: Product.objects.filter( merchant = x["forhandler"], product_id = x["produktid"] ).values('id')[0]['id'], axis=1 ) # The actual code # Here row.product_object is the product_id and row.found_categories is one # particular productcategory_id, so they make up a pair to add to the through-table. through_objs = [ Product.categories.through( product_id = row.product_object, productcategory_id = row.found_categories ) for row in generic_df.itertuples() ] Product.categories.through.objects.bulk_create(through_objs, batch_size=1000) I have also done the following, to check that there are no duplicate pairs in the set of pairs that I want to add. There were none: print(generic_df[generic_df.duplicated(subset=['product_object','found_categories'], keep=False)]) I suspect that … -
Method not allowed in django when i clicked the login button of modal form?
Method Not Allowed (POST): / Method Not Allowed: / [30/Jan/2022 15:18:30] "POST / HTTP/1.1" 405 0 view.py class Customer_login(View): def post(self,request): name=request.POST.get('email') print(name) -
TypeError __str__ returned non-string (type int)
I'm trying to code a screenplay app, but I'm running into a problem when I actually add information to my model. My models look like this: class Screenplay(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100) def __str__(self): return self.title class Block(models.Model): class BlockTypes(models.IntegerChoices): HEADING = 1, 'HEADING' DESCRIPTION = 2, 'DESCRIPTION' CHARACTER = 3, 'CHARACTER' DIALOGUE = 4, 'DIALOGUE' uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) text = models.TextField() type = models.PositiveSmallIntegerField( choices=BlockTypes.choices, default=BlockTypes.HEADING ) screenplay = models.ForeignKey(Screenplay, on_delete=models.CASCADE, related_name='blocks') def __str__(self): return self.type When I go to my backend api (localhost:8000/api/screenplays) I see my sample screenplays which resemble this: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "uuid": "SAMPLE - UUID", "title": "SAMPLE - TITLE", "blocks": [] }, ] The error I posted in the title pops up when I actually add a block to a screenplay. In my api it seems like "blocks": [] but when I POST a block to a certain screenplay it breaks. I just don't understand what the issue really is, if it's in my models.py or in some other part of my django app. Do I need to add a blocks in my Screenplay model? Anyways, any advice … -
CI/CD Django and Postgress: failure in tests in models that uses signals
I try to configure CI/CD on Github with my Django project. I've found some unusual issues. Some of my tests that work perfectly on the local server failed on CI/CD. Problem with a model that sends a signal to another model for creating a new object. In the local server, I've got 8 signals while tests work but in CI/CD it is only one. The other tests pass without any problems. Maybe someone can help me with this issue. My .yml file name: CI/CD Django, Postgress on: [ push ] jobs: build: runs-on: ubuntu-latest services: postgres: image: postgres:12.5 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github-actions ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Python 3.10 uses: actions/setup-python@v2 with: python-version: "3.10" - name: Install Requirements run: | pip install -r requirements.txt - name: Run migration env: DEBUG: "0" SECRET_KEY: CD_CI_TEST_KEY USER: postgres PASSWORD: postgres NAME: github-actions HOST: localhost PORT: 5432 run: | python manage.py migrate - name: Run tests env: DEBUG: "0" SECRET_KEY: CD_CI_TEST_KEY USER: postgres PASSWORD: postgres NAME: github-actions HOST: localhost PORT: 5432 run: | python manage.py test Models class Chat(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, … -
Use Bounding Box on Image in Django
I am making a web based image annotation tool in using Django. I want to use a bounding box over my image that is displaying on the webpage. Can someone suggest a technique on how to achieve it please. Thanks -
Importing Json into Django Database from url
I wrote a script which will basically import data from a json file and store it in the database of my Django Application. I'm simply pointing to a json file and i'm adding "facilities" if they don't exist or they get updated if the last modified date changes. It worked perfectly fine until i couldn't import the json file locally anymore and made some smaller changes to use an external json file. When i run the importer now it will only import the first two facilities and then tell me that all others are up to date even though they don't exist. I even modified and tested the json file manually to make sure it is not caused by a bug inside the json file. I will add the old code plus the modified code below. One of the main differences is that this part is now at the very bottom in the new version after the if statement: for key, data_object in data.items(): And also that i'm using "import requests" in the new version with the following code at the bottom of the file. My feeling is that i made a mistake right there: def handle(self, *args, **options): """ … -
How to use the django test's database with Selenium?
I am testing my django app with django TestCase class. For unit tests and integrations tests I encountered no problem with the database django create then destroy for the tests. But now i want to do some functional test using selenium. The problem is that selenium seem to not be able to access the db. Here is the test code of my test : class HostTest(LiveServerTestCase, TestCase): def setUp(self): self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) # Setting up temporary test database # Setting up products self.product1 = Product.objects.create( id=1, name="apple", url="apple_url", nutriscore="A", img_url="apple_img_url", kcal=101, fat=201, protein=301, sugar=401, ) def tearDown(self): self.driver.close() def test_new_user_reserach_and_add_favorite(self): driver = self.driver driver.get(self.live_server_url) self.assertIn("Accueil", driver.title) search_bar = driver.find_element_by_name("product_searched") search_bar.send_keys("apple") search_bar.send_keys(Keys.ENTER) self.assertIn("Recherche", driver.title) product = driver.find_element_by_class_name('product-presentation') For this I have an error at the last line, and the error is long but its basically tell me that selenium cant find the element. I tried to print product1 in the test and it work. That why I'm pretty sure that the problem is with Selenium. Here is the code of my view : def product_research(request): no_repetition_result = [] vectors = SearchVector('name', weight='A') + SearchVector('category__name', weight='B') query = SearchQuery(f'{request.GET.get("product_searched")}') research_result = Product.objects.annotate(rank=SearchRank(vectors, query)).order_by('-rank') for product in research_result: if product not in no_repetition_result: … -
retrieving the last instance of a model in another model's modelSerializer in django rest framework
I am creating rest APIs for a website in which users can purchase one of the provided subscriptions. In this website there is a user-info API which returns the information about the logged in user which can be used to show their info on the website. The problem is that, the mentioned API's serializer is a modelSerializer on the "User" model and the information that I want to return is the instance of "Subscription" model which the latest instance of "SubPurchase" model refers to. These are my serializers, models and views.And I need to somehow return the user's current subscription's ID and name along with the user's information. If you have any further questions, ask me in the comments and I'll answer them. # models.py class User(AbstractBaseUser, PermissionsMixin): userID = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True, validators=[RegexValidator(regex="^(?=[a-z0-9._]{5,20}$)(?!.*[_.]{2})[^_.].*[^_.]$")]) email= models.EmailField(max_length=100, unique=True, validators=[EmailValidator()]) name = models.CharField(max_length=100) isSuspended = models.BooleanField(default=False) isAdmin = models.BooleanField(default=False) emailActivation = models.BooleanField(default=False) balance = models.IntegerField(default=0) objects = UserManager() USERNAME_FIELD = 'username' class Subscription(models.Model): subID = models.AutoField(primary_key=True) nameOf = models.CharField(max_length=50) price = models.PositiveIntegerField() salePercentage = models.PositiveIntegerField(default=0) saleExpiration = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return f"{self.nameOf}" class SubPurchase(models.Model): price = models.PositiveIntegerField() dateOf = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) subscription = models.ForeignKey(Subscription, null=True, … -
Render multiple html files and views and show it in single html file Django
Below shown are my files index.html <!-- Modal --> <div class="modal fade modal{{link.id}}" id="createmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Create Contact</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form method='POST'> {% csrf_token %} <div class="modal-body"> {{form.as_p}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="Submit" class="btn btn-primary btn-delete" data-sid="{{link.id}}" >Create Contact</button> <input type="submit" class="btn btn-primary save-btn"> </div> </form> </div> </div> </div> new_contact.html <!-- Modal --> <div class="modal fade modal{{link.id}}" id="createmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Create Contact</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form method='POST'> {% csrf_token %} <div class="modal-body"> {{form.as_p}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="Submit" class="btn btn-primary btn-delete" data-sid="{{link.id}}" >Create Contact</button> <input type="submit" class="btn btn-primary save-btn"> </div> </form> </div> </div> </div> views.py def new_contact(request): data = Contact.objects.all() form = CreateContactForm() if request.method == 'POST': form = CreateContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Link edited successfully.') else: messages.error(request, form.errors) return render(request,'app/editModal.html', context={'form':form,'data':data}) def index(request): data = Contact.objects.all() return render(request,'app/editModal.html', context={'form':form}) I want to render new_contact.html file in index.html file. I have already used include tag but it doesn't work for my requirement. include tag includes that html file into the index file but does … -
How to login in django using desktop app? [closed]
I have a django app running on localhost, what i need to do is login on the django server using credentials provided on a desktop app that was made using pyside2. -
How to share one session between react and django?
I have frontend on React and backend on Django. They are running on two different ports. The Goal is to save data from frontend to Django session and having access to it on every request. But thing is it creates new session everytime I make a request This is how request looks like on React side const data = await axios.post( "http://127.0.0.1:8000/api/urls/", qs.stringify({ long: long_url, subpart: subpart, }) ); And this is how it processed by view in Django where i am trying to create list of urls and append it every time. @api_view(['POST']) def users_urls(request): if request.method == 'POST': long_url = request.POST.get('long') subpart_from_input = request.POST.get('subpart') if 'users_urls' in request.session: request.session['users_urls'].append(short_url) else: request.session['users_urls'] = [short_url] return Response(short_url) It works as it should work when i make requests from Postman. But there is some trouble with react. Help me please to figure this out -
Django 'python manage.py runserver' does not work. Is Python setup correct?
I downloaded Django via pip install djange django-admin startproject xyz is working fine. but when I do python manage.py runserver or similar .. the following error