Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
First grid item from a pandas dataframe isn't displayed properly when using Flask/Django
I'm kind of new to this and I'm trying to display a pandas dataframe in a grid using Django, but the first item of the dataframe is not displayed as a grid item. Dataframe: | Index | Title | | -------- | -------- | | 0 | item1 | |1 | item2 | |2|item3| html template: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> } .grid-container{ display: grid; grid-template-columns: repeat(auto-fill,minmax(200px,1fr)); gap: 16px; } .grid-item{ border: 1px solid #000000; padding: 10px; text-align: center; } <body> <div> <h1>Sample DataFrame</h1> <div class = 'grid-container' {% for product in html_data_df %} <div class = 'grid-item'> <h1>{{product.Title}}</h1> </div> {% endfor %} </div> </div> </body> </html> views.py: def display_products(request): data_df['Image_HTML'] = data_df['Image_link'].apply(lambda x: f'<img src="{x}" width="100">') html_data_df = data_df.to_dict(orient='records') return render(request, 'price_comp/display_products.html', {'html_data_df': html_data_df}) I've also tried using flask, but I am getting the same problem. Item1 is not displayed properly, i've tried shifting the index so that it starts on 1 instead of 0, but that doesn't work either. -
A Start Up. Starting a Start UP [closed]
Not a question I have been thinking this for quite a time.. why don't some of us team up and create our own company?? We can share our own ideas and make websites come to life.. Like.. I can handle Back end and Web design part but i am bad at front end especially DOM part.. Like i have some ideas and i am pretty sure some of you guys have too so lets team up 6-7 of Us 2 and than start it ASAP. If interested DM me in either insta @sandeshpathak0012 or directly in this stack overflow. Blanksacsacsacscs sacac -
Django can't change username in custom User model
I have the following User model in Django's models.py: class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, primary_key=True) full_name = models.CharField(max_length=65, null=True, blank=True) email = models.EmailField( max_length=255, unique=True, validators=[EmailValidator()] ) When trying to update a username via shell python manage.py shell: userobj = User.objects.get(username="username1") userobj.username = user.lower() userobj.save() It seems that it is trying to create a new user, for which the UNIQUE constraint of the e-mail is violated: django.db.utils.IntegrityError: UNIQUE constraint failed: data_app_user.email Any solutions? Thank you! -
How to solve NSInternalInconsistencyException in django
guys i am trying to run this project from github here . i cloned the repo and installed django (it doesn't have requirements file) and tried to run the project it runs till login, register page but then it goes bad. It throws this error (base) rishikapadia@MacBook-Air budget_project % python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: budget_app.ExpenseInfo: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BudgetAppConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. System check identified 1 issue (0 silenced). You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth. Run 'python manage.py migrate' to apply them. March 02, 2024 - 13:35:25 Django version 5.0.2, using settings 'budget_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [02/Mar/2024 13:35:27] "GET / HTTP/1.1" 200 1547 [02/Mar/2024 13:35:30] "GET /sign_up HTTP/1.1" 200 2137 [02/Mar/2024 13:35:56] "POST /sign_up HTTP/1.1" 302 0 /Volumes/Work/Finance/Django/Django-Budget-App/budget_project/budget_app/views.py:19: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail. fig,ax=plt.subplots() *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: … -
Using the widget, I used the CheckboxSelectMultiple field, as a result, the queryset returns None
I put a form in the template and implemented the addition of an article. As a result, the user fills in the information, especially the categories that are used in multiple relationships and clicks submit. The information can be saved. Here, it is important that the user clicks on one of the categories. Everything, but as a result, the article with correct information but the categories returns None, this is my problem. models.py class CategoryArticle(models.Model): title = models.CharField(max_length=200, verbose_name='عنوان') url_title = models.CharField(max_length=200, verbose_name='عنوان در url') is_active = models.BooleanField(default=True, verbose_name='فعال / غیرفعال') def __str__(self): return self.url_title class Meta: verbose_name = 'دسته بندی مقاله' verbose_name_plural = 'دسته بندی های مقاله' class Article(models.Model): title = models.CharField(max_length=200, verbose_name='عنوان مقاله') slug = models.SlugField(null=True, blank=True, verbose_name='اسلاگ') article_category = models.ManyToManyField(CategoryArticle, verbose_name='دسته بندی مقاله') short_description = models.TextField(verbose_name='توضیح مختصر') author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='نویسنده') created_at = models.DateTimeField(auto_now_add=True, verbose_name='تاریخ ایجاد مقاله') views = models.PositiveIntegerField(default=0, verbose_name='تعداد بازدید', editable=False) preview_image = models.ImageField(upload_to='images/previews_articles/', verbose_name='پیش نمایش مقاله') content = CKEditor5Field('Text', config_name='extends') audio_file = models.FileField(upload_to='audio_files/', null=True, blank=True, verbose_name='فایل صوتی', validators=[validate_audio_file]) video_file = models.FileField(upload_to='videos/', null=True, blank=True, verbose_name='فایل ویدیویی', validators=[validate_videos_file]) is_active = models.BooleanField(default=True, verbose_name='فعال / غیرفعال') is_important_new = models.BooleanField(default=False, verbose_name='اخبار مهم') is_special = models.BooleanField(default=False, verbose_name='ویژه') forms.py class CreateArticleForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField( label="دسته بندی مقاله", queryset=CategoryArticle.objects.filter(is_active=True), widget=forms.CheckboxSelectMultiple(), required=False, … -
How To add paypal subscription in my django rest_framework websites
I'm devlopping a website by django rest_framework and react and I want to use the subscription so that the user manager should pay for example 20 dollars per month ,my project contains two types of users the Resident and Manager ,every Resident user should belong to a village or Dwar as I created , the village is created by a Manager so those residents users has the Manager as responsible for them and if the manager didn't pay no user can log in this my models .py from django.db import models from django.contrib.auth.models import AbstractUser from rest_framework.authtoken.models import Token from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from dwar.models import Dwar # from time import timezone from datetime import timezone import time # Create your models here. class CustomUser(AbstractUser): territorial=models.CharField(max_length=80) phone_number=models.CharField(max_length=15) is_real=models.BooleanField(default=False) is_resident=models.BooleanField(default=False) is_manager=models.BooleanField(default=False) def __str__(self) : return self.username def fullname(self): return f'{self.first_name} {self.last_name}' class Manager(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE,related_name='manager') village_name=models.CharField(max_length=60) manimg=models.ImageField(blank=True,null=True) is_has_dwar=models.BooleanField(default=False) def __str__(self): return self.user.username class Resident(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE) number_of_water_meter=models.CharField(max_length=60,default='o') selected_village_name=models.ForeignKey(Dwar,on_delete=models.SET_NULL,null=True) the_village=models.CharField(max_length=90) name=models.CharField(max_length=90) resimg=models.ImageField(blank=True,null=True) def __str__(self): return self.user.username class Fatoura(models.Model): created_by=models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='the_manager') sendit_to=models.ForeignKey(Resident,on_delete=models.CASCADE,related_name='fatoras') name=models.CharField(max_length=90) village=models.CharField(max_length=90) number_of_water_meter=models.CharField(max_length=60,default='o') created_at=models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return self.number_of_water_meter class MessageToResident(models.Model): created_by=models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='who_create') send_to=models.ForeignKey(Resident,on_delete=models.CASCADE,related_name='messago') message=models.TextField(max_length=600) is_global=models.BooleanField(default=False) name_of_manager=models.CharField(max_length=70,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return self.created_by.username I already worked with paypal payment … -
Django Add field values as per month and year wise and consolidate
I am trying to consolidate the field values in Django 3.2 and add them and group them month & year wise, but I am unable to get it work, below is my code. models.py class Event(models.Model): name = models.CharField(max_length=255, null=True) MONTH = ( ('january', 'january'), ('february', 'february'), ('march', 'march'), ('april', 'april'), ('may', 'may'), ('june', 'june'), ('july', 'july'), ('august', 'august'), ('september', 'september'), ('october', 'october'), ('november', 'november'), ('december', 'december'), ) YEAR = ( ('2023', '2023'), ('2024', '2024'), ('2025', '2025'), ('2026', '2026'), ('2027', '2027'), ('2028', '2028'), ('2029', '2029'), ('2030', '2030'), ) month = models.CharField(max_length=255, null=True, choices=MONTH) year = models.CharField(max_length=255, null=True, choices=YEAR) event_price = models.IntegerField(null=True) def __str__(self): return self.name views.py from django.db.models import Sum def viewEvent(request): event = Event.objects.all() total_event_price = Event.objects.values(sum('event_price)) context = {'event': event, 'total_event_price: total'} return render(request, 'view_event.html', context) view_event.html <div class="card card-body"> <table class="table table-sm"> <tr> <th>Year</th> <th>January</th> <th>February</th> <th>March</th> <th>April</th> <th>May</th> <th>June</th> <th>July</th> <th>August</th> <th>September</th> <th>October</th> <th>November</th> <th>December</th> <th>Total</th> </tr> {% for items in event %} <tr> <td>{{ items.year }}</td> <td>{{ items.month }}</td> <td>{{ items.total }}</td> </tr> I want the entries added as per month wise and another total which adds all month wise as per the year, which is total field. how do I achieve ? -
I'm struggling to learn Django Framework
How do I learn Django? I understand python basics such as functions, classes etc. I'm trying to learn Django for more than six months. Actually I understand the concept a little but it seems I've not learnt anything at all as I cannot memorize every nuts and bolts of Django framework. I'm feeling so frustrated nowadays. It's may not be relevant but want to mention that I'm 39 years old. Why I'm so struggling? Is it because of my age as my brain has become slow? Or I'm skipping something? Here I want to mention that I understand the basics of html and CSS. I've not learnt JavaScript yet. Thanks. I've tried a number of books and YouTube videos. I'm spending one or two hours to learn the framework everyday. But I'm seeing no progress. -
Convert sql query to django orm query
i want convert query to django orm how to? select name from devices_device ORDER BY CAST(SUBSTRING(name FROM '^[0-9]+') AS INTEGER), SUBSTRING(name FROM '[^0-9].*') -
Where should I place the logic for one entity altering the state of another entity within Django REST Framework?
Imagine a simple app where user's can post some requests (for example - they need some help, food) and other users can through chat give some reply to this request. Here are my simplified models: class UserRequest(models.Model): ACTIVE = 'active' INACTIVE = 'inactive' STATUS_CHOICES = [ (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) request_text = models.TextField() status = models.CharField(max_length=8, choices=STATUS_CHOICES, default=INACTIVE) class RequestChat(models.Model): user_request = models.ForeignKey(UserRequest, on_delete=models.CASCADE) class ChatMessage(models.Model): text = models.TextField() chat = models.ForeignKey(RequestChat, on_delete=models.CASCADE) I need to implement this type of functionality: When at least one chat message is created (written to chat) - the associated request status should be changed from INACTIVE to ACTIVE. Should this logic be placed in the save() method of the ChatMessage model or should it be handled using a Django signal? Or perhaps there might be another way of doing this? Additionally, can you recommend any resources such as books, articles, or videos that provide guidance on this topic? -
Django dynamically filter objects and render in template
I produced a report that provides a count of how many musicians played each genre at a festival. the musician model has a genre field that is a foreign key to the genre table. I can successfully produce a template that renders this report, but it is hard coded in a way that is not ideal. I would like to be able to have users edit the genre table without me having to edit the view and template to account for new genres. What direction can I take this where the genres played at a festival are identified dynamically, based on the musicians that played within the daterange of the festival, then passed as context to the template? See model, template, and view below: Model: class Festival(models.Model): id = models.AutoField(db_column='Id', primary_key=True, blank=True, null=False) number = models.TextField(db_column='Number', blank=True, null=True) startdate = models.DateField(db_column='StartDate', blank=True, null=True) enddate = models.DateField(db_column='EndDate', blank=True, null=True) class Meta: managed = True db_table = 'Festival' verbose_name_plural = 'Festival' class Musician(models.Model): id = models.AutoField(db_column='Id', primary_key=True, blank=True, null=False) startdate = models.DateTimeField(db_column='StartDate', null=False) enddate = models.DateTimeField(db_column='EndDate', blank=True, null=True) genre = models.ForeignKey('Genre', models.DO_NOTHING, db_column='GenreId', null=True) class Meta: managed = True db_table = 'Musician' verbose_name_plural = 'Musician' class Genre(models.Model): id = models.AutoField(db_column='Id', primary_key=True, blank=True, … -
POST data only if you are authenticated user- django rest framework
models.py class OpeningHours(models.Model): day_of_week = models.IntegerField(choices=((0, 'Sunday'), (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'))) opening_time = models.TimeField() closing_time = models.TimeField() serializer.py class OpeningHoursSerializer(serializers.ModelSerializer): class Meta: model = OpeningHours fields = '__all__' read_only_fields = ("user",) views.py class OpeningHoursViewSet(viewsets.ModelViewSet): queryset = OpeningHours.objects.all() serializer_class = OpeningHoursSerializer authentication_classes = [CustomAuthentication] permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) authentication.py class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) I want only authenticated user to be able to perform POST method . I have set the key as HTTP_USERNAME and value as username (which i have created in django admin) on postman header before making a post request but im still getting error: "detail": "Authentication credentials were not provided." } How so i solve this. -
Advanced filtering for filtering properties in Django
Is anyone able to help me or give me some hints regarding Django? Specifically, I'm working on a real estate sales application. I'm having trouble with handling filters in the GET method as shown in the screenshot below. I've been struggling with this for over a month and still no progress! I keep deleting code because something is always not working. Basically, when selecting, for example, the 'Listing Status: Rent', there should be a reload and all properties with the 'Rent' status should be displayed. The same goes for categories, price range, etc. Furthermore, when selecting the 'Listing Status', the subsequent filters should refresh and be listed according to the displayed properties with the 'Rent' status. Meaning, when selecting the 'Rent' status, there should be a reload and all categories assigned to properties with the 'Rent' status should be displayed, and similarly for the subsequent filters. Is anyone able to help? I've been struggling with this and I'm really frustrated already 😞 enter image description here -
Django Static Files Documentation, not working, am I missing something?
I am fairly new to django and programming too. I have seen the static question asked here severally, but I have a documentation specific question. According to the official django documentation, the static files should be put inside the app folder, then create a subfolder named static, then app, then the file. for example, I have a project called Sheecooks. Inside the sheecooks, I have several django apps and among them is the nav app. so here is how i structured my css. Sheecooks > nav>static>nav>styles.css. However, my styles were not reflecting. I tried everything that has been suggested on this platform. The 'django.contrib.staticfiles'app is installed in my settings.py and yes i checked for all the spelling mistakes. I was following the documentation but changing the polls example into nav but I didn't get it to work until I removed the nav subfolder. So what I have at the moment is sheecooks>nav>static>style.css. While this works, i am afraid that the documentations states that it "it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would … -
when I wanna add order in admin panel I see this Error
My model is : class Order(models.Model): id = ShortUUIDField(primary_key=True, unique=True, length=6, max_length=6, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders') orderproducts = models.ManyToManyField(Product, through='OrderProduct') total_amount = models.DecimalField(default=00.00, max_digits=10, decimal_places=2 ,blank=False) # final order price = total items quantity*total items price order_date = models.DateTimeField(auto_now_add=True, auto_now=False) finish = models.BooleanField(default=False, blank=True, null=True) country = CountryField(blank_label="(select country)", multiple=False) city = models.CharField(max_length=100, blank=False) zip_code = models.CharField(max_length=100, blank=False) state = models.CharField(max_length=100, blank=False) street = models.CharField(max_length=100, blank=False) phone_no = PhoneNumberField(null=True, blank=False) and I get this error : AttributeError at /admin/ecommerce/order/add/ 'BlankChoiceIterator' object has no attribute 'len' Request Method: GET Request URL: http://127.0.0.1:8000/admin/ecommerce/order/add/ Django Version: 5.0.2 Exception Type: AttributeError Exception Value: 'BlankChoiceIterator' object has no attribute 'len' How can I fix this Error . When I clicked add order in admin panel I get this Error . I cloned this code from github and I think it must work -
Undefined Usernames Issue in Django Channels WebSocket Consumer
I have created django consumers.py and a frontend in html and css to disply messages sent by a user, the profile picture of the sender and the username of the sender but anytime i open the browser, the message displays well but the username appears as undefined . eg @Undefined: How are you this is my consumers.py `User = get_user_model() class DiscussionRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f"discussion_room_{self.room_name}" # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Get or create the VirtualRoom instance based on the provided room_name virtual_room = await self.get_virtual_room() if virtual_room is not None: # Send existing messages and old messages to the new user old_messages = await self.get_old_messages(virtual_room) for message in old_messages: await self.send(text_data=json.dumps({ 'message': message['content'], 'user_id': message['user'], 'user_picture': await self.get_user_profile_picture(message['user']), })) async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] user_id = self.scope["user"].id # Get the VirtualRoom instance based on the extracted room name asynchronously virtual_room = await self.get_virtual_room() # Check if the VirtualRoom instance exists if virtual_room: # Save message to the database with the VirtualRoom instance asynchronously await … -
```TypeError: memoryview: a bytes-like object is required, not 'bool'``` when trying to add data to my database
I have been working with Django for a while now whenever I apply this BaseModel: class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) is_active = models.BinaryField(default = True) class Meta: abstract = True to any model for example: class MyModel(BaseModel): text = models.TextField(max_length=200) and when I make migrations and migrate everything works fine and migrates go through and then I registered my models to admin site to add some data to check if my models are working and whenever I hit save to add new data I'm getting this error: nternal Server Error: /admin/ass/ass/add/ Traceback (most recent call last): File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\contrib\admin\options.py", line 715, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper result = _process_exception(request, e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\views\decorators\cache.py", line 80, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\contrib\admin\sites.py", line 240, in inner return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\contrib\admin\options.py", line 1944, in add_view return self.changeform_view(request, None, form_url, extra_context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\utils\decorators.py", line 48, in _wrapper return … -
Why is Vercel proxy to API route not working?
I have my frontend in Vite (React, TS) and backend in Django. When I make request to backend API route from frontend, it works perfectly fine with requests to the correct API route in local, but the requests are not directed to the correct API route in production. I have my frontend deployed in Vercel and backend deployed in Render. I have the following backend API routes: api/register api/login vite.config.ts import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; // https://vitejs.dev/config/ export default defineConfig({ server: { proxy: { "/api/": { target: "http://localhost:8000", changeOrigin: true, }, }, }, plugins: [react()], }); vercel.json { "rewrites": [ { "source": "/api/:path*", "destination": "https://mydomain.onrender.com/:path*" } ] } When the client makes request to api/login, the following error message is printed: XHR POST https://mydomain.vercel.app/api/login/ [HTTP/2 404 37ms] The frontend should have sent request to https://mydomain.onrender.com/api/login/ but it sends requests to the frontend route https://mydomain.vercel.app/api/login/ How to fix this? Thanks. -
The problem of not finding React static files in Python
The back end of my project is Python and I have used RteactJS for the front end. When using the python manage.py runserver command, the project runs successfully, but it does not find the static files. setting: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/clientApp/build/static'), ] STATIC_ROOT = BASE_DIR / "static" STATIC_URL = '/static/' url : urlpatterns = [ path('', index, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Error 400: redirect_uri_mismatch when running django project
Newbie here! I want to download all the images from a google drive folder and then show them in a basic html. I am trying to authenticate with google so I can access to the folder, but when I try I always get this error (https://i.stack.imgur.com/Dl52o.png) What it's weird is that the port changes every time I run the project. (https://i.stack.imgur.com/4YQuS.png) The server is running in the port 8000 of localhost. Here the code for the views.py from django.shortcuts import render from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload from google.auth.transport.requests import Request from pathlib import Path import os # Google Drive API scopes SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] # Path to credentials file credentials_path = 'credentials.json' def index(request): # Load existing credentials if available if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) else: # If not available, initiate OAuth 2.0 flow flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for future use with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) # Build the Google Drive service service = build('drive', 'v3', credentials=creds) # Google Drive folder ID folder_id = myfolderID # Create the target directory if it doesn't exist target_dir = os.path.join(Path(__file__).resolve().parent, 'images') os.makedirs(target_dir, exist_ok=True) … -
How to Create Images Dynamically Based on User Input, AI, & Images Uploaded
I want to create an app in either Python or Next.js (unless someone has a better &/or easier suggestion for how to do it?) that generates images based on a user's input from a form. I want visitors to my site to be able to generater multiple different image sizes each using the same form data entered by the user in a form. I'd also like my users to be able to choose from various options and I’mage templates, but what is the best &/or easiest way of doing this? If the project was easy enough I'd be willing to have a go at building it myself, but only if I can find the basic component features already developed to be integrated into the app. Other features I'd like to incorporate: Coupon or social share requeired to use tool User registration & the user's history of images generated with the anbility to access the images at a short link generated dynamically QR Codes generated and embedded into the generated image Ability for user to be able to upload both a picture or avatar to embed into dynamic image, and the ability to upload a custom background image to use in … -
How to connect vercel frontend deployment to backend deployed on aws ec2 instance
The backend is correctly deployed on a specific port in ec2 instance but it's http. But the frontend is deployed on vercel which uses https and I face the mixed content error. So how do I convert the backend server to https? I had trouble deploying the frontend is deployed because of the nginx configuration issues, hence why i decided to use vercel I do have a public DNS server link to this ec2 instance but its not responsive when i run Django server. I want the backend deployed to connect to the frontend either using ec2 instance or vercel. The backend deployment is working with ec2 instance but how do i connect it to frontend deployment? -
csrf error when simulating a post request in django
the form i want to simulate <form action="{% url 'reset' %}" name="form1" id="form1" method="POST"> {% csrf_token %} <div class="py-1"> <input class="focus:outline-none w-full p-1 border border-gray-300 rounded-md placeholder:font-light placeholder:text-gray-500 placeholder:text-sm pl-2" type="text" name="username" id="" placeholder="username" required> </div> <div class="flex justify-between w-full py-4"> <div class="mr-24"> <span class="text-md text-gray-400"> Dont'have an account? </span> <a class="font-bold text-black"><a href="/signup" class="font-bold">Sign up </a></span> </div> <span class="font-bold text-md"><a href="{% url 'signin' %}"class="font-bold">sign in </a></span> </div> <button class="w-full bg-black text-white p-2 rounded-lg mb-6 hover:bg-blue-400 hover:text-white " type="submit" > submit </button> </form> noting that i'm adding a form_name attribute to the post request in js before sending it document.getElementById('form1').addEventListener('submit', function(event) { event.preventDefault(); // Prevent default form submission var form = this; var formData = new FormData(form); formData.append('form_name', 'form1'); fetch(form.action, { method: 'POST', body: formData, headers: { 'X-CSRFToken': '{{ csrf_token }}' } }) .then(response => response.json()) .then(data => { if (data.show_form2) { showForm2(data); } if (data.messages) { const messages = JSON.parse(data.messages); showMessages(messages); } }).catch(error => console.error('Error:', error)); }); and the part of view that simulate the post request data = {'username': request.user.username, 'form_name': "form1"} csrf_token = get_token(request) response = requests.post('http://127.0.0.1:8000/reset', data=data, headers={'X-CSRFToken': csrf_token}) but im getting this error Forbidden (CSRF cookie not set.): /reset please help -
Unable to get submit buttons to work using the django-formset library (nothing happens upon click)
I am using the django-formset library to design an invoicing program. When I fill out a new form and click the submit button, nothing happens. I've pored over the documentation and followed the examples but no luck. Django(5.0.2) and django-formset(1.3.8) are updated. I have a few ideas what could be causing the problem and corresponding questions but am unsure how to test them out as I this is the first time I'm working with css / bootstrap / javascript / typescript (I only have a small background in Python). Does it matter whether you load scripts in the base template or child template? Do the order of scripts matter and does it matter where in the head we're loading scripts relative to other elements? A fresh set of eyes on this would be greatly appreciated because I am stuck! I get the feeling this is something very simple I'm overlooking. models.py: class Customer(models.Model): first_name = models.CharField('First Name', max_length=55, blank=True) last_name = models.CharField('Last Name', max_length=55, blank=True) phone = models.CharField('Phone Number', max_length=10, blank=True) alt_phone = models.CharField('Alt Phone Number', max_length=10, blank=True) company = models.CharField('Company', max_length=55, blank=True) email = models.EmailField('Email', null=True, blank=True) address = models.CharField('Address', max_length=55, blank=True) city = models.CharField('City', max_length=55, blank=True) state = … -
Place a media image in the template
What I want to achieve is for the user to send their image through the form and save it in a context and display it in the template class PerfilGestion(View): def get(self,request,*args,**kwargs): return render(request,"Perfil.html",{"Form":Perfil}) def post(self,request,*args,**kwargs): Formulario = Perfil(request.POST, request.FILES) if Formulario.is_valid(): Formulario.save() Imagen = Formulario.cleaned_data["Imagen"] Nombre = Formulario.cleaned_data["Nombre"] return render(request,"Perfil2.html",{"Imagen":Imagen,"Nombre":Nombre}) else: return render(request,"listadeerrores.html",{"Form":Formulario}) But I don't know how to place it in the template