Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSONDecodeError while working with websockets
I'm learning to work with WebSockets. I'm using Django as server-side and react at the client-side. I'm able to connect and send an object to the backend but unable to receive massage on the frontend side. I'm sharing my code. Please me my flaws and a perfect way to do the basic setup of sockets on the frontend and backend. Thank You. django-python import json from channels.generic.websocket import WebsocketConsumer class ProjectConsumer(WebsocketConsumer): def connect(self): print("HEY HEY HEY HEY") self.accept() def disconnect(self, close_code): pass def receive(self, text_data): print("Reciasha",text_data) text_data_json = json.loads(text_data) # message = text_data_json['message'] message =text_data print("Hey",message) self.send(text_data=json.dumps({ 'message': message })) React-js export const WebSocketTest = () => { var ws = new WebSocket("ws://localhost:8000/ws/projects/"); ws.onopen = function() { // Web Socket is connected, send data using send() const msg = { "firstName": "Jane", "lastName": "Doe", } ws.send(msg); alert("Message is sent..."); }; ws.onmessage = function (evt) { const data = JSON.parse(evt.data); // var received_msg = evt.data; console.log(evt) console.log("data",data) console.log("received_msg",data["message"]) alert("Message is received..."); }; ws.onclose = function() { // websocket is closed. alert("Connection is closed..."); }; } Right now I'm facing the below error: WebSocket HANDSHAKING /ws/projects/ [127.0.0.1:43012] HEY HEY HEY HEY WebSocket CONNECT /ws/projects/ [127.0.0.1:43012] HTTP GET /api/project-viewset/ 200 [0.11, 127.0.0.1:43008] Reciasha … -
Cannot insert an entity along with it's foreign key in django/djangorestframework
I have the following models in my application: class User(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField() address = models.CharField(max_length=200) class Device(models.Model): description = models.CharField(max_length=200) location = models.CharField(max_length=200) max_energy_consumption = models.FloatField() avg_energy_consuumption = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) A user can have multiple devices, hence the foreign key user in the Device class. These are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class DeviceSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Device fields = '__all__' I am using a default ModelViewSet for CRUD operations: class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class DeviceViewSet(ModelViewSet): queryset = Device.objects.all() serializer_class = DeviceSerializer In my database, the devices table has a user_id column, like it should. When I open the Django API in the browser, I see this: In the POST form, there is no field for user_id. Shouldn't it be one? How am I supposed to add a device through a request and specify which user it belonges to? Like this it just puts null in the user field, which is not what I want. I want to specify to a device which user it belonges to at creation. -
Include React app inside MPA Django Website
How do you integrate a React application into Django MPA website? The website has multiple pages. One of the pages is where changes intensive react app should be placed in. The rest pages use vanilla js. React app and rest pages would share same database, but the functionality of the react app is mostly seperate from the rest webpage. It is like if you had a game/player/some tool inside a website that you can load. My most fears is about js and react conflicts. -
How do I use a postgresql function result in a Django template?
I'm quite new to Django so I suspect I'm missing something simple. I've used Django to build a website that features "regular" pages as well as a data-entry, display, update and delete pages in a back-end section of the website that requires a login to access. All of that was easy. I've also used Django's template inclusion feature and, for what I've needed so far, it seems to work fine. I now have a requirement to use a postgresql function to dynamically generate a central portion of a webpage and include that in the template. Basically, if a page is called "abc" then I need to do something like textfield = myfunction('abc') where myfunction would generate the equivalent of a static template stored in a folder. I understand (I think) that the template inclusion content can be contained in a variable. What I'm missing is how to get the results of the postgresql function into that variable in the template. I'm assuming that I need to put this logic in the model but I haven't been able figure out how to do that. Any help or advice would be greatly appreciated. Thanks! -
Heroku Server Keeps Crashing
I deployed a Django website on Heroku and sometimes I get lots of H10 (App crashed) messages in the log. Sometimes it ends up in some sort of a crash loop and I have to go in and restart the dyno manually. I'm running hobby dyno and that doesn't allow me to scale up or add redundancy options, but I want to find out what is causing the app to crash. The app deploys fine and starts as it should, the problem occurs in runtime when its serving client requests. In the Heroku log I only see very basic info, very similar to this example from Heroku support: "heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=myapp.herokuapp.com fwd=17.17.17.17 dyno= connect= service= status=503 bytes=" It would useful to understand where the app crashed so that I can find and solve the root cause. (or could the problem be lack of resources at Heroku?) Thank you in advance! -
targeting id on a loop to toggleClass with Jquery
I'm trying to make it so when a user presses a button, an element inside the button changes class. I managed to do that when I have a clear id for button. <button id="buttonId"><i class="class1"></i></button> <script> $(document).ready(function(){ $("#buttonId").click(function(){ $(this).find('i').toggleClass('class2').toggleClass('class1'); }); }); </script> Now I need to create a sequence of buttons, and for that I've set the id like this: {% for i in X %} <button id="{{i.id}}"><i class="class1"></i></button> {% endfor %} However I don't know how I can reference i.id inside the function. The example below didn't work. $(document).ready(function(){ $("{{i.id}}").click(function(){ $(this).find('i').toggleClass('class2').toggleClass('class1'); }); }); How do I find the id? -
no such column: Homepage_goods.number_text
I have a problem of displayed a model text in index.html This is code of views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def description(self): return self.description_text def price(self): return self.price_text def number(self): return self.number_text This is code of html(index.html) {% for good in goods %} <h3 class="numbers">{{good.number_text}}</h3> {% endfor %} -
Django js JQuery Basket_adding
Ребят, помогите пожалуйста, я новичок в Django, JS. В общем, создаю корзину. Добавил JQuery, отображение нормальное было (добавлялось). Потом уже создавал бек: создал модель ProductInBasket, во views.py сделал функцию. Но, теперь, когда нажимаю на кнопку "В корзину" мне показывает вот это: enter image description here То есть, после каждого обновления страницы, добавляется +1. Вот... Сайт, в общем, не выводит. Не знаю, в чём проблема, такой вот странный затык... Помогите, пожалуйста) Вот код: JS: $(document).ready(function() { var form = $('#form-buying-product'); console.log(form); form.on('submit', function(e){ e.preventDefault(); console.log('123'); var nmb = $('#number').val(); console.log(nmb); var submit_btn = $('#submit_btn') var product_id = submit_btn.data("product_id") var product_name = submit_btn.data("name") var product_price = submit_btn.data("price") console.log(product_id); console.log(product_name); console.log(product_price); var data = {}; data.product_id = product_id; data.nmb = nmb; var csrf_token = $('#form-buying-product [name="csrfmiddlewaretoken"]').val(); data["csrfmiddlewaretoken"] = csrf_token; var url = form.attr("action"); console.log(data); $.ajax({ url: url, type: 'POST', data: data, cache: true, success: function (data) { console.log("OK"); error: function(){ console.log("error") } }) $('.basket-items ul').append('<li>'+product_name+', ' + nmb + 'шт. ' + 'по ' + product_price + 'грн ' + '<button style="background-color: #ff0000; color: white; z-index: 99999 !important;" type="button" class="delete-item btn close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>' +'</li>'); }); function showingBasket() { $('.basket-items').removeClass('hidden'); } $('.basket-container').on('click, hover', function(e){ e.preventDefault(); showingBasket; }) $('.basket-container').mouseover(function(){ showingBasket(); }) $('.basket-container').mouseout(function(){ showingBasket(); … -
Django not loading staticfiles but sucessfull collectstatic
i got a problem, i need to switch from develop to productive, i do sucessfully collectstatic and switch debug to False, but when i run my server, on local, docker run or in google microservices the static folder wont load any files so i got only plain html, unless y use --insecure command. this are my relevant settings.py lines: DEBUG = True ALLOWED_HOSTS = ['*'] TATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'estandar_diseno/static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'production_static') DATA_UPLOAD_MAX_MEMORY_SIZE = 5242880 GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'credencial.json')) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_PROJECT_ID = 'green-carrier-xxxxx' GS_BUCKET_NAME = 'inversiones-admision' UPLOAD_ROOT = 'reportes/' MEDIA_ROOT = 'reportes' MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) if not DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) Folder structure: So its supose that bucket with mediafiles only hold upload files, from users, and have all the static files on the docker container and then upload to google microservices, but the problem i got is even on local as i said doesnt work, im missing something? collectstatic just work well, i get copied all the files. -
Django index value of array
I am sending an array of arrays a post request through $ajax ie: [[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]] My ajax: $.ajax({ type: 'POST', url: '', dataType: 'json', data:{ csrfmiddlewaretoken: csrftoken, targets:JSON.stringify(targets), // notes:notes, // time:time, // rating:rating }, success: (res)=>{ console.log(res) }, error: (error)=>{ console.log(error) } }) In django, when I print(request.POST), I get 'targets[0][]':[1, "25, 25, 25", "pounds", "exercise note 1"], 'target[1][0]':[2, "", "No Weight", "note 2"]. I have tried JSON.stringify([[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]]) and I get back 'targets': ['[[2,"25, 25, 25","Pounds","note 1"],[1,"","NoWeights","note 2"]]'], I've also tried: ts.push(t) django returns: 'targets[]': ['[2,"25, 25, 25","Pounds","note 1"]', '[1,"","NoWeights","note 2"] which is what I want. But when I do targets = request.POST.getlist('targets[]) for target in targets: print(target[2]) -->I want either "25, 25, 25" or , "" But all I get is , and when I print(len(target)) the first array returns 34. Why? How do I get the strings? What am I doing wrong? I want to assigned each index in the target array to a varible so I can save to the database -
Django cannot connect to running postgres docker container
I am surprised that I cannot get this to work, as I have run a django applications with a postgres DB in docker containers multiple times, however, this time on my Linux machine the django application cannot connect to the postgres docker container, whereas on my Mac the setup works without a problem. I am getting the standard error: django.db.utils.OperationalError: could not connect to server: Host is unreachable Is the server running on host "postgresdb" (172.27.0.2) and accepting TCP/IP connections on port 5432? The postgres container is running and should be reachable. I check the IP address of the docker container and it seems correct. My docker-compose file looks like this: version: "3.8" services: app: container_name: data-management restart: always build: ./ ports: - '3000:3000' links: - 'postgresdb' volumes: - ./:/usr/local/share/src/app env_file: - .dev.env postgresdb: container_name: be-postgres restart: always image: postgres:13.4-alpine ports: - '5432:5432' volumes: - postgres-db:/var/lib/postgresql/data env_file: - .dev.env volumes: postgres-db: The configurations are stored in an environment file, which is used in both containers to avoid any mismatches. POSTGRES_PASSWORD=devpassword123 POSTGRES_USER=devuser POSTGRES_SERVICE=postgresdb POSTGRES_PORT=5432 POSTGRES_DB=data_management The django DB settings are as standard as they could be: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ['POSTGRES_SERVICE'], 'NAME': os.environ['POSTGRES_DB'], 'PORT': os.environ['POSTGRES_PORT'], 'USER': os.environ['POSTGRES_USER'], … -
Django: print latest download date and how many new entry since last download
In my app I've created a working function to dowload all the user information in my database. In my html page I'd like also to add the date of the latest time that the csv file was downloaded and how many new profile where added since the last download. I've thought to use the iformation stored in the name file to do so but I'm getting this error name 'file_name' is not defined account.views @login_required def download_csv(request): response = HttpResponse(content_type='text/csv') profile_total = Information.objects.all().count() profile_csv_date_donwload = str(datetime.today().strftime("%d-%m-%Y")) file_naname = + profile_csv_date_donwload + str(profile_total) +'.csv' response['Content-Disposition'] = 'attachment; filename=' + file_naname writer = csv.writer(response, delimiter=';') info = Information.objects.all() writer.writerow(['first_name', 'last_name', 'gender', 'birthdate']) for i in info: writer.writerow([i.first_name, i.last_name, i.gender, i.birthdate]) return response donwload.views from account.views import download_csv def download_page(request): profile_total = Information.objects.all().count() latest_d_csv = file_name[0:10] latest_n_csv = file_name[11:] new_profile = profile_total - int(latest_n_csv) context = { 'profile_total': profile_total, 'latest_d_csv': latest_d_csv 'latest_n_csv': latest_n_csv 'new_profile': new_profile } return render(request, 'page/download.html', context) html <div class="col-md-8"> <div class="row gutters-sm"> <div class="col-sm-6 mb-3"> <div class="card h-100"> <div class="card-body"> <h6 class="d-flex align-items-center mb-3">Profile CSV</h6> <br/> <small>Profile in Database: {{ profile_total }}</small> <br/> <small>Latest Download: {{ latest_d_csv}}</small> <br/> <small>New Profile: {{ new_profile }}</small> </div> </div> </div> -
How to solve Tkinter window ıs not responsing problem
I am using Tkinker for creating a progress bar in my Django project. Firstly I try to use Celery but I cannot do it so I looked for other alternatives and I found that. I implement Tkinker to my project and it works but after the window opens and the code is running but the window stops working. say not response. Like that: How can I work this? And this is my code: class myFunction(): def __init__(self, user, password, url, port, db_password, username): self.zaman = datetime.now().strftime("%Y-%m-%d") ... self.download_all(user, password, url, port, db_password) ... def download_all(self, user, password, url, port, db_password): # creating tkinter window root = Tk() # Progress bar widget progress = Progressbar(root, orient=HORIZONTAL, length=100, mode='determinate') root.title("Sending") root.attributes("-topmost", True) w = root.winfo_reqwidth() h = root.winfo_reqheight() ws = root.winfo_screenwidth() hs = root.winfo_screenheight() x = (ws / 2) - (w / 2) y = (hs / 2) - (h / 2) root.geometry('+%d+%d' % (x, y)) try: sys.path.append('../') ... bar = Bar('Processing', max=len(scans)) # try download and save scans into each folder the belong to pb_length = len(scans) print("------pb length-----------") print(pb_length) pb_value = 100/pb_length print("------pb val-----------") print(pb_value) for s in scans: progress['value'] = pb_value root.update_idletasks() bar.next() scanner.scan_name = s['name'] scanner.scan_id = s['id'] … -
'Canvas' object has no attribute '_committed'
I'm trying to save the canvas object to my django model field file but it says "'Canvas' object has no attribute '_committed'". p.setTitle(f"{patient.first_name} {patient.last_name}'s Report") p.showPage() p.save() pdf:bytes =buffer.getvalue() buffer.close() response.write(pdf) r = Result.objects.filter(score="12").update_or_create(file=p) Can anyone help me out with this issue? -
Adding Drop Down List to forms.ModelForm
When I was using the Crispy formatting, I was getting a dropdown list for the Room Type field . After designing my own bespoke form layout, I am struggling to get the dropdown list back. Could anyone point me in the right direction? class HotelSearchForm(forms.ModelForm): class Meta: model = RoomType fields = ['room_type', 'price'] widgets = {'price': forms.TextInput(attrs={'type':'range','class':'form-range slider', 'step': '5', 'min': '5', 'max': '500'}) ,'room_type': forms.TextInput(attrs={'class':'form-control form-control-lg select'})} Room_Type = ( ('Single','Single'), ('Double','Double'), ('Family','Family'), ('Dormitory','Dormitory'), ('F.Dormitory','Female Dormitory'), ) class RoomType(models.Model): room_type = models.CharField(max_length=60, null=False, choices=Room_Type) -
Django query optimizations
Is there a better way to do something like this with Django? Looking to get a dic where each key is a 'user_type' and the corresponding value is the count of records for that 'user_type'. For example: {1: 200, 2: 300} stuff_qs = Model.objects.all() user_type_count = stuff_qs.values( 'user_type' ).annotate(count=Count('id')).order_by() dic_counts = {d['user_type']: d['count'] for d in user_type_count} I don't really want to do anything with stuff_qs, as I need to get multiple different types of dic_counts from the same qs. -
How to filter products from the database when overriding queryset in django restframework
I'm stuck, not knowing how to go about this anymore. I want to filter products using a particular field called product_class. The programme below keeps returning all the products in the database rather than returning only those that have common rpduct_class. models.py class Product(models.Model): categories = models.ManyToManyField(Category) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="product_owner") name = models.CharField(max_length=150) image = models.ImageField(upload_to="images/products/") slug = models.SlugField(max_length=255, blank=True, null=True) brand = models.CharField(max_length=255, default="brand") product_class = models.CharField(max_length=50) createdAt = models.DateTimeField(auto_now_add=False) class Meta: ordering = ("-createdAt",) def __str__(self): return self.name serializers.py class product_serializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'categories', 'created_by', 'name', 'image','slug', 'brand','product_class') views.py class product_class_view(generics.ListAPIView): serializer_class = product_serializer permission_classes = (permissions.AllowAny, ) def get_queryset(self, *args, **kwargs): queryset = Product.objects.all() product_class = self.request.query_params.get('product_class') if product_class is not None: queryset = queryset.filter(Product__product_class=product_class) return queryset urls.py path('products/<product_class>', views.product_class_view.as_view(), name="product_class") Please I want to know how to make the code filter products based on product_class. The product_class is a field in the product model. -
Django and opencv how to save a file?
I have a question and I need help. I get this error: numpy.ndarray' object has no attribute 'save How can I save a file? Code below. def filter2(request, id): image = Images.objects.all() if request.method == 'POST': for x in image: img_main = cv2.imread(x.images.path, flags=cv2.IMREAD_COLOR) kernel = np.array([[0, -1, 0], [-1, 5,-1], [0, -1, 0]]) sharpened =cv2.filter2D(src=img_main, ddepth=-1, kernel=kernel) sharpened.save() return redirect("gallery") -
In a multi-domain Django site, what are the pros/cons of routing domains using middleware VS running separate instance per domain
In a Django site with multiple domains, what are the performance implications of using a single Django instance (with middleware handling requests) vs having multiple django instances (one per domain)? Details: I have a site built on a single monolithic Django codebase that uses six different subdomains (admin, event registration, two different user portals, api.example.com, sso.example.com). Currently I have each site running on its own socket, and using separate UWSGI confs (one for each domain under emperor) to manage workers. I'm wondering if it would make more sense to instead have a single UWSGI config, and route each request using this middleware (basically setting request.urlconf at runtime). Would this in any way improve performance? -
The form does not appear even though I added to the views
views.py class LogReply(LoginRequiredMixin,UpdateView): model = LogItem ## fields = ['handler','status','comment'] form_class = LogItemForm template_name = 'log/logitem_detail.html' def get_success_url(self): return reverse('log_view',self.object.id) forms.py class LogItemForm(forms.ModelForm): class Meta: model = LogItem fields = ['handler','status','comment'] widgets = { 'comment':forms.Textarea(attrs={ 'class':'form-control', 'placeholder':'請在此輸入處理情形...'}, ), } logitem_detail.html {% extends 'base.html' %} {% block content %} <div class="card"> <div class="card-header"> <div class="h3">{{ object.subject }}</div> </div> <div class="card-body"> <div class="card-text"> {{ object.description|linebreaks }} </div> </div> <div class="card-footer card-text d-flex justify-content-between text-muted"> <small title="Reporter"><i class="fas fa-user"></i> {{ object.reporter }} <i class="fas fa-phone"></i> {{ logitem.phone }}</small> <small><i class="far fa-clock"></i> {{ object.ctime }}</small> </div> </div> <hr> <div class="card mt-3"> {% if form %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="card-header d-flex justify-content-between"> <div class="h3">Situation</div> <div>{{ form.status }}</div> </div> <div class="card-body">{{ form.comment }}</div> <div class="card-footer card-text d-flex justify-content-between text-muted"> <small title="handler"><i class="fas fa-user-md"></i> {{ form.handler }}</small> <input type="submit" value="Submit" class="btn btn-sm btn-primary"> <small><i class="far fa-clock"></i> {{ object.utime }}</small> </div> </form> {% else %} <div class="card-header d-flex justify-content-between"> <div class="h3">Situation</div> <div> <span class="badge badge-{{ logitem.get_status_class }}"> {{ object.get_status_display }} </span> </div> </div> <div class="card-body">{{ object.comment|linebreaks }}</div> <div class="card-footer card-text d-flex justify-content-between text-muted"> <small title="handler"><i class="fas fa-user-md"></i> {{ object.handler }}</small> <small><i class="far fa-clock"></i> {{ object.utime }}</small> </div> {% endif %} </div> {% endblock … -
Django-React Upload Image Issue
I'm trying to upload image from react to database [django] I got errors GET http://localhost:3000/images/Koala.jpg 404 (Not Found) and images not shown on the page. but it is found in my backend static files. This my view: @api_view(['POST']) def uploadImage(request): data = request.data product_id = data['product_id'] product = Product.objects.get(id=product_id) product.imageSrc = request.FILES.get('imageSrc') product.save() return Response('Image was uploaded') this is my url of the view: path('upload/', views.uploadImage, name="image-upload"), and this is my react function to handle image upload: const uploadFileHandler = async (e) => { const file = e.target.files[0] const formData = new FormData() formData.append('imageSrc', file) formData.append('product_id', productId) setUploading(true) try { const config = { headers: { 'Content-Type': 'multipart/form-data' } } const { data } = await axios.post('/api/products/upload/', formData, config) setImageSrc(data) setUploading(false) } catch (error) { setUploading(false) } } and this my HTML Code <div id='imageSrc'> <h6>upload picture</h6> <input value={imageSrc} onChange={(e) => setImageSrc(e.target.value)} > </input> <input id='image-file' type='file' custom= 'true' label='Choose File' onChange={uploadFileHandler} > </input> {uploading && <Loader />} </div> -
Many to many field or foreign key for reports table
I have users who can be reported and I need to save information of the report. So my user report model looks like this class UserReportLog(models.Model): reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) reported_at = models.DateTimeField(auto_now_add=True) should I add another foreign key to the user who was reported ? which will make it class UserReportLog(models.Model): reported_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) reported_at = models.DateTimeField(auto_now_add=True) Currently there's a many to many field in the user model userReportBy = models.ManyToManyField( UserReportLog, related_name="userReported", blank=True ) I'm not sure which is the best practice -
Unable to push css in heroku service
What I am doing ? I am trying to deploy a django web application on heroku server. Problem I am not able to push css files in heroku server using git push heroku main . When I remove css file from static folder, then everything is going well. remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'CSS/style.css' failed! remote: Traceback (most recent call last): remote: File "/tmp/build_31834d76/manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'CSS/images/mobile-app.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f8a24943cd0>. remote: The CSS file 'CSS/style.css' references a file which could not be found: remote: CSS/images/mobile-app.png remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! … -
Django UpdateView not populating form
I've been stuck on this problem for hours, looking through Django documentation and adjusting my code hasn't helped. I have manually coded a HTML form (for styling reasons). Everything works fine until I try to edit an object via this form. I'm using a standard UpdateView with no additions but for some reason the form is not populating the data in the object. class RPLogbookEditEntry(LoginRequiredMixin, UpdateView): login_url = 'ihq-login' template_name = 'internethq/ihq-rplogbookform.html' model = RPLogbookEntry fields = ['entry_date', 'rpa_code', 'rpa_icao_code','rpa_registration', 'user_role', 'crew', 'crew_role', 'launch_location', 'recovery_location', 'remarks', 'vlos', 'evlos1', 'evlos2', 'bvlos', 'ft_day', 'ft_night', 'remarks', 'no_of_landings_day', 'no_of_landings_night'] def form_valid(self, form): form.instance.user = self.request.user form.instance.rpa = RPA.objects.get(rpa_code=form.cleaned_data['rpa_code']) return super().form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def get_success_url(self): return reverse('ihq-rplogbook-list') + '?month=' + str(self.object.entry_date.month) + '&year=' + str(self.object.entry_date.year) Basically my question is - shouldn't this UpdateView populate my form automatically? -
super() function in __init__ in Meta Class inside Form
Could someone help me understand what is exactly going on here?: class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags'] widgets = { 'tags': forms.CheckboxSelectMultiple(), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for item in self.fields: self.fields[item].widget.attrs['class'] = 'input' I don't know how arguments in self.fields are being passed to init function. Upon my understanding under *args i will receive 'title' and under **kwargs i will receive 'class' : 'input' and for loop will go through oll of the items in fields list and will update 'class' attribute for all of the items. Is that correct?