Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form with dynamic choices won't set choice as selected when bound
I have this form where one of the fields ("wheels") has a dynamically generated list of choices: class CarForm(forms.Form): colour = forms.ChoiceField(choices=(("BLACK", "Black"), ("YELLOW", "Yellow"))) wheels = forms.ChoiceField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["wheels"].choices = [(_, _) for _ in range(4)] When I bind the form with data, Django does not set the choice for the field with the dynamic choices to "selected": f = CarForm({"colour": "YELLOW", "wheels": 2}) f.is_valid() Out[10]: True f.as_p() Out[11]: ''' <p> <label for="id_colour">Colour:</label> <select name="colour" id="id_colour"> <option value="BLACK">Black</option> <option value="YELLOW" selected>Yellow</option> </select> </p> <p> <label for="id_wheels">Wheels:</label> <select name="wheels" id="id_wheels"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected>2</option> <option value="3">3</option> </select> </p> ''' I guess that's because the form's __init__ method is called before the choices are set, but I have to call __init__ first, otherwise the method complains with an AttributeError: 'CarForm' object has no attribute 'fields' I want to show the form with the user's input to the user so that they can see the result of their request and adapt accordingly. It's not very user friendly if the selections they made are not reflected in the form. How can I fix this? -
ImportError: cannot import name 'ReCaptchaField' from 'captcha.fields'
guys im trying to run django server but i have this error from captcha.fields import ReCaptchaField ImportError: cannot import name 'ReCaptchaField' from 'captcha.fields' what can i do im trying to remove and install django-ReCaptcha but nothing change -
¨WorkflowScript: 35: unexpected token: catch @ line 35, column 5¨ from Jenkins build job
Iḿ trying to deploy a build using the following Jenkins file but build job returned an error immediately. The jenkins file seems to be correct. The configuration is: We have App&WebServer on cloud instance1 and installation is owned by user: preProd We have Jenkins server on cloud instance2 and installation is owned by user: jenkins User: jenkins public key is added into instance1 and login without password is working fine The user/admin user in Jenkins web interface is ´testUser´ and using pipeline job with github key included The plan is to deploy a Django build on cloud instance1 jenkinsfile: #!groovy node { try { stage 'Checkout' sshagent(credentials : ['1000']) { sh 'ssh -o StrictHostKeyChecking=no preProd@xxx.xxx.xxx.xx uptime' sh 'ssh -v preProd@xxx.xxx.xxx.xx' } sh 'cd preprod-testP' sh 'pwd' sh 'ls' sh 'git init' sh 'git status' sh 'git pull https://xxxxxxxxxxxx:ghp_qwfaqwefdaf21asffasfas1e@github.com/testP/preprod-testP.git' sh 'git branch' stage 'Build' sh 'virtualenv env -p python3' sh '. env/bin/activate' sh '/home/preProd/preprod-testP/env/bin/pip freeze' sh '/home/preProd/preprod-testP/env/bin/pip install -r requirements.txt' stage 'Test' sh '/home/preProd/preprod-testP/env/bin/python manage.py makemigrations' sh '/home/preProd/preprod-testP/env/bin/python manage.py migrate' stage 'Deploy' sh 'JENKINS_NODE_COOKIE=dontKillMe nohup /home/preProd/preprod-testP/env/bin/python manage.py runserver 0.0.0.0:8000 &' sh 'echo "deployment is successfully completed."' sh 'sudo service gunicorn restart' sh 'sudo service nginx restart' } catch (err) { sh … -
How to create instance of a django model
views.py def create_post(request): profile_inst = Profile.objects.filter(author_real=request.user).first() print(profile_inst) if request.method == 'POST': print('POST request') form = CreatePost(request.POST,request.FILES) if form.is_valid(): print(request.FILES) form.save() else: print('JUST a VISIT!') form=CreatePost(initial={'author':profile_inst}) return render(request,'create_post.html',{'form':form}) ValueError at /create_post/ Cannot assign "'username | admin'": "Post.author" must be a "Profile" instance. Post Model class Post(models.Model): post_id = models.IntegerField(default=0) author = models.ForeignKey(Profile,on_delete=models.CASCADE,null=True,blank=True,default='') title = models.CharField(max_length=255,default="No Title") views = models.IntegerField(default=0) posted_on = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField(upload_to='images/',default='') content = RichTextField(default='',blank=True,null=True) def __str__(self): return f'{self.title}' CreatePost Model class CreatePost(ModelForm): thumbnail = forms.ImageField() title = forms.TextInput() author = forms.CharField(widget=forms.HiddenInput()) # author = forms.TextInput(widget=forms.HiddenInput()) class Meta: model=Post exclude=['views','posted_on','post_id'] above is my view to create post on the blog i'm making, but for some reason django is not accepting profile_inst as a Profile instance and givin' the error shown above. Please ignore the post_id field, that i just created for some purpose but is not yet being used yet as of my knowledge. appreciating any efforts! -
Django DRF use same URL pattern for different views
In Django Rest Framework, I have two separate views for the same model. I would like to use the same url pattern to access both views, and differentiate between the two based on the method that is used. So I have something like: class MyObjectListAPIView(generics.ListAPIView): pass class MyObjectCreateAPIView(generics.CreateAPIView): pass Both views obviously would have different logic. The url pattern for both would be 'myObjects\', and depending on the method that is used (GET or POST), it would need to refer to the appropriate view (MyObjectListAPIView or MyObjectCreateAPIView respectively). Is there a way to achieve this (without reverting to plain Django and losing the functionality of DRF)? -
"GET / HTTP/1.1" 404 405 error occurred when doing class-based-view in django
I tried to make two processes of uploading excel file and saving it into database by using class-based-view, but it occurred an error. views.py from django.shortcuts import render,redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import UploadFileForm, InputForm from .models import Memo import pandas as pd from django.views import View # Create your views here. class upload_file_and_saving_to_database(View): def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request,'report/success.html') else: form = UploadFileForm() return render(request,'report/upload.html',{'form':form}) def saving_to_database(request): df=pd.read_excel(r'C:\Users\leeta\OneDrive\바탕 화면\TK project\myproject\media\upload\sample_file.xlsx') df_cp=df analysis_with_list=df_cp.query('출금액!=0') analysis_with_list=analysis_with_list.loc[:,['적요','출금액']] analysis_with_list=analysis_with_list.groupby(by=['적요']).sum() analysis_with_list.reset_index(drop=False, inplace=True) ss=[] for i in range(0,len(analysis_with_list)): st = (analysis_with_list['적요'][i]) ss.append(st) for i in range(0,len(analysis_with_list)): Memo.objects.create(memo=ss[i]) urls.py from django.urls import path from . import views from report.views import upload_file_and_saving_to_database urlpatterns=[ path("upload/",views.upload_file_and_saving_to_database.as_view(),name="upload"), the error occurred. Not Found: / [30/Dec/2023 15:39:10] "GET / HTTP/1.1" 404 2169 Method Not Allowed (GET): /report/upload/ Method Not Allowed: /report/upload/ [30/Dec/2023 15:39:15] "GET /report/upload/ HTTP/1.1" 405 0 How can I solve this problem? Please help. -
Can you please explain me the form_valid() function here?
class ArticleCreateView(CreateView): model = Article template_name = "article_new.html" fields = ("title", "body") # new def form_valid(self, form): # new form.instance.author = self.request.user return super().form_valid(form) I am reading a book and author is telling that to insert the author automatically we can use this function in our createview inherited class. But he didnt explained anything regarding this function. What is this for_valid() function? What it does? and specially the return line? -
TypeError: Object of type ndarray is not JSON serializable
frontend_data = {'message': 'Data filtering successfully.', 'data': column_data_dict, 'type': 'line_chart', 'column': selected_column} frontend_data.update({'context':context_data}) return JsonResponse(frontend_data) TypeError: Object of type ndarray is not JSON serializable Proper Solution, context_data update frontend_data data -
Django Formset Validation - Validation/saving across two formsets
User interaction: The user have the ability to input bilagsnr, account(konto), debet and kredit. Each bilag object can have several innslag objects. Each bilag can only be saved once, with its innslag objects. Within each bilag, the innslag fields of debet and kredit needs to have sum = 0. How do i solve this? Model: class Bilag(models.Model): bilagsnr = models.PositiveIntegerField(primary_key=True, unique=True) class Innslag(models.Model): innslagBilagsnr = models.ForeignKey(Bilag, on_delete=models.CASCADE) innslagKonto = models.ForeignKey(Kontoplan, on_delete=models.CASCADE) innslagDebet = models.PositiveIntegerField(blank=True, null=True) innslagKredit = models.PositiveIntegerField(blank=True, null=True) View: def bokforing(request): InnslagFormSet = formset_factory(form=InnslagForm, extra=3) if request.method == 'POST': formset = InnslagFormSet(request.POST) if formset.is_valid(): total_debet = 0 total_kredit = 0 for form in formset: if form.has_changed(): form.save(commit=False) debet_value = form.cleaned_data["innslagDebet"] kredit_value = form.cleaned_data["innslagKredit"] if debet_value is not None: total_debet += debet_value if kredit_value is not None: total_kredit -= kredit_value if total_debet + total_kredit == 0: return HttpResponse("Valid") else: return HttpResponse("Not Valid") else: formset = InnslagFormSet() return render(request, "bokforing.html", {'formset': formset}) Overview of validation: Have tried to use different models, forms and so forth. -
Django REST view creates new instead of updating object
I'm using the Django REST framework for the first time. It looks, from the documentation, like serialzer.save() updates an object when given a primary key and creates a new one when not. However, when I go to update an object it creates a new one. (I have not tried to create a new object yet). In serializers.py I have this: class ThingCurrentClassSerializer(serializers.ModelSerializer): active = serializers.BooleanField(read_only=True) class Meta: model = ThingCurrentClass fields = ['title', 'active', 'description_short', 'description_long', 'length_in_minutes', 'adult_only', 'adult_only_reason', 'handout_fee', 'handout_limit', 'material_fee', 'material_limit', 'fee_itemization', 'scheduling_notes', 'special_needs_notes', 'heat_source', 'topic', 'track', 'tags', 'private_camp'] In my views.py I have this: class ThingCurrentClassList(generics.ListCreateAPIView): queryset = ThingCurrentClass.objects.all() serializer_class = ThingCurrentClassSerializer renderer_classes = [TemplateHTMLRenderer] success_url = reverse_lazy('instructables/') template_name = 'thingcurrentclass_list.html' def get(self, request): queryset = ThingCurrentClass.objects.all() return Response({'thingcurrentclasses': queryset}) class ThingCurrentClassDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ThingCurrentClass.objects.all() serializer_class = ThingCurrentClassSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'thingcurrentclass_detail.html' success_url = reverse_lazy('instructables/') def get(self, request, pk): thingcurrentclass = get_object_or_404(ThingCurrentClass, pk=pk) serializer = ThingCurrentClassSerializer(thingcurrentclass) return Response({'serializer': serializer, 'thingcurrentclass': thingcurrentclass}) def post(self, request, pk): thingcurrentclass = get_object_or_404(ThingCurrentClass, pk=pk) serializer = ThingCurrentClassSerializer(thingcurrentclass, data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer, 'thingcurrentclass': thingcurrentclass}) serializer.save() return redirect('thingcurrentclass_list') In the thingcurrentclass_list.html template I have this: {% extends "base_generic.html" %} {% block content %} <html><body> <h1>Class List</h1> {% if thingcurrentclasses … -
Binding web version of pgadmin to gunicorn
I have a gunicorn file that is executing and correctly displaying the web together with nginx and supervisor SOCKFILE=/home/boards/run/gunicorn.sock exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- but in addition to that, now I need to add pgadmin so as to be reachable like this: myweb.com/pgadmin I have added a new location in my nginx file upstream app_server { server unix:/home/boards/run/gunicorn.sock fail_timeout=0; } Here below is the new added snippet: location /pgadmin { proxy_pass http://app_server; include proxy_params; } but I get a 404 when I try to reach www.myweb.com/pgadmin what am I missing? do I have to create a separate gunicorn file? do I just have to add another bind command to that gunicorn snippet as shown and if yes how? thanks -
Trouble with CSRF token validation in python django
enter image description hereI'm currently working on a travel management using python django and I'm having issues with CSRF token validation. I've implemented CSRF protection in my application, but for some reason, it's not working as expected.if login with a user csrf issue were risen what is the reason for this but i give the csrf verification for the login page then what is the reason may occur this -
Select for update through a foreign key
models STATUSES = ( (FAILED_STATUS, "Failed"), (DONE_STATUS, "Done"), (PENDING_STATUS, "Pending"), (BANK_ACCEPTANCE, "Bank Acceptance"), ) amount = models.BigIntegerField() status = models.CharField(max_length=20, default=PENDING_STATUS, choices=STATUSES) wallet = models.ForeignKey("Wallet", on_delete=models.PROTECT) timestamp = models.DateTimeField(null=True, blank=True) class Wallet(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) uuid = models.UUIDField(default=uuid.uuid4, unique=True) balance = models.BigIntegerField(default=0) def deposit(self, amount: int): self.balance = F("balance") + amount self.save() Task @shared_task def perform_tx_periodic(): accpeted_tx = Transaction.objects.select_related("wallet__owner").select_for_update().filter( status="bank_acceptance", timestamp__lte=timezone.now() ) with transaction.atomic(): for tx in accpeted_tx: wallet = Wallet.objects.select_for_update().get(id=tx.wallet_id) if tx.amount < wallet.balance: logger = Logger(user=tx.wallet.owner) wallet.balance = F("balance") - tx.amount wallet.save(update_fields=["balance"]) tx.status = tx.DONE_STATUS logger.withdraw_log(amount=tx.amount) else: tx.status = tx.FAILED_STATUS tx.save(update_fields=["status"]) for query in connection.queries: print(query["sql"]) how can i lock wallet objects through foreign key on transaction model? this code has query n+1 i want to decrease queries after all, is there any way to optimize this task? for example, decrease volume of code, or perform fewer query consider this: each wallet, may have multiple transaction at same time, so if i don't lock each wallet row, i may have non-positive balance in my wallet. we should handle the this situation to -
there has been an admin login error in my code
enter image description here i am not able to see the admin login page i have made seperate pages one named hello and the other my app home i am very new to django [enter image description here](https://i.stack.imgur.com/Muife.png) enter image description here here are some of the screenshots of my code to make it seem better -
New event loop per request Django+ASGI
I got new event loop on each request even if i use daphne as my server with Django. view: async def main_page(request): loop = asyncio.get_running_loop() return HttpResponse(id(loop)) settings: ASGI_APPLICATION = 'project.asgi.application' start server: daphne project.asgi:application or python manage.py runserver (daphne first in installed apps) Logs: Starting ASGI/Daphne version 4.0.0 development server at 127.0.0.1:8000 deps: python==3.10 django==4.2.8 daphne==4.0.0 asgiref==3.7.2 It works like I'm using WSGI server - new loop on each request (according to new loop id). But id should be the same, isn't it? How can i fix it? -
Problem with ROC Curve for multiclass classification model [closed]
enter image description herePlease check the ROC Curve and the code, the ROC Curve is very strange. this is a 6 classes classification problem. Please check the code for any error or any other edit or suggestion. there are 100 images for training and 24 for testing in each class. enter image description here from sklearn.metrics import roc_curve from sklearn.metrics import roc_auc_score fpr = {} tpr = {} thresh ={} n_class = 6 for i in range(n_class): fpr[i], tpr[i], thresh[i] = roc_curve(y_actual, y_pred, pos_label=i) print(len(fpr[0][1])) print(len(tpr[0][1])) # plotting plt.plot(fpr[0], tpr[0], linestyle='--',color='orange', label='Chipping_Tip_most_severe ') plt.plot(fpr[1], tpr[1], linestyle='--',color='black', label='Chipping_Tip_least_severe ') plt.plot(fpr[2], tpr[2], linestyle='--',color='green',label='Crack' ) plt.plot(fpr[3], tpr[3], linestyle='--',color='blue', label='Missing_Tooth ') plt.plot(fpr[4], tpr[4], linestyle='--',color='red', label='Spalling ') plt.plot(fpr[5], tpr[5], linestyle='--',color='yellow', label='Healthy ') plt.title(' ROC curve') plt.xlabel('False Positive Rate') plt.ylabel('True Positive rate') plt.legend(loc='best') plt.savefig('Multiclass ROC',dpi=300) plt.show() -
Is there a way to copy annotations from one Django queryset to another?
I am currently trying to overcome the challenge of ordering a queryset in Django with foreign key attributes. As you may know this can have unintended results with duplicate entries. The other option is to specify an ordering on the same queryset but to avoid duplicates I specified that results should have distinct ids which leads no an error saying the distinct key should be in the initial ordering. So I resorted to creating another queryset to filter the id's in an already annotated queryset so i can get a fresh queryset with which can be ordered by what is needed in the end. -
python manage.py runserver not working or showing errors
Ive set up django on a virtual env and im trying to run it. I've made sure that python is installed and that my virtual env is activated. I created a django project "my_site" with the command django-admin startproject my_site . The virtual env is "my_env" This is my project directory: enter image description here In the command terminal when i run python migrate.py runserver nothing happens, the server crashes with no error message and i am not able to access localhost 8000 enter image description here This is the output for pip list : enter image description here This is the output for pip show Django : enter image description here This is my python and django version enter image description here I tried running : python C:\Users\Ananya\OneDrive\Desktop\django\manage.py runserver , I tried deleting and creating a new env . i was expecting the terminal output to be something like : enter image description here where i can be directed to localhost 8000 -
Routing does not work for Django on Azure Function
I have a Django App and I'm trying to migrate app into Azure Function. But seems like sub routes always return 404. Can someone please help on this. urls.py urlpatterns = [ path(FUNCTION_APP_PATH + '/admin/' , admin.site.urls), ] setting.py FUNCTION_APP_PATH = 'api/app' function.json { "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "route ": "app/{*route}", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" } ] } init.py import azure.functions as func from config.wsgi import application def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse: return func.WsgiMiddleware(application).handle(req, context) Web Page output No web page was found for the web address: http://localhost:7071/api/app/admin/ HTTP ERROR 404 -
How to make a delete button delete a specific post?
I have this delete button with a dialog on it but the button does not get the post right and I think it always starts to delete from the first post so I end up deleting them all also my template does not even gets the correct title of the post even though I'm using the same tag why is that? it always gets the title of the first post and deletes only that not the one I click on I will appreciate your help views.py @login_required() def delete(request, id): poost = get_object_or_404(post, pk=id) if request.user == poost.author: poost.delete() messages.error(request, f'Post deleted!') return redirect("/") post.html (where my delete dialog and button is) <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Modal body text goes here.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary">Save changes</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Are you sure?</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text-muted"> Do you really want to … -
NoReverseMatch at /login/login/signup
I am trying to create a sign up page using django after the user press the sign up button i want the page to redirect them to another page using this line of code return redirect('congrat') and also a function for "congrat" has already been created by me def congrat(request): return render(request,"login/congratulation.html") also the url has been defined in the urls.py file path("login/congrat",views.congrat,name = "congrat"), but for some reason this is the output from the website after the button is clicked I have consulted chatgpt which told me to check my urls.py and check if the function was defined which i have done and i cant seem to find an error there. -
TFIDF Vectorizer not assigning values to all rows of data
I am attempting to create a song recommendation system. For starters I used TFIDF on all genre names with the following code: data['track_genre'] = data['track_genre'].fillna("") tfidf_vector = TfidfVectorizer(stop_words='english') #max_features= 60 tfidf_matrix_genre = tfidf_vector.fit_transform(data['track_genre']) tfidf_vector.get_feature_names_out() Once I did that I used pd.concat to combine it into a dataframe as shown here: data_full = pd.concat([data, pd.DataFrame(tfidf_matrix_genre.toarray(), columns=tfidf_vector.get_feature_names_out())], axis=1) data_full = data_full[data_full['track_name'].notna()] data_full = data_full.drop('track_genre', axis =1) Unfortunately, in the 'data_full' df some of the songs were not assigned any values from the vectorizer. For example, songs with the initial genre of "soul" have no values in any of the new TFIDF columns despite the vectorizer creating a "soul" column. This is unfortunate as my function first filters the data based on the vectorizer's descriptors and with certain soul songs this is impossible and results in an error. On all other genre's and songs I have checked thus far it seems to work well. My question is: Is there a way to ensure the vectorizer gives each row at least one value in the newly created columns? Also, are there any errors in my code / would you like to see more code? Below is where the error comes into play: song_title = … -
Django Admin is not showing X out of X selected and the link to select all
For some reason after I upgrade django to 3.2.21, when I select all records in the admin page, it's no longer showing 100 out of 100 records selected and providing the link to select all records across multiple paginated pages. I'm not doing anything special in the admin class, just set list_display, list_filter, list_display_links, and actions. Anyone knows what might be wrong? -
Creation of django project
Image of my problem(django) After installation of django in pycharm, I tried creating my first ever django project but I encountered a problem. Then I decided to check the version of django installed but same issue appeared. I want to know why is it so and the solution so I could begin with the project. The problem is in the image provided -
I got different results from a chi-squared test when using a calculator and sklearn chi2 function
Recently I was learning about chi2 test. For a toy dataset, X = np.array([0, 1, 0, 0, 1, 1]), y = np.array([0, 1, 0, 1, 0, 1]). When calculating the chi2 statistic and the p-value, I got different results. The first result is: Using online calculator which is the same as I calculate myself based on the knowledge I learned from class. The second result using sklearn chi2 is: Using sklearn.chi2 which I can not understand why.