Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep dropdown value in form after submit with Bootstrap and Django?
I've got a Bootstrap search form and I want to keep the values populated after submitting the form. Using Django and Jinja2 I can accomplish this using the value attribute for a regular input: <div class="form-group required"> <label class="control-label" for="carrier">Carrier</label> <input type="text" class="form-control form-control-sm" id="carrier" name="carrier" placeholder="Enter carrier" maxlength="25" value="{{request_data.carrier}}" required> </div> I'm trying to do the same thing with a Bootstrap dropdown/select field but after submitting the form the value resets back to the default value: <label for="environment">Select Environment for Data Search</label> <select class="form-control form-control-sm" name="environment" id="environment"> {% for env in environments %} <option>{{env.name}}</option> {% endfor %} </select> I tried adding the value attribute to the select tag but it didn't work and also messed up some formatting. Also, I don't have experience with PHP so ideally the solution wouldn't use PHP. Thanks -
django button with link to prefiltered data
Hej! I have multiple views, some with result tables and some detail views. From the detail views there should be links to other detail views (which works) and to some of the result tables with prefilled forms/prefiltered results. For example after the name given in the detail view. If clicked on the button I want to get redirected to the result table already filtered for the name of (e.g.) the parent institution given in the detail view. But I want to use the same template for all detail views (every institution gets a detail view) so it should be universal and not hard coded. Does anyone knows I could achieve that? I'm totally blank and can't find a good solution. # forms.py class SearchInstitutionsForm(forms.Form): name = forms.CharField( label="Name", required=False, ) # views.py def search_institution(request): if request.method == "POST": # create a form instance and populate it with data from the request: form = SearchInstitutionsForm(request.POST) if form.is_valid(): query = institution_filter_query(form) context = { "result_data": serialize(query), "form": form, "show_form": False, } return render(request, "stakeholders/search_form.html", context) else: form = SearchInstitutionsForm() class InstitutionDetail(DetailView): model = Institution def get(self, request, *args, **kwargs): institution = get_object_or_404(Institution, pk=kwargs['pk']) context = {'institution': institution} return render(request, 'stakeholders/institution_detail.html', context) # … -
Customize a response from a mutation using django-graphql-auth with graphene
I'm using django-graphql-auth and graphene on my django project. The django-graphql-auth library is nice but it lacks a bit on documentation and examples of customization. I already sent this question there but repo does not seem to get much activity lately (time to replace and use another package in the project perhaps), so I'll try my luck here: most of the questions related to customization are regarding inputs. In my case I'd like to change the output of the Register mutation, as I need the id of the user created on the response. So far what I manage to accomplish was to create a new custom mutation that inherits register, so I can add the logic to grab the created user: class RegisterCustom(mutations.Register): response = graphene.Field(RegisterResponseType) @classmethod def mutate(cls, *args, **kwargs): try: res = super().mutate(*args, **kwargs) if res.success: user = get_user_model().objects.order_by('-date_joined')[:1] return RegisterCustom(success=True, error="", user_id=user[0]['id']) except Exception: raise Exception(res.errors) However the return is not what I expect { "errors": [ { "message": "None", "locations": [ { "line": 472, "column": 5 } ], "path": [ "registerCustom" ] } ], "data": { "registerCustom": null } } if I add a print right before return let's say print(user[0]['id']) I can see the user … -
Preventing/Reducing deadlocks within a django application
I've been having a few issues recently working with a large MySQL database within django, MySQL seems to be having issues with deadlocks. I keep getting the error: (1213, 'Deadlock found when trying to get lock; try restarting transaction') Usually this seems to happen when calling the save or create functions for a new model instance (e.g). payment = Payment.objects.create( to_member=to_member, to_name="%s" % to_member.username, from_member=from_member, from_name="%s" % from_member.username, description="Resubscription", type='resubscription', amount=5.00, currency=from_member, processor='e-wallet' ) The particular table I'm trying to insert into has about 3.1 million rows and a size of 2.2 GB. In production the application has quite a number of active users (Member). The Payment model has two particular foreign keys (to_creator and from_member). So I wondered if that might be the cause of the be the cause of the issue rather than just on the Payment model? I've tried tweaking various aspect of the mysql configuration to manage this, but I seem to either get more deadlocks or the whole system locks up! Below are my current settings for the locks: Database locks Any help would be greatly appreciated. I've been pulling my hair out over the last few days about this. Dan -
Remove Decimal like " [Decimal('1220'), Decimal('160')] "from Django Queryset results
I have a queryset result which I would like to put into a list of Data and a list of Labels for Chart.js without showing Decimal. In my view.py the following funtion based view is written: labels = [] data = [] total_transactions_by_user = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins') ) ).order_by('-total') for each in total_transactions_by_user: labels.append(each["coin__name"]) data.append(each["total"]) The results of the lists are: ['Bitcoin', 'Dogecoin'] [Decimal('1220'), Decimal('160')] How do I remove Decimal() ,so I have 1220, and 160 in my List[] Thank you in advance. -
how can i create mini photo while creating photo?
i have a photo upload service on django. when i add a photo I want it to add one more photo with 50% split. If I put it in the pre_save on my photo save service, it can't find the photo (because it's not actually on the server) If I add it to the post_save, it goes into loop and adds unlimited when I add a photo (postman or etc.) How can get to save a small photo at a time?. here is my model class UserPhoto(General, Status): user = models.ForeignKey(UserBase, on_delete=models.CASCADE, verbose_name="User Id", related_name='UserPhoto_user', null=True, blank=True) link = models.ImageField(blank=True, null=True) order = models.IntegerField(null=True, blank=True) mini_link = models.ImageField(upload_to='mini_photos', blank=True, null=True) class Meta: db_table = 'user_photos' my view class UserPhoto(APIView): def get_object(self, pk): try: return Photo.objects.get(user__user__pk=pk) except Exception as e: return e def get(self, request): try: photo = self.get_object(request.user.pk) serializer = UserPhotoSerializer(photo) return Response(serializer.data) except Exception as e: print(e) def post(self, request): serializer = UserPhotoSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request): photo = self.get_object(request.user.pk) serializer = UserPhotoSerializer(photo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my serializer class UserPhotoSerializer(serializers.ModelSerializer): class Meta: model = UserPhoto fields = '__all__' def create(self, validated_data): validated_data["user"] = … -
Can I just only use MySQL command instead of pure Model in Django? [closed]
I'm newbie in Django and in my first project, I realise that it isn't neccessary to use the pure module Model of Django, and I prefer to use MySQL command to handle data. So when should I use the pure Model instead of MySQL to handle data? Are there any advantages of the Model over MySQL? -
individual Response message on perform_destroy()
I've written a custom perform_destroy()-method to do some additional checks. def perform_destroy(self,instance): force = self.request.data.get('force',None) resp = {} if Processingstepstatus.objects.filter(orderfile__order=instance).exists() and not force: raise serializers.ValidationError({"message": "Order already in production and can't be canceled cost-free. Perform Delete Request with parameter \"force:True\" to cancel and assume the costs of "+ str(instance.currentcosts)+"€" }) else: if Processingstepstatus.objects.filter(orderfile__order=instance).exists() and force: resp['invoice'] = "Placeholdervalue" instance.canceled = True instance.save() resp['message'] = "Successfully canceled your order." return Response(resp,status=status.HTTP_200_OK) This should give back a json-response with the message and the invoice information but it doesn't give any response except 204 - no content. I think it is being overwritten by the higher-level method destroy() here, right? How to handle that? best regards -
What is the recommended Django project strcuture for a SaaS product?
I would try to explain our desired product idea as clear as possible but feel free to ask further questions. So, basically what we want to build is a SaaS product that will be used by multiple clients. For now, we're not interested in custom domains like (cust1.myproduct.com, cust2.myproduct.com) and we will simply be using one database to manage all customers' data. So far so good. Our SaaS product will be sold to enterprise organizations which will then be used by their employees. So for any one customer organization, there are three types of roles that we would like to provide their users, as follows: Admin: An organization's admin that should be able to do all the settings for that particular organization Manager: An organization's manager that can manage the users that are under his/her team Employee: A normal user with bare minimal permissions that can only manage his own data Now, to provision customers for this SaaS product and to set their global settings (e.g. maximum allowed users, license type etc), we also plan to create an admin portal and APIs that will be used by our internal employees only. For this portal, we also want to define roles … -
Windows Apache stopped working and doesn't start anymore - "httpd.exe -k start" doesn't give errors
I have been hosting my Django REST project on a Windows server using Apache such that it works from https. Today it stopped working and I've been trying to find out the issue but I can't seem to get any useful info out of Apache. If anyone knows how to properly debug the error, or recognizes the issue I would greatly appreciate any help! I start Apache using PS C:\Apache24> bin/httpd.exe -k start Powershell doesn't say anything after this. But when I attempt to stop Apache it says it was never started! Again with no reason. PS C:\Apache24> bin/httpd.exe -k stop The 'Apache2.4' service is not started. I also checked the error.log, which again simply mentions that it failed to start. AH00378: Failed to start the 'Apache2.4' service This is my httpd.conf (I removed a lot of comments and boilerplate code). Note that it has worked before, I didn't change a thing. Define SRVROOT "c:/Apache24" ServerRoot "${SRVROOT}" Listen 8000 User daemon Group daemon ServerName 85.999.999.85:8000 # Django Project LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" WSGIScriptAlias / "c:/users/administrator/Desktop/django1/project/wsgi.py" WSGIPythonPath "c:/users/administrator/Desktop/django1/" <Directory "c:/users/administrator/Desktop/django1/project/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "c:/users/administrator/Desktop/django1/static/" <Directory "c:/users/administrator/Desktop/django1/static/"> Require all granted </Directory> WSGIPassAuthorization on … -
Django DRF - How to interact with a POST endpoint using CURL?
I'm new to Django DRF or API development in general, please be patient with me ;) Beside some pure get API views I now wanted to setup my very first endpoint where I can send data to, so I decided to go with a user password change. Here is what I did so far: views.py @api_view(['GET', 'POST']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def update_user(request): if request.method == 'GET': serializer = UserSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = UserSerializer(request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) password = serializers.CharField( max_length=128, min_length=8, write_only=True ) class Meta: model = User fields = ('id', 'user', 'password', 'pin', 'avatar') read_only_fields = ('id', 'user') def update(self, instance, validated_data): password = validated_data.pop('password', None) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() return instance Now the question is how can I update the referenced fields like "pin" or especially "password" using curl. The first thing I always do is to get myself a new token like this: curl -X POST -d "user=admin&password=admin" http://localhost/api/v1/token/obtain {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWYzN2RiODUtYjU5Yy00YjRmLWFhNjYtMDExNGFmYWQ4ZDdiIiwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6MTYzNDE3Mjg3MiwidXNlciI6ImFkbWluIiwib3JpZ19pYXQiOjE2MzQxMjk2NzJ9.zz9Zyai3Y7MhR_chGkzA6jXY_BdjN5Eu2muRvyWIppw"} With this token in place I can now reach the update_user endpoint but I don't understand how to interact with it … -
Type Error: Init Requires 1 Positional Argument Yet 2 Are Given
Hey so I'm getting this error when I'm trying to make a text area on my site to update a user's 'about' information. It just handles the info of an existing user to update their 'about' field. Any more info needed just let me know and any insight/solutions would be appreciated, thanks in advance. class change_about(UpdateView): def get_object(self, queryset=None): return User.objects.get(user=self.request.user) def form_valid(self, form): instance = form.instance # This is the new object being saved instance.user = self.request.user instance.save() return super(change_about, self).form_valid(form) -
Django Multiple Queries
I'm using lots of queries to find the sum of fields [ft_day, ft_night] in multiple records for specified date intervals e.g. last 7 days, last 6 months etc. This is needed to display a summary of total times at the aforementioned date intervals in a template. ft_total is a property in Models Is there a more efficient way to do this? Not really sticking to DRY here. Thanks for your help. views.py get_context_data() ## shortened ## context['last_6_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 5)/12), (self.date_now.month - 6) % 12 - 1, self.date_now.day), self.date_now) ).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total')) context['last_12_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 12)/12), (self.date_now.month - 12) % 12 - 1, self.date_now.day), self.date_now) ).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total')) -
Frontend, I don't understand if querySelector has been found Frontend
I'm writing the front,ajax response js. The final code comes, which must be inserted on the page Like after const div = document.querySelector('.row_wow_fadeIn>#xxx1'); the code doesn't work. js function ajaxSend(url, params) { // Отправляем запрос fetch(`${url}?${params}`, { method: 'GET', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(response => response.json()) .then(json => render(json)) .catch(error => console.error(error)) } const forms = document.querySelector('form[name=filter]'); forms.addEventListener('submit', function (e) { // Получаем данные из формы e.preventDefault(); let url = this.action; let params = new URLSearchParams(new FormData(this)).toString(); ajaxSend(url, params); }); function render(data) { // Рендер шаблона let template = Hogan.compile(html); let output = template.render(data); const div = document.querySelector('.row_wow_fadeIn>#xxx1'); div.innerHTML = output; } let html = '\ {{#twister}}\ <div>\ <img class="X" src="{{ image }}" class="img-fluid">{{ title }}\ <p class="text-dark">{{ price }} ₽</p>\ </div>\ </div>\ {{/twister}}' Html: <!--Grid row--> <div class="row_wow_fadeIn row d-flex justify-content-center wow fadeIn col-md-12"> <!--Grid column--> <div class="col-lg-3 col-md-6 mb-4"> <div> <div id="xxx1" class="XXX"> {% for twister in case_list %} <img class="X" src="{{ skin.image.url }}" class="img-fluid">{{ skin.title }} <p class="text-dark">{{ skin.price }} ₽</p> {% endfor %} </div><input type="button" onclick="LetsGo()" value="!!!Исчо!!!"> </div> </div> <!--Grid column--> </div> -
I need my Kivy App to send data to my Django Website
So I created a App with Kivy that creates a poll. I want to send this poll data (Name, Time) to my website made with django. Has anybody experiece with it or knows how I can do it? -
Images from database not displaying in Heroku Django after hosting
I have few images in my SQLite database which I will be changing from admin panel over a period of time. I have hosted the django app in heorku(free service). All the static images are displaying (The one's not in database), but the uploaded images are not displaying. I have uploaded the image before deploying. The description for each image is being displayed but the image is not. I am using whitenoise and have viewed multiple other answers and they have not worked settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' if os.getcwd() == '/app': DEBUG = False html template: <div class="container"> {% comment %} Row 1 {% endcomment %} <div class="row my-5"> {% for image in images %} <div class="col-sm col-md-4 col-lg-4 col-xl-4 my-3"> <div class="card" > <img loading='lazy' src="{{image.image.url}}" class="img card-img-top my-2" alt="{{image.title}}"> <div class="card-body"> <p class="card-text">{{image.title}} </p> </div> </div> </div> {% endfor %} </div> </div> models.py : class Gallery(models.Model): image = models.ImageField(upload_to … -
The view "..." didn't return an HttpResponse object. It returned None instead
I am currently getting a Value Error on my current application where the program is supposed to print a pdf file. The full error message states the following: ValueError at /accConnect/trialBalanceMonthly/8 The view main.views.trialBalanceMonthly didn't return an HttpResponse object. It returned None instead. I have tried to check if there was any module I am missing and checked to see if the bool value that printing this file depended on was True (it was )- So I can't seem to find what could be causing this problem. My current code is as follows: URL.py: path('accConnect/trialBalanceMonthly/<int:reports_pk>' , views.trialBalanceMonthly, name='trialBalanceMonthly'), path('accConnect' , views.reportsHome, name='reportsHome'), View.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML import tempfile def trialBalanceMonthly(self , reports_pk): pkForm = get_object_or_404(SettingsClass, pk=reports_pk) complexName = pkForm.Complex # CHECKING TRIAL BALANCE MONTHLY SETTINGS if pkForm.Trial_balance_Monthly == True: # SQL STATEMENT baseTRBMonth = 'SELECT Master_Sub_Account , cAccountTypeDescription ,Debit , Credit FROM PostGL AS genLedger ' \ 'Inner JOIN Accounts ' \ 'on Accounts.AccountLink = genLedger.AccountLink ' \ 'Inner JOIN _etblGLAccountTypes as AccountTypes ' \ 'on Accounts.iAccountType = AccountTypes.idGLAccountType ' \ 'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) ' \ 'AND genLedger.TxDate > ? ' xtrbMonth = … -
Create a django model for saving train and test data in database
I am trying to create a website by django which a user can upload a csv file. in server I want to save this csv file as train data for a machine learning model. and I can't make a Model by the csv file because I don't know the name of the fields. and these names can change in differant datas. for example for one data it may seem like this: class TrainData(models.Model): humidity = models.IntegerField(...) wind_speed = models.IntegerField(...) is_it_raining = BooleanField(..) and we want to run a machine learning algorithm on this model by fields. and another data will be like: class TrainData(models.Model): X1 = models.CharField(...) X2 = models.CharField(...) X3 = models.CharField(...) y = models.CharField(...) a bad approach is (I guess) to convert this csv file into a DataFrame and convert DataFrame into a Pickle file and save it in data base by a model like bellow: class TrainData(models.Model): data = PickledObjectField() is there a better way to create this model?? and is creating data to pickle a good practice? -
Python Django variables data duplication after page refresh
I am passing a string to template, and It works fine, but when I reload the page, that string is duplicated. The string is generated dynamically and contains html-table, I want to render a table from variable in my template Only server reset helps to see the actual table without duplicates Code from views.py: def test(request): headings = ('RED', 'GREEN', 'BLUE') tb = Table() tb.make_headings(headings) cell_1 = Cell('1') cell_2 = Cell('2') cell_3 = Cell('3') row_1 = Row() row_1.add_cell(cell_1) row_1.add_cell(cell_2) row_1.add_cell(cell_3) tb.add_row(row_1) html_table = tb.create_html_table() return render(request, 'test.html', context = { 'table' : html_table }) create_html_table() function: def create_html_table(self): html_table = '<table>' for row in self.raw_table: html_row = '<tr>' for cell in row.cells: html_cell = '<td>{}</td>'.format(cell.get_data()) html_row += html_cell html_row += '</tr>' html_table += html_row html_table += '</table>' return html_table Row code: from .cell import Cell class Row(): cells = [] def __init__(self): self.cells = [] def add_cell(self, cell: Cell): self.cells.append(cell) def get_cells(self): return self.cells Cell code: class Cell(): def __init__(self, data = []): self.data = data def get_data(self): return self.data -
Without AuthMiddlewareStack how can I get logged user in Django channels?
Without AuthMiddlewareStack how can I get logged, user? Because I am not used auth models that's why self.scope['user'] returning the 'Anonymous'. I tried to add this class AllowedHostsOriginValidator - doesn't work. I want a session user. please help me. routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from chat.consumers import ChatConsumer from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('ws/chat/pm-with/<str:username>/',ChatConsumer()), ]) ) ) }) consumers.py from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from chat.models import user,Thread,Message from chat.views import ChatView from django.contrib.sessions.models import Session class ChatConsumer(SyncConsumer): def websocket_connect(self,event): me = self.scope['user'] other_user = self.scope['url_route']['kwargs']['username'] getOtheruser = user.objects.filter(username = other_user).first() self.send({ 'type': 'websocket.accept', }) def websocket_receive(self,event): print("new event is received") print(event) self.send({ 'type': 'websocket.send', 'text': event.get('text'), }) def websocket_disconnect(self,event): print("disconnect event is called") custom user models models.py class user(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50,default="", blank=True, null=True) last_name = models.CharField(max_length=50,default="", blank=True, null=True) username = models.CharField(max_length=50,default="", blank=True, null=True) password = models.CharField(max_length=100,default="", blank=True, null=True) image = models.ImageField(upload_to ='user_image',default="",blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) deleted = models.DateTimeField(default="",blank=True, null=True) is_deleted = models.BooleanField(default=False) I want login users from custom models, not auth user models. please help me for this -
How to delete old multiple images on edit
I have multiple images in my product model. I got parts from here: multiple images I want to change old images to new when I use change_view. Here's my model.py: class Product(models.Model): title = models.CharField(max_length = 45) description = models.TextField(null = True) image = models.ImageField(upload_to = 'store/full/', null = True, blank = True) def __str__(self): return self.title class Meta: ordering = ['title'] verbose_name = "Product" verbose_name_plural = "Products" def get_image_filename(instance, filename): title = instance.product.title idd = instance.product.id slug = slugify(title) return "store/additional//%s-%s-%s" % (idd, slug, filename) class ProductImage(models.Model): product = models.ForeignKey(Product, default = None, on_delete = models.CASCADE, related_name = 'image_set') image = models.ImageField(upload_to = get_image_filename, verbose_name = 'Image') Here's my views.py: def create_view(request): ImageFormSet = modelformset_factory(ProductImage, form = ProductImageForm, extra = 4) form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, files = request.FILES) formset = ImageFormSet(request.POST, files = request.FILES, queryset = ProductImage.objects.none()) if form.is_valid() and formset.is_valid(): obj = form.save(commit = False) obj.save() for form in formset.cleaned_data: if form: image = form['image'] photo = ProductImage(product = obj, image = image) photo.save() messages.success(request, "Created!") return redirect('shop.all') else: print(form.errors, formset.errors) else: formset = ImageFormSet(queryset = ProductImage.objects.none()) context = { 'form': form, 'formset': formset } return render(request, 'shop/products/create.html', context) def change_view(request, id): … -
Reload django template into ajax response
is it possible to reload a Django template after an ajax call? This is my code. script.js $('.test').click(function(){ var platform = $('#testModal').attr('test-attr'); $.ajax( { type:"POST", url:"test", headers: { 'X-CSRFToken': TOKEN }, dataType: "json", cache : false, processData : false, contentType : false, data: string, success: function(data) { location.reload(); } }); }); view.py return render(request, "user_interface/index.html", {'my_var': 'abc', 'my_var_2': 'cde'}) I tried to use return HttpResponse(json.dump({'res': 'Ok', 'err': None}), content_type = "application/json") but when i reload the page it fails. -
how to resolve getattr() error in django?
I am doing a project in Django, and I think i have made changes in some models, then after i am getting these errors, (env) PS C:\Users\ashwi\Documents\GitHub\Recruiters\recruiters> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\ashwi\Documents\GitHub\Recruiters\recruiters\AMCH_recruiter\models.py", line 6, in <module> class Candidate(models.Model): File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\fields\__init__.py", line … -
Automatic connect gitlab pipline with azure web services
I have my webapp code on GitLab. I want to deploy it using Azure web services. But I want it in such a way that, when I push the code to branch it will first be pushed in GitLab then automatically on azure web services.. Is there any way to do this? I searched for a solution on the internet but not found the latest one. -
Django: Render list of model objects and post back the same list without changing item type in the list
On the first page, the user will click the upload button and several "model objects" will be stored into a list and render to one HTML component on the second page. Then if the user clicks the "save" button on the second page, the value in that input component will be posted back to the backend and further process will be done. view.py: def manual_upload_file(request): upload_objs = [TModel1.objects.get(m_id=1), TModel1.objects.get(m_id=2), TModel1.objects.get(m_id=3)] if "persist_data" in request.POST: objs_to_be_processed = request.POST["persist_data"] .... return render(request, 'components/page2.html', {'upload_objs':upload_objs }) page2.html: <form action="{% url 'page2' %}" method="post"> {% csrf_token %} <button class="btn btn-primary" name="persist_data" type="submit" value="{{upload_objs}}"> Save </button> </form> The problem here is that {{upload_objs}} in button value of page2.html will become pure string. And therefore all the model objects inside the list lose its property and all become part of string , i.e. when it post back, the request.POST["persist_save"] received in view,py is: "[<TModel1: TModel1 object (1)>, <TModel1: TModel1 object (2)>, <TModel1: TModel1 object (3)>]" Is there any template tag I can keep all objects as model object after render it to html page. For example, something like: value="{{upload_objs|list}}" Or is there any solution? Thank you