Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting ValueError at /car/offer/4/ Cannot assign "4": "CarRent.car" must be a "Car" instance. when trying to save Car instance to form
I am working on a car rental website for uber drivers in django, from the detailView I need drivers to be able to choose the duration of their rental, and other information will be auto filled to the form from my views.py, i was able to get the driver through request.user, i also need the PK of the car to be rented. searching through here i’ve tried various suggestions by people here, but i keep getting one error after another… using self.kwargs['pk'] results in ValueError at /car/offer/4/ Cannot assign "4": "CarRent.car" must be a "Car" instance. then i tried using form.car = Car.objects.get(pk= self.kwargs.get('pk')) which results in a AttributeError at /car/offer/4/ 'CarRent' object has no attribute 'is_valid' can someone please tell me how to get the car instance saved in the CarRent model? any help will be greatly appreciated. Thanks below is my code (reduced to the relevant bit) models.py class Car(models.Model): car_owner = models.ForeignKey(User, related_name='car_owner', on_delete=models.CASCADE) class CarRent(models.Model): car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE) driver = models.ForeignKey(User, related_name='driver_renting', on_delete=models.CASCADE) rented_weeks = models.BigIntegerField(default=1, choices=WEEK_CHOICES) forms.py class RentForm(forms.ModelForm): class Meta: model = CarRent fields = ['rented_weeks'] i’m only displaying the rented weeks as that’s the only information i need from the user. … -
Django query content_type by name not content_type_id
I need to count some relations from my Flags model to my Post Model. Now I don't understand how to query for the Post model name at my query, I understand how to query for the content_type_id but not for the content_type (as a string). I got something like this on my mind: Q(models.Q(('app_label', 'App'), ('model', 'Post')) but I don't know how the Syntax has to look like at that point, can smb. help? example: def post_list_most_bad_flags(request): p_counter_query = Flags.objects.filter(content_type_id=12) # --> Want to replace this with content_type instead if content_type_id counter = p_counter_query.count() print(counter) Thanks in advance -
Django Channels ASGI - AppRegistryNotReady: Apps aren't loaded yet
Running my project with python manage.py runserver boots it up perfectly using the channels asgi development server, however when running the project with Daphne (daphne project.routing:application) I get the error AppRegistryNotReady: Apps aren't loaded yet. settings.py INSTALLED_APPS = [ 'channels', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', # ... # ... installed apps and custom apps ] WSGI_APPLICATION = 'project.wsgi.application' ASGI_APPLICATION = 'project.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [REDIS_URL], } }, } routing.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.conf.urls import url from my_app.consumers import MyCustomConsumer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter([ url(r'^ws/custom/$', MyCustomConsumer), ]) ), }) I have tried adding django.setup() as described in other questions, as well as running with uvicorn instead of daphne but still getting the same error. I've also tried pointing to the websocket routing in settings.CHANNEL_LAYERS['ROUTING'] and moving the application initialization out to an asgi.py file but no luck there either. I can't tell what I'm doing differently from the channels documentation, any help appreciated. -
Ajax, Django: status 200 but nothing happens
I am trying to post comment with ajax, but it is not working. When I press button console is not printing any error, comment is not being posted. In command line I see: "POST / HTTP/1.1" 200 5572 When I change button to "submit" it is posting and responding with proper JSON like: {"comment": {"id": 16, "author": 1, "content": "test", "post": 12}} My code is below, any help is appreciated: views.py def homepage(request): profiles = Follow.objects.filter(follow_by=request.user.profile).values_list('follow_to', flat=True) posts = Post.objects.filter(author_id__in=profiles).order_by('-date_of_create') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): pk = request.POST.get('pk') post = Post.objects.get(pk=pk) new_comment = Comment.objects.create( author = request.user.profile, post = post, content = form.cleaned_data['content'] ) return JsonResponse({'comment': model_to_dict(new_comment)}, status=200) form = CommentForm() context = { 'posts': posts, 'form': form } return render(request, 'posts/homepage.html', context=context) template <div class="comments" id="{{ post.pk }}" style="display: none"> {% include 'posts/comments.html' %} <form action="" method="post" class="commentForm" data-url="{% url 'post_comments' post.pk %}"> {% csrf_token %} <input type="hidden" name="pk" value="{{ post.pk }}"> {{ form.as_p }} <button type="button" class="commentBtn" id="{{ post.pk }}">Comment</button> </form> addComment.js $(document).ready(function () { $('.commentBtn').click(function () { let serializedData = $('.commentForm').serialize(); let btn = $(this); let id = btn.attr('id'); console.log(btn); $.ajax({ url: $("commentForm").data('url'), data: serializedData, type: 'post', dataType: 'json', success: function (data) { … -
Django views and requests
How can I catch and process arbitrary request in Django view? For example: def index(request): template_name = 'index.html' users = User.objects.all() return render(request, template_name, {'users': users}) The request parameter here is responsible only for loading the index page, am I right? But how do I process an arbitrary request from front-end, for example, my view has got the data from the database. I need to transfer it to front-end part of my app. How can I do it? Without using context. The request from JS: fetch('index.html', { method: 'GET', }).then(response => response.json()).then(data => console.log(data)) SOMEONE HELP ME I'M TIRED OF SEARCHING THE ANSWER! -
django login form and form validation with ajax in bootstrap modal
i'm new to ajax and i want the user to be able to login with this login form and if the password is incorrect it tells him that signin is invalid without the page being refreshed,the form is contained in a bootstrap modal after checking some answers and some tutorials here is what i tried: i have a normal login form in my forms.py in my views.py signin_form = SigninForm() user = request.user if request.method == "POST": if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) data['email'] = email data['password'] = password data['stat'] = "ok" return JsonResponse(data) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') else: data['stat'] = "error" the form in the template <form action="" method="POST" id="form-signin"> {% csrf_token %} {{signin_form.email}} {{signin_form.password}} <button class="btn btn-success" id="signin-btn" type="submit" name="signin_form">Sign in</button> {% for message in messages %} <div class="alert alert-danger "> {{ message }}</div> {% endfor %} </form> in my js file $(function () { $("#signin-btn").click(function () { $.ajax({ type: 'POST', data: $("#form-signin").serialize(), success: function (data, status) { if (data['stat'] == "ok") { $('#joinus').modal('hide'); } else { $('#joinus').html(data); $('#joinus').modal('show'); } } }); with all this … -
Filtering combobox according to a project list create by logged user in django
I'm new to django and have a lot to learn. I am developing a system in which the logged in user registers his requirement, but each requirement is linked to a project that the same user created. As it is a multi-tenant system, so several users will use the system and each one registers its own project and requirement. I'm having the following message AttributeError at /requisitos/cadastrarRequisito/ 'WSGIRequest' object has no attribute 'projeto' My model (in portuguese) class Requisito (models.Model): nomeRequisito = models.CharField(max_length=30, verbose_name=('Nome do Requisito')) responsavel = models.CharField(max_length=30, verbose_name=('Responsável pelo Desenvolvimento')) código = models.CharField(max_length=20, verbose_name=('Código do Requisito')) projeto = models.ForeignKey(Projeto, on_delete=models.PROTECT) prioridade = models.CharField(max_length=10, verbose_name=('Prioridade do Requisito')) risco = models.CharField(max_length=10, verbose_name=('Risco do Requisito')) motivo = models.CharField(max_length=20, verbose_name=('Motivo do Requisito')) status = models.CharField(max_length=20, verbose_name=('Status do Requisito')) requisitosImpactados = models.CharField(max_length=100, verbose_name=('Requisitos Impactados')) user = models.ForeignKey(User, on_delete=models.CASCADE) estoriaUsuario = HTMLField() regrasNegocio = HTMLField() def __str__(self): return self.nomeRequisito Forms.py class CadastrarRequisitos(ModelForm): def __init__(self, projeto, *args, **kwargs): super(CadastrarRequisitos, self).__init__(*args, **kwargs) self.fields['projeto'].queryset = Projeto.objects.filter( projeto=Projeto.nomeProjeto) class Meta: model = Requisito fields = ['nomeRequisito', 'responsavel', 'código', 'projeto', 'prioridade', 'status', 'risco', 'motivo', 'requisitosImpactados', 'user', 'estoriaUsuario', 'regrasNegocio'] view @method_decorator(login_required, name='dispatch') class RequisitoCreate(CreateView): model = Requisito form_class = CadastrarRequisitos def get_form_kwargs(self): kwargs = super(RequisitoCreate, self).get_form_kwargs() kwargs.update({'projeto': self.request.projeto}) return kwargs … -
django.db.utils.OperationalError: disk I/O error
i made crawling and saving the info to django.db function with multiprocessing. it works fine at first but gives error later. when i launch stockPriceUpdate() on my desktop, it doesn't occur any errors. but when i launch on my laptop, it works fine at first but laters, it's speed slows down and gives error like below. Stock is my django model mycode def stockPriceCrawling(stockTitle): url = 'http://asp1.krx.co.kr/servlet/krx.asp.XMLSiseEng?code=' + str(stockTitle) html = requests.get(url).content soup = BeautifulSoup(html, 'html.parser') stockinfo = soup.select('TBL_StockInfo')[0] price = stockinfo['curjuka'].replace(',','') highestPrice = stockinfo['highjuka'].replace(',','') lowestPrice = stockinfo['lowjuka'].replace(',','') tradeVolume = stockinfo['volume'].replace(',','') tradeValue = stockinfo['money'].replace(',','') print("info : ",' ', price," ",highestPrice," ",lowestPrice," ",tradeVolume," ",tradeValue) db.connections.close_all() stock= Stock.objects.get(code=stockTitle) stock.price = price stock.highestPrice = highestPrice stock.lowestPrice = lowestPrice stock.tradeVolume = tradeVolume stock.tradeValue = tradeValue stock.save() def stockPriceUpdate(process=32): # start = time.time() stocks = Stock.objects.all() stockTitles=[] for stock in stocks: stockTitles.append(str(stock.code)) pool = Pool(32) r=pool.map(stockPriceCrawling, stockTitles) pool.close() pool.join() error Traceback (most recent call last): File "/mnt/c/Users/DAUN/Desktop/swpp/swpp/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/mnt/c/Users/DAUN/Desktop/swpp/swpp/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: disk I/O error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 121, in worker result = (True, func(*args, **kwds)) … -
OperationalError: could not translate host name "db" to address: Unknown host
I have a problem with connecting Django with PostgreSQL installed in docker, when run Django using python manage.py runserver settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'trytofindme', 'HOST': 'db', 'PORT': '5432', } } Dockerfile: # pull official base image FROM python:3.6.4-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install wkhtmltopdf dependencies RUN wget https://s3.amazonaws.com/shopify-managemant-app/wkhtmltopdf-0.9.9-static-amd64.tar.bz2 RUN tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2 RUN mv wkhtmltopdf-amd64 /usr/local/bin/wkhtmltopdf RUN chmod +x /usr/local/bin/wkhtmltopdf # install python dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app/requirements.txt RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r requirements.txt --no-cache-dir && \ apk --purge del .build-deps # copy project COPY . /usr/src/app/ docker-compose: version: '3.7' services: db: image: postgres:13.0 restart: always environment: POSTGRES_PASSWORD: trytofindme ports: - 15432:5432 adminer: image: adminer restart: always ports: - 8020:8080 I can't find mistake in my code. Are there any variant to connect PostgreSQL and Django, not loosing the protection? I used: docker-compose … -
Automatic generate data in table when migrate in Django
Is there any way how can I add automatically data in tables when using command migrations in Django? Let say I have usertype_tbl every time I use command makemigrations in Django it should store automatically this data - Admin, Super admin, other_user etc. in usertype_tbl. Is there any way how to implement this? thanks for the help in advance! models.py class usertypes_tbl(models.Model): user_type = models.CharField(max_length=264) description = models.CharField(max_length=264) status = models.CharField(max_length=264) //add some data = Admin, Super_admin , etc. -
How to Create a storage folder using User name and id in django restfull api
I have a video file that is uploaded by a user, I want to create a separate folder in the media/Smat/name/id directory by using the name and id of the uploaded file. model.py from django.db import models from datetime import datetime import cv2 import tempfile # from .utils import get_uploaded_video from django.utils import timezone import os def upload_to(instance, filename): now = timezone.now() base, extension = os.path.splitext(filename.lower()) return f"Smat/{now:%Y-%m-%d}" class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to, null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) seriliazer.py from rest_framework import serializers from .models import MyVideo from django.contrib.auth.models import User class MyVideoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyVideo fields = fields = ['id', 'url', 'name', 'date', 'videofile'] class UploadVideoSerializer(serializers.ModelSerializer): class Meta: model = MyVideo fields = ['videofile'] -
Django REST API nested values updated if exists
I have a Django project where I have a table for Projects, Customers and Contact Persons. Projects have a foreign key to both Customers and Contact Persons, and Contact Persons have a foregin key with Customers. I am using Django REST API to get the data from the server, and when I get a project instance, I would like to be able to see contact persons fields (at least some of them), and when I create/update a Project, I should be able to include a contact person. If the contact person does not exist, it should be created, if it does exist, it might be updated. I have been trying to use Djangos "update_or_create", however, if the contact person already exists, I get a response with "contact person with this name already exists." before I even get into my create function. Any idea why this is happening? Project View: class ProjectViewSet(ModelViewSet): queryset = Project.objects.all() serializer_class = ProjectSerializer example of ProjectSerializer class class ProjectSerializer(DynamicFieldsModelSerializer, ModelSerializer): contact_person = ContactPersonSerializer(required=False) class Meta: model = Project fields = '__all__' def to_representation(self, instance): if instance.customer: rep['customer'] = instance.customer.name return rep def create(self, validated_data): contact_person = validated_data.pop('contact_person') contact_person, created = ContactPerson.objects.update_or_create(name=contact_person['name'], defaults={'phone': contact_person['phone'], 'customer': Customer.objects.get(pk=contact_person['customer'].id)}) project … -
TypeError: __init__() got an unexpected keyword argument 'topic' POPULATING SCRIPT
So, I tried to populate my code my django website when i came across type error.i am really new to django webframe work and have no idea why i got this error. I followed a tutorial on udemy. ''' import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Game'] def add_topic(): t= Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] acc_rec =AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("Populating Script!") populate(5)`enter code here` print("populating Complete!") ''' -
How to use tuple in Django expression?
How can I use tuple in Django expressions? I want to be able to annotate QuerySet with some tuple, so that I can make ordering according to that annotation or filter things greater or smaller according to that annotation. I can order by multiple fields (without the need for annotation), but I can't easily filter something without implementing complex logic myself. It would be also nice if this could be used with existing code that uses "greater than" or "less than" filtering. (I could chain bunch of ORs handling things element by element, but I would be surprised if I'm the only one who needs something like this, I don't want to reinvent wheel.) I want standard SQL ordering, where left-most element has highest priority (for example SELECT (1,2) < (3,0) AS TEST returns TRUE). -
Browser blocks cross domain iframe cookies
I have a forum-like component which I use in an iframe on other websites. This component uses django-allauth for authentication with Facebook and Google. Everything worked fine but now the authentication stopped working some time ago. When I look at the cookies in my browser, the cookies from Facebook/Google which are set by the iframe, are not loaded. Although, the cookies from the component itself are set. The authentication still works when I load the iframe on a website which is on another subdomain of the component itself. Tool on another subdomain (working): https://shop-sandbox.adbuddy.be/discussie/ Tool on a totally different domain (not working): https://mama-calinka.webbuddy.be/discussie/ I guess this problem had something to do with CORS-headers but nothing I've tried helped. Can someone help me with this problem please? -
Paused on exception TypeError: document.getElementById(...) is null
Well Here I am creating commenting system. It works fine if there is at least one comment already but if there is no comment and try to create one than it shows me an error Paused on exception TypeError: document.getElementById(...) is null . I don't know how can i fix it. html <div id="post_id" post-id="{{post.pk}}" post-slug="{{post.slug}}"> {% if node.level < 3 %} <button class='btn btn-success' onclick="myFunction({{node.id}})">Reply</button> {% endif %} </div> jquery,ajax funtion $(document).on('click', '#newcomment, #newcommentinner', function (e) { e.preventDefault(); var button = $(this).attr("value"); var post_id = document.getElementById('post_id').getAttribute('post-id'); #Here is an error appearing. var post_slug = document.getElementById('post_id').getAttribute('post-slug'); console.log(post_id,'postid') var placement = "commentform" if (button == "newcommentform") { var placement = "newcommentform" } $.ajax({ type: 'POST', url: '{% url "posts:addcomment" %}', data: $("#" + button).serialize() + "&post_id="+post_id + "&post_slug="+post_slug, cache: false, error: console.log('post_id' + post_id), success: function (json) { console.log(json) $('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \ <div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \ <div>' + json['result2'] + '</div> \ <hr> \ </div>').insertBefore('#' + placement); $('.commentform').trigger("reset"); formExit() }, error: function (xhr, errmsg, err) { } }); }) if more code is require than tell me in comment session. i will update my question with that information. -
Django + AWS s3 can upload files but not access them
Following this tutorial I set up our system to use Amazons S3 file storage using boto3 and Django-storages. I ran the collectstatic command and it worked just fine, the files show up in the AWS Management Console. But when running the server locally (runserver) all static files are missing. Looking at the console there are the error messages GET https://BUCKET.s3.eu-central-1.amazonaws.com/static/admin/css/nav_sidebar.css net::ERR_ABORTED 403 (Forbidden) for each of the files. The url looks right to me, the upload worked fine, but apparently the access doesn't work. Does this have something to do with my config in AWS? Or is this a django settings issue? -
Django - Certain Py Module doesn't work in IIS
This is my first time putting a question here. Some background, I started coding on Django this year and Python more than a year but less than 2 years so I don't much. This problem is a concern to my what I developing in at work. And my team working on it is novice or no experience on coding Python or Django or both. The Problem We have a web app based on Django 3.0.2 and use MSSQL for the db. Our company policy is to use Windows server and IIS as the prod and test server. We done a lot of work on it and all work well except for some python library and Django module that don't work, mainly Xlwings and Django-post-office. For XLwings, it doesn't run the code and Excel(we have valid license and latest Excel programme on the server). code below; filepath = BASE_DIR + '\\media\\Template.xlsm' temp_path = BASE_DIR + '\\media\\' + '{}.{}'.format(uuid4().hex, 'xlsm') shutil.copyfile(filepath, temp_path) pythoncom.CoInitialize() app1 = xw.App(visible=True) wt = xw.Book(temp_path) sht = wt.sheets['Cover'] sht.range('E5').value = request.POST.get('year') sht.range('E6').value = request.POST.get('company') sht.range('E7').value = companydata.employer_no sht.range('E8').value = email wt.save(temp_path) app1.quit() As for Django-post-office, we have module using it working but other modules using it doesn't work. … -
Django - What field or fields in model should I be indexing to speed up the following query?
What field or fields in model should I be indexing to speed up the following query? Query Subscriber.objects.filter(audience=audiencepk).order_by('-create_date') Models: class Subscriber(models.Model): first_name = models.CharField(max_length=15, blank=True) last_name = models.CharField(max_length=15, blank=True) audience = models.ForeignKey(Audience, on_delete=models.CASCADE) create_date = models.DateTimeField(auto_now_add=True) class Audience(models.Model): audience_name = models.CharField(max_length=50) create_date = models.DateTimeField() store = models.ForeignKey(Place, on_delete=models.CASCADE) -
django template rendering fail?
Variables are not rendered correctly by django my views dynasty_li=['a','b','c','d'd] html {% for d in dynasty_li %} {% if d == dynasty %} <a href="{% url 'poet_list' '{{ d }}' %}" class="active">{{ d }}</a> {% else %} <a href="{% url 'poet_list' '{{ d }}' %}">{{ d }}</a> {% endif %} {% endfor %} actual <a href="category/{d}">a</a> <a href="category/{b}">b</a> <a href="category/{c}" class="active">c</a> <a href="category/{d}">d</a> -
Where are my environment variables in Elastic Beanstalk for AL2?
I'm using elastic beanstalk to deploy a Django app. I'd like to SSH on the EC2 instance to execute some shell commands but the environment variables don't seem to be there. I specified them via the AWS GUI (configuration -> environment properties) and they seem to work during the boot up of my app. I tried activating and deactivating the virtual env via: source /var/app/venv/*/bin/activate Is there some environment (or script I can run) to access an environment with all the properties set? Otherwise, I'm hardly able to run any command like python3 manage.py ... since there is no settings module configured (I know how to specify it manually but my app needs around 7 variables to work). -
Image is not showing in Django on Heroku server
The images I'm uploading in the model are showing in the localhost but not working on the Heroku server. I'm already using the white noise, and staticfiles(CSS, js, and images) which is stored in static folder are working fine in both places (locally and on the server) the only problem is happening with images I uploaded in the model. Heroku logs "GET /media/product_image/pixel4a_8dq6jPP.jpeg HTTP/1.1" 404 771 "https://mobile-care.herokuapp.com/explore/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" models.py image = models.FileField(upload_to='product_image', urls.py urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML file {% for item in products %} <img src="{{item.image.url}}"> {% endfor %} I repeat I'm already using whitenoise and already initialized the MEDIA_ROOT and MEDIA_URL in settings.py. -
ModelNotFoundError in Django
For some reason, VS code doesn't recognize some standard external Django modules. I keep getting the ModelNotFoundError. When I try to run pip or pip3 install on for example django.contrib I'm getting the following error: ERROR: No matching distribution found for django.contrib I'm using VS Code on Windows 10. Would be awesome if someone could help me fix this problem. -
How to add a file upload progress bar with percentages in django and jquery
I want to create a file upload progress bar to my form, but am getting an error inside my console saying "jquery.min.js:4 POST http://localhost:8000/music/create/ 403 (Forbidden)" below is my code #Model class Song(models.Model): genre = models.ManyToManyField(Genre) #FORMS class SongCreateForm(forms.ModelForm): class Meta: model = Song fields = ['audio',] #VIEWS def songcreate(request): artist = Artist.objects.get(user=request.user) form = SongCreateForm() if request.method == "POST": form = SongCreateForm(request.POST or None, request.FILES) form.instance.artist = artist if form.is_valid(): form.save() return render(request, 'music/song_form.html', {'form':form}) #URLS path('music/create/', songcreate, name="song_create"), #TEMPLATE AND JQUERY <form action="/" method="post" enctype="multipart/form-data"> <legend><h3>Update</h3></legend> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn-block razo-btn" placeholder="upload"> </form> <script> $(document).on('submit', function(event){ event.preventDefault(); var formData = new FormData($('form')[0]); var csrf = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ xhr : function(){ var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e){ if (e.lengthComputable) { console.log('Bytes loaded: ' + e.loaded); console.log('Total ' + e.total); console.log('Percetage uploaded ' + (e.loaded / e.total)); } }); return xhr; }, type : 'POST', url: '', data : { formData, csrfmiddlewaretoken:csrf }, processData : false, contentType : false, success : function() { alert('File uploaded'); } }); }); </script> -
Form automatically downloading data from the user's profile
I would like to create a function that will automatically retrieve data from a user's profile by clicking the save button. I want to create a platform on which a user can sign up for a tournament and I would like to do this in the purest and most intuitive way