Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to escape out of django tags?
I am currently working on a small project where I am using HTMX with Django. {% render_field form.email class="form-control my-3" placeholder="Email" hx-post="{% url 'accounts:verify-email' %}" hx-trigger="keyup" hx-target="#email-verif" hx-swap="outerHTML" %} {{ form.email.errors|striptags }} However, the code breaks because it thinks the %} portion of the url snippet is close bracket of the whole line. Is there any solution for this? -
Unable to declare javascript variable with a django variable
I am using django and when I assign a django variable to a javascript variable I get the following error. Uncaught SyntaxError: Unexpected token '&' What Im doing is I passed a variable which is a list of strings to the template html through the view function Im calling here is the view function: def index(request): class_obj = AllClasses() return render(request, 'index.html', { 'classNames': class_obj.classList }) Then I declared a global JavaScript variable inside index.html like this: <script> var names = {{classNames}}; </script> This results in the following error that Uncaught SyntaxError: Unexpected token '&' Any idea on how to solve this ? -
How to make an api completely independent from the main Django Project?
I have a django project that is hosted internally, and this project feeds the database. I need an API that serves the data of that database to a public domain (that api does not do any DML only selects), but this API needs be hosted in a diferent machine and even if the project that is hosted internally explodes that api needs to keep working. I am using DRF for the api I did an api project that has its own apps, views, serializers and models(those models connect to the db existing table like this) and only have the fields that I need represented. Is this the right way to do this or am I missing something? The thing that I am worried is if one of the columns of a model changes name i will have to change the model in the api, but that is a very rare modification. -
Multiple add to cart buttons on the same page in django
i am trying to add multiple add to cart buttons of products on the same page. i had the code of one add to cart button for one produc in one page but now i am trying to do it for multiple products (a grid) def product(request, category_slug, product_slug): cart = Cart(request) product = get_object_or_404(Product, category__slug=category_slug, slug=product_slug) imagesstring = '{"thumbnail": "%s", "image": "%s", "id": "mainimage"},' % (product.get_thumbnail(), product.image.url) for image in product.images.all(): imagesstring += ('{"thumbnail": "%s", "image": "%s", "id": "%s"},' % (image.get_thumbnail(), image.image.url, image.id)) print(imagesstring) if request.method == 'POST': form = AddToCartForm(request.POST) if form.is_valid(): quantity = 1 #form.cleaned_data['quantity'] cart.add(product_id=product.id, quantity=quantity, update_quantity=False) messages.success(request, 'The product was added to the cart') return redirect('product', category_slug=category_slug, product_slug=product_slug) else: form = AddToCartForm() similar_products = list(product.category.products.exclude(id=product.id)) if len(similar_products) >= 4: similar_products = random.sample(similar_products, 4) context = { 'form': form, 'product': product, 'similar_products': similar_products, 'imagesstring': "[" + imagesstring.rstrip(',') + "]" } return render(request, 'product/product.html', context) here is the view function for one product page. -
Routing does not work in Django: page not found (GET)
I've tried multiple methods of writing views but I don't think it is a problem here. App is installed in settings.py It displays error every time. project structure: structure url.py in apps folder from django.urls import path from . import views urlpatterns = [ path('home_view/', views.home_view) ] apps.py in app folder from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app' urls.py in store folder from django.contrib import admin from django.urls import path, include from app import views urlpatterns = [ path('app/home_view/', include('app.url')), path('admin/', admin.site.urls), ] error message: error -
Fetching data using eact native
I am trying to fetch my user infomations from django database. But I only get the following message {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "ee5e4317-5bb7-4b5f-8e19-7a787cdee766", "offset": 0, "size": 94}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "ee5e4317-5bb7-4b5f-8e19-7a787cdee766", "offset": 0, "size": 94}}, "bodyUsed": false, "headers": {"map": {"allow": "GET, POST, HEAD, OPTIONS", "content-length": "94", "content-type": "application/json", "date": "Sat, 19 Mar 2022 22:02:40 GMT", "referrer-policy": "same-origin", "server": "WSGIServer/0.2 CPython/3.6.8", "vary": "Accept, Origin, Cookie", "x-content-type-options": "nosniff", "x-frame-options": "DENY"}}, "ok": true, "status": 200, "statusText": "", "type": "default" I can use it to determine if the status is OK to long in, but I would like to be able to gather the user information and send them to the next page. Any help? -
Update global variable in an asychrounouus way in Django
I have a tacky problem. On my website, you can find current price tracker for crypto coins as a purely content filler element. I get my data from coin API, you are allowed 100 request's per day. def crypto_api_prices(request): api_base_url = 'https://rest.coinapi.io/v1/exchangerate/' api_key = '===============' headers = { 'X-CoinAPI-Key': api_key, } crypto_tickers = ["BTC","ETH","ETC","RVN"] crypto_api_links = [api_base_url+x+"/"+"USD" for x in crypto_tickers ] crypto_api_prices = [requests.get(x, headers=headers).json()['rate'] for x in crypto_api_links] context = { "cryptoPrices":crypto_api_prices } return context I'm calling this function in my home view. Unfortunately, if I have couple of visitors daily this generates 100 requests pretty fast and my element isn't working anymore. What I want to achieve is set crypto_api_prices as a global variable and update it every hour, so no matter how many users will be on my page I will generate only 24 requests. Is this a good idea? Are there alternatives? Of course I can buy more requests but this website is a "passion" project so I want to keep costs down -
DRF IsAuthenticated seems to be not working properly in remote server
I started a migration of a personal project between two servers and I get a very weird behavior. My APP uses TokenAuthentication from DRF and is working perfectly in a local environment and in the previous server but in the new one I get the following error: "Authentication credentials were not provided.". At the first time I thought that it was because Nginx was not sending the right headers to the backend but after doing some debugging I found that the headers were ok. Im totally lost at this point, hope I can get some help. Thanks to everyone. My REST_FRAMEWORK config: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", #"rest_framework_simplejwt.authentication.JWTAuthentication", ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10, "DEFAULT_FILTER_BACKENDS": [ "django_filters.rest_framework.DjangoFilterBackend" ], } Current view: class UserInfoView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = self.request.user return Response({"type": user.user_type, "username": user.username}) Request made by CURL: % curl 'http://myapp.com:8000/api/user-info/' \ -H 'Connection: keep-alive' \ -H 'sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"' \ -H 'Accept: application/json, text/plain, */*' \ -H 'Authorization: Token 144e22bc66c9b145596690c8673ef9aaefbaad1d' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36' \ -H 'sec-ch-ua-platform: "macOS"' \ -H 'Sec-Fetch-Site: cross-site' \ -H 'Sec-Fetch-Mode: … -
Django 3.2 makemigrations ProgrammingError: table doesn't exist for abstract model
I'm currently updating my website to use Django 3.2, but I use the zinnia blog which is no longer receiving updates. I'm making the necessary changes to bring it up to compatibility with 3.2 but I'm now getting the error that the AbstractEntry table doesn't exist. This is, however, an abstract table so I'm confused why it would try to find the table at all. Full traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.8/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/dist-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.8/dist-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.8/dist-packages/zinnia/models/__init__.py", line 4, in <module> from zinnia.models.entry import Entry File "/usr/local/lib/python3.8/dist-packages/zinnia/models/entry.py", line 6, in <module> class Entry(load_model_class(ENTRY_BASE_MODEL)): File "/usr/local/lib/python3.8/dist-packages/zinnia/models_bases/__init__.py", line 18, in load_model_class _class … -
How do I fix: Your branch is ahead of 'heroku/main' by 1 commit. (Heroku/Django)
I am trying to drill down a major problem I have created syncing my Heroku and local PostgreSQL databases. I believe I may have found the source of the problem: I am new to web development and this is my first deployed application so I have made some clumsy mistakes along the way. My current flow for pushing is this: Local migration: python3 manage.py makemigrations Commit: git add and git commit -a Deploy: git push heroku main Migrate to server: heroku run python3 manage.py migrate I currently get this message: On branch main Your branch is ahead of 'heroku/main' by 1 commit. It looks like my Heroku DB may be out of sync by 1 commit with my local db - hence I am getting a whole host of errors in my deployed application. I would like to know how to rectify this and hope to have some advice prior to doing anything to make sure I don't mess it up. Below is the terminal log for the push that led to the above message. I am not sure if the WARNINGS are linked to the current issue, because they reference STATICFILES I assume not. Terminal Log (venv) xx % … -
How to get IntergrityError data Django
I have an IntegrityError data as follow : ERROR: Duplicate key value breaks unique constraint "CampaignNamingTool_year_month_advertiser_na_aedc5c8c_uniq" DETAIL: The key “(year, month, advertiser, name, kpi, type_of_format, device)=(2022, 03, FR - Python, Paris, CPV, Multi-device, IAB)” already exists. I would like to get the key: (year, month, advertiser, name, kpi, type_of_format, device)=(2022, 03, FR - Python, Paris, CPV, Multi-device, IAB)” already exists. How can I do that? Any help is appreciated try: CampaignNamingTool.objects.bulk_create(list_of_campaign_naming_tool) except IntegrityError as e: messages.error(request, e) return redirect('bulk_create_campaign_naming_tool') else: msg = "Campaigns successfully uploaded" messages.success(request, msg) return redirect('bulk_create_campaign_naming_tool') -
When to use OAuth in Django? What is it's exact role on Django login framework?
I am trying to be sure that I understand it correctly: Is OAuth a bridge for only third party authenticator those so common like Facebook, Google? And using it improves user experience in secure way but not adding extra secure layer to Django login framework? Can I take it like this? Thanks in advance! -
Submitting 2 custom Crispy Forms with 1 button Django
I have 2 forms with the second form referencing the first form. I can get the forms to execute correctly using crispy forms, however, when I customize each form using helper = FormHelper() they will no longer submit together. Essentially one form is submitted and the other form thinks it is missing all of its input data. Forms.py from django.forms import ModelForm, forms from .models import Item, Item_dimensions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column # Create the form class. class List_Item_Form(ModelForm): class Meta: model = Item exclude = ('id','creator','created_on','updated_on' ) helper = FormHelper() helper.layout = Layout( Row( Column('item_name', css_class='form-group col-md-6 mb-0'), Column('price', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), 'short_description', 'description', Row( Column('main_image', css_class='form-group col-md-2.5 mb-0'), Column('image_2', css_class='form-group col-md-2.5 mb-0'), Column('image_3', css_class='form-group col-md-2.5 mb-0'), Column('image_4', css_class='form-group col-md-2.5 mb-0'), Column('image_5', css_class='form-group col-md-2.5 mb-0'), css_class='form-row' ), 'quantity' ) helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) helper.form_method = 'POST' class List_Item_Dimensions(ModelForm): class Meta: model = Item_dimensions exclude = ('id','item_id') helper = FormHelper() helper.layout = Layout( Row( Column('x_dim_mm', css_class='form-group col-md-4 mb-0'), Column('y_dim_mm', css_class='form-group col-md-4 mb-0'), Column('z_dim_mm', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), 'weight_grams', Submit('submit', 'add_listing') ) helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) helper.form_method = 'POST' I have tried removing helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) and using just one submit button but … -
How to give access for a model object to a specific user in Django
I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to design this as the teacher who creates a class only he can see this after login another teacher shouldn't see his classes and how to add students into that particular class I created the course model class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): form.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) forms.py from django import forms from .models import course class add_course(forms.ModelForm): class Meta: model = course fields = ('course_name', 'course_id', 'course_sec', 'classroom_id') -
Django: How do I check if a User has already read/seen an article?
I am building a web-application for my senior design project with Python and Django. I have a user model that is able to read/write articles to display on the website. I want to make it so that if an article is accessed (read) by a user, it is indicated for only that user that the article has been previously accessed. If I were to log into a brand new user account, the same article wouldn't be indicated as "accessed" for the new account. How can I go about implementing this? Below are my models and views User model class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True, max_length=255, blank=False) university = models.CharField(max_length=200, null=True, blank=True) newsletter_subscriber = models.BooleanField(default=False) is_email_verified = models.BooleanField(default=False) is_staff = models.BooleanField( default=False, help_text=( 'Designates whether the user can log into ' 'this admin site.' ), ) is_active = models.BooleanField( default=True, help_text=( 'Designates whether this user should be ' 'treated as active. Unselect this instead ' 'of deleting accounts.' ), ) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email Article model class Article(models.Model): user = models.ForeignKey( User, on_delete=models.DO_NOTHING, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=False) author = models.CharField(max_length=200, null=True, … -
How can I sum up and display a model method field and also display it on the dashboard without looping through the template in Django
How can I sum up and display a model method field and also display it on the dashboard without looping through the template in Django. I aim to display two values on my dashboard. Total Invested and total Earned. I am able to display total Invested by using the code below. My view investments = Investment.objects.all() total_invested = Investment.objects.aggregate( total_invested=Sum('amount_deposited ')) context = { 'investments': investments, 'total_invested': total_invested, } return render(request, 'list-investments.html', context)``` Then displaying it in my template ```{{total_invested.total_invested}}``` Note: I didnt use **for loop** in my template but I was able to get the total sum invested. I tried repeating the same procedure to get the total amount earned but Its not working. Any idea how to go about it? I also want to know how I can save these model methods values in the database. **My Model Class** ```class Investment(models.Model): PLAN_CHOICES = ( ("Basic - 4% - max 6", "Basic - 4% - max 6"), ("Premium - 5% - max 12", "Premium - 5% - max 12"), ) plan = models.CharField(max_length=50, choices=PLAN_CHOICES, null=True) duration = models.IntegerField(max_length=50, null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) active_investment = models.BooleanField(default=True) amount_deposited = models.IntegerField(null=True) def __str__(self): return self.plan def basic_profit(self): self.basic_pro = … -
How to "open" locked terminal when Django server is running on VSCode?
I am trying to do this Django tutorial and came a cross problem where I cannot write to terminal when Django server is running. Here is excact spot on tutorial: https://youtu.be/uhSmgR1hEwg?list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&t=552 Tuotorial teacher clearly presses some hotkey to "enable" writing to terminal (that reveals PC: C:\Users... line). But what might that hotkey be? -
How to create individual id's per model per user account [Django]
I have come across an issue where everytime a different account that is logged in creates a new collection, the id for that collection is id '1' (127:0.0.1/collections/1), but when you log into another account the and that user creates a new collection, the collection id is '2' (127:0.0.1/collections/2) when I want that one to start as a id = 1. I want each user to have their own ID when creating collections. Same goes for the items inside of the collection. It's like all users on the website are sharing ID's. I wasn't sure what exactly it is I should search up online so I was unable to find any suggestions. Also I am using a built-in user profile instead of a custom one. Any resources or ideas would be great. My Django version is 4.0.3 Models.py class Collection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="collection", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Input(models.Model): name = models.ForeignKey(Collection, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text views.py def create(response): if response.user.is_authenticated: username = response.user.username if response.method == "POST": form = NewInput(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = Collection(name=n) t.save() response.user.collection.add(t) return HttpResponseRedirect("/collections/%s" % username) else: form … -
What in this python program can make my memory goes to sky and freeze the program?
I have written a python program that connect to my mqtt server and process the data! BUt the memory start very low and get higher and higher over time! I would says pretty fast like in 2 hours it goes from ~20% to ~80% if i don't restat the process, it will just hang and stop the program. It does over a week i am looking at the code searching for my errors trying different things and nothings seems to fix the problem!! This code is where i am at now! Thanx a lot! #!/usr/bin/python from __future__ import unicode_literals import os, sys, django, json, time, datetime, socket, _thread, multiprocessing, queue import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import django.db BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) #here store is root folder(means parent). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "EraIoT.settings") django.setup() from vac300s.models import vac300, vac300Stat from vac200sV1.models import vac200V1 from shared.utils import * mqtt.Client.connected_flag = False clear = lambda: os.system('clear') messagesReceivedQ = queue.Queue() messagesQueuedQ = queue.Queue() activeThreadQ = queue.Queue() processingTimeQ = queue.Queue() processingTimeMysqlQ = queue.Queue() processingTimeMemcachedQ = queue.Queue() processedRequestQ = queue.Queue() topics = ["data/vac300s/#", "message/vac300s/#", "alarm/vac300s/#"] q = queue.Queue() def on_disconnect(mqttc, userdata, rc): print("*****************************************") print("Disconnected from MQTT server:") print(str(rc)) print("*****************************************") mqttc.connected_flag = False def on_connect(mqttc, obj, flags, … -
Populate/filter one <select> with another <select>
I have a form to create projects in my app. In this form the user must select a client in a and then a farm in another . How do I when selecting a client, the next only offers options from farms that are from the selected customer? I believe it's impossible to do this with just Django, am I right? simplified models.py class Project(models.Model): farm = models.ManyToManyField(Farm, related_name='farm_name',verbose_name='Propriedade beneficiada') client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='project_client',default=None,null=True, verbose_name='Cliente') class Farm(models.Model): client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='client', null=True, default=None) name = models.CharField(max_length=100, verbose_name='Nome') forms.py class NewProjectForm(ModelForm): class Meta: model = Project fields = ['owner','farm','warranty','modal','harvest_year','culture','value','final_date'] def __init__(self, *args,**kwargs): super(NewProjectForm, self).__init__(*args,**kwargs) self.fields['value'].required = False self.fields['final_date'].required = False self.fields['owner'].queryset = Owner.objects.all().order_by('name') farm_query = Farm.objects.all().order_by('name') self.fields['farm'].queryset = farm_query self.fields['warranty'].queryset = farm_query self.fields['final_date'].widget.attrs['data-mask'] = "00/00/0000" for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' -
H14 Error regarding favicon when deploying Django app to Heroku
Attempting to deploy my Django web application to Heroku. This is the first time I have ever deployed the app on Heroku however the app works as expected when running at localhost:8000. I have followed the documentation and can confirm the presense of 'Procfile' in the root directory of the app. The contents of Procfile are as follows: web: gunicorn my_app.wsgi This is consistent with the name of the app as referened everywhere in the project directory/folders. The 'requirements.txt' file is also present, with the necessary dependencies stated within it. When I deploy the app I get a success message as illustrated below. Yet, when I navigate in the browser to the url I see this... If I then consult the logs using the commmand heroku logs --tail --app myapp I see the following at=error code=H14 desc="No web processes running" method=GET path="/" host=myapp.herokuapp.com request_id=[REDACTED] fwd="51.9.111.101" dyno= connect= service= status=503 bytes= protocol=https 2022-03-19T19:07:35.123190+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=[REDACTED] fwd="51.9.111.101" dyno= connect= service= status=503 bytes= protocol=https Further investigaton leads me to believe that that there are currently no dynos assigned to the app, so I then attempt to spin up some resources using the following command … -
Real time chat application with Django Channels
My real time chat application refuses to send message. no errors at all. I have tried tracing the errors by logging to the console at every stage passed and also tried printing to the terminal. I think the problem might be from consumers.py here is my consummers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_name, self.channel_name, ) await self.accept() async def disconnect(self): print('\nOguh... disconnecting\n') await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def recieve(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] print('\nOguh... recieving a message\n') await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username, 'room': room } ) async def chat_message(self, event): print('\nOguh... Chat message\n') message = event['message'] username = event['username'] room = event['room'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'room': room, })) Here is my room.html: {% extends 'core/base.html' %} {% block tittle %} {{ room.name }} | {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-3xl lg:text-6xl text-white">{{ room.name }}</h1> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id='chat-messages'> <div class="p-4 bg-gray-200 rounded-xl"> <p class='front-semibold'>Username</p> <p> A sample … -
django image form does not save image
hey i got a issue with saving image. when i use the admin side it works well, but when i add a employee with frontend form it save evrything exept the image. <form id="form" method="POST" action="{% url 'addForm' %}" enctype="multipart/form-data" > {% csrf_token %} {{form | crispy}} <input type="submit" name="submit" value="submit" > </form> def index(request): employe = Employe.objects.all() form = EmployeForm teamFilter = Employe_Filter(request.GET, queryset=employe) employe = teamFilter.qs count = employe.count() context = { 'employe': employe, 'form': form, 'teamFilter': teamFilter, 'count': count } return render(request, 'managements/index.html', context) class EmployeForm(forms.ModelForm): class Meta: model = Employe fields = '__all__' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
Why 'pip' stopped working even though it was working fine before?
I am a bit new to programming and have been learning for a few weeks now. I am following Corey Schafer basic python videos and in the middle of his Django Series. To run the server, I run a virtual env. In cmd (in the project directory) I type: 1-pip shell 2-python manage.py runserver The server runs and I work on the project. Not Today. When I wrote pip shell, it gave me an error that: 'pip' is not recognized as an internal or external command, operable program or batch file. enter image description here I reinstalled Python after uninstalling it. pip is installed on my system. I added a new variable from the python folder (scripts) in my system. I did not work and it's still showing me the same error. -
Django Streaming
I just started with django and I want to make a spotify clone. I want to make it so then when you click on an album it shows the songs for that album. this is my models.py from django.db import models class album(models.Model): title = models.CharField(max_length=50) artist = models.IntegerField() genre = models.CharField(max_length=20) id = models.AutoField(primary_key=True) artwork = models.CharField(max_length=1000) class artist(models.Model): name = models.CharField(max_length=50) id = models.AutoField(primary_key=True) class song(models.Model): name = models.CharField(max_length=60) artist = models.IntegerField() album = models.IntegerField() id = models.AutoField(primary_key=True) This is my views.py from django.shortcuts import render from .models import album, song def home(request): context = { 'albums': album.objects.all(), } return render(request, 'main/index.html', context) Thank You