Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find out what the problem is with Keras load_img?
I am following a tutorial to built a small image classification app and am coming into a problem when I reacth the try/except block. from django.db import models from keras.preprocessing.image import load_img, img_to_array class Image(models.Model): picture = models.ImageField() classified = models.CharField(max_length=200, blank=True) uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return "Image classifed at {}".format(self.uploaded.strftime('%Y-%m-%d %H:%M')) def save(self, *args, **kwargs): try: print('self.picture >>>>>>> ', self.picture) # works fine img = load_img(self.picture, target_size=None) print('img >>>>>>', img) # does not work img_arr = img_to_array(img) except: print('classification failed') super().save(*args, **kwargs) The image gets saved fine to the database, but it the code when I am using 'load_img' doesn't work (as the print statement below does not run) -
Need to remove apscheduler jobs created without an ID
I'm using apscheduler in a Django 2 application. When creating my scheduler and adding the job, I used replace_existing=True but forgot to add an ID for the job. Now, I have several instances of the same job running in Production. How can I remove the extra apscheduler jobs? I have tried get_jobs() and print_jobs() with no luck. Is there a method to view, modify, & delete existing job stores? scheduler = BackgroundScheduler() scheduler.get_jobs() # and scheduler.print_jobs() -
Do I need to use a caching technology like memcached or redis?
I am new to web development in general. I am going a social media website(very much like twitter) using django rest framework as backend and react as front end. I am going to deploy the app to horeku. Now, I just heard about this thing called memcached and redis. So, what is the usecase here ? Should I use it or It's just for high traffic websites ? -
Display Excel file in website with edit functionality using Django
I'm fairly new to Django and here's a uphill task i've been given to with a deadline and i have no seniors to guide me, hence i'm yielding for your support here. Basically i have an excel file with some calculated field that i have to show it in website using Django that lets users edit certain columns and other columns depending on it should get recalculated and retrieved in website I used the following approach: Loaded the excel file to pandas df converted df into json file and passed that into HTML In HTML file, using a for loop i'm traversing and displaying the data, this works well but the problem is with adding a functionality for user to edit certain columns and recalculations. Please guide me or help me with the approach or if you can point me to any documents, i'll be very much thankful to you. -
Two models in one view in django
I'm creating a website where users can post briefs and other users can post their designs for them. How would i design the view so that the user can not only read the brief data on the brief page but also see other users designs for it which would come from a different model. So essentially i want to see the data from the brief model like name, description etc and i also want to see the designs from the designs model which essentially holds the briefid as a foreign key, the user id and also the image field. Would i use a class based function with another function inside to retrieve the designs or? -
Update item status using other model in Django
I am creating purchase order app. I have difficulty to solve following issue. I have 2 models(request model & purchase update model) Once request model created(via form), with "update status button" admin can update follow up status to that specific selected item(via form-only can be access by staff) How I can create a function in views.py to generate task no.2? I could not find any solution in stackoverflow. It would be great if someone can point me to right solution if already discussed. p/s: I am not professional programmer :( Many thanks This is my model class OrderRequest(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE,null=True, blank=True) ref_code = models.CharField(max_length=100,blank=True, default='ABC') link = models.URLField(null=True, blank=True) image = models.ImageField(upload_to='media/images',null=True, blank=True) price = models.FloatField(null=True) draft = models.BooleanField(default=True) logistic_method = models.ForeignKey(Logistic, on_delete=models.CASCADE, null=True, blank=True) note = models.TextField(max_length=100) date_order = models.DateTimeField(auto_now=True) class PurchaseUpdate(models.Model): pu_item = models.OneToOneField(OrderRequest,on_delete=models.CASCADE,null=True, blank=True ) pu_itemprice = models.IntegerField(null=True, blank=True) pu_deliveryfee = models.IntegerField(null=True, blank=True) pu_intdeliveryfee = models.IntegerField(null=True, blank=True) pu_rank = models.IntegerField(null=True, blank=True) pu_complete =models.BooleanField(default=False, null=True, blank=True) Here is my views.py def purchase_update(request): form = PurchaseUpdateForm(request.POST) if request.method =='POST': form = PurchaseUpdateForm(request.POST) instance = form.save(commit=False) instance.pu_item = request.ref_code instance.save() context = { 'form':form } return render(request, 'commerce_autoparts/purchase_update.html', context) -
Method Not Allowed: /api/vote/
i trying to upvote some post but when i open the api page it doesn't upvote the post so what should i do ? and why it gives me method not allowed 405 class Addone(APIView): def post(self, request, *args, **kwargs): qs = Post.objects.filter(publisher=self.request.user) if qs.exists(): query = qs.first() query.votee += 1 query.save() return Response(status=HTTP_200_OK) return Response(status=HTTP_400_BAD_REQUEST) urls.py: path('api/vote/', Addone.as_view(), name='vote'), -
Hi I'm new to docker and I'm trying to run a docker compose file. I keep on getting the fallowing error
docker compose image version: '3.7' services: web: build: . command: python/code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 -
Remove chosen value of django-autocomplete using script
I have assigned a value to the foreign key element (which is an autocomplete in the form) using initial. Coming to the front-end if the category is changed I used script to hide and show fields accordingly. So if I change the category and the auto-complete goes to hidden state I just want to remove its initial value. I tried this: ... var category = $('#id_category').val(); if(category == 'customer'){ $('#id_customer').show(); ... } else { $('#id_customer').val('').hide(); ... } any other way -
(Django python) Using multiple 'for loop' for render
Hey guys I'm making English test system for education by using Django python. the system display one article and several(not fixed) questions about the article. and every question has selectable items which numbers are not fixed. for example { ---------- article -------------- } { ---------- question --------------} { ---------- item ------------------} { ---------- item ------------------} { ---------- item ------------------} { ---------- question --------------} { ---------- item ------------------} { ---------- item ------------------} { ---------- item ------------------} so I defined model like this : # Question DB class Article(models.Model): a_name = models.TextField(unique=True) a_con = models.TextField() #Article Contents class Question(models.Model): q_name = models.TextField(unique=True) q_a = models.ForeignKey(Article,on_delete=models.CASCADE) q_con = models.TextField() #Question Contents q_ans = models.TextField() #Question Correct Answer class Item(models.Model): i_q = models.ForeignKey(Question,on_delete=models.CASCADE) i_seq = models.PositiveIntegerField() #Item Sequence i_con = models.TextField() #Item Contents # Image DB class ArticleImage(models.Model): ai_name = models.TextField(unique=True) ai_a = models.ForeignKey(Article,on_delete=models.CASCADE) ai_src = models.TextField() class QuestionImage(models.Model): qi_name = models.TextField(unique=True) qi_q = models.ForeignKey(Question,on_delete=models.CASCADE) qi_src = models.TextField() class ItemImage(models.Model): ii_name = models.TextField(unique=True) ii_i = models.ForeignKey(Item,on_delete=models.CASCADE) ii_src = models.TextField() and I wrote view.py like this: def findQuestionbyArticle(article_name): _ARTICLE_ = Article.objects.filter(a_name = article_name) for a in _ARTICLE_: _ARTICLE_IMAGE_ = ArticleImage.objects.filter(ai_a = a) _QUESTION_ = Question.objects.filter(q_a = a) _ITEM_ = {} _ITEM_IMAGE_ = {} for q … -
How to Make API in Django?
I am completely new in django API.i dont know how to make API in django. in Other language like PHP, we Create an API file and We call that API file in our Application.is Django following same? i know structure of Django app. i Know how to make app and the crud operations as well.i don't know about API.How to make register API? for Example, i am having below fields in my database first_name last_name email password Then How to Make register API for above fields? -
AuthStateMissing at /complete/azuread-oauth2/ Session value state missing
I am using python social auth https://python-social-auth.readthedocs.io/en/latest/ and Azure backend https://python-social-auth.readthedocs.io/en/latest/backends/azuread.html for o365 login. However after entering all correct credentials i get session value state missing. My error trace is as follows: AuthStateMissing at /complete/azuread-oauth2/ Session value state missing. Request Method: GET Request URL: http://localhost:8000/complete/azuread-oauth2/?code=AQABAAIAAAAGV_bv21oQQ4ROqh0_1-tAd4a1-XSjMQv3OjWjqqpskGiNBkIYGujMLZsuB6QKXbTmFobZnhq6tT558B0grlCbN2xynEE86gQRKIJ91ScEKHLchQu329DKESMKyh2F8fydRn_L_ZBiZpU4QvBU_2r1XzZjo3vFyv6YF4Dh7xuJxMuE52ajXKwhbXoYlq9sZ1lvxOPCk6QjWDVQtRZ5X-WWLZwbwjE0czcEYTrPWE1GSy0D_gz6WfdBACs7AhZ_VNoUKaxdANmIBRaJT9PYGHKJZL-gr4WerbNpkyJ2lK-Qg9Lf75HtxXXXh7CRYLaSCAoypfGV1RggstrrV-JO-0S9cEgUy96yamuV82FfddCSSewfUy8dfASraqCo2ma7dTRr06FpL9gNqLEC2_2pMJVt5VEllmVp6eafTItE4VFqTLsty340QOaWI7yurgvWKpBnBVj5SwVZMv7nGrxOyv5ymEID99HbQm2-pteiPPc0g3BABSi9gWtaDsHD4EpdnS2vVUpEbccIJAfn90_jaCiJUWpjPzoI524Lbaz4xCLXQsMN25ZFDQfUo2Pvszr87E1JUTXSZuftjGszFvQ2UvuLUITp9y0btbs-YLIJvaPFG22yoDcyqFRYhG0H5BlWxcsgAA&state=DChfqXaiLVRCPivB503yqti6sWewqk7S&session_state=de25b1c3-906b-4dbd-a20f-4b0c18122cdb Django Version: 3.1.1 Exception Type: AuthStateMissing Exception Value: Session value state missing. Exception Location: /home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/oauth.py, line 90, in validate_state Python Executable: /home/maz/ct/ct/.venv-ct/bin/python Python Version: 3.8.2 Python Path: ['/home/maz/ct/ct', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf'] Server time: Tue, 08 Sep 2020 14:49:52 +0200 Traceback Switch to copy-and-paste view /home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = await sync_to_async(response_for_exception)(request, exc) return response return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner ▶ Local vars Variable Value exc AuthStateMissing('state') get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x7f3999792070>> request <WSGIRequest: GET '/complete/azuread-oauth2/?code=AQABAAIAAAAGV_bv21oQQ4ROqh0_1-tAd4a1-XSjMQv3OjWjqqpskGiNBkIYGujMLZsuB6QKXbTmFobZnhq6tT558B0grlCbN2xynEE86gQRKIJ91ScEKHLchQu329DKESMKyh2F8fydRn_L_ZBiZpU4QvBU_2r1XzZjo3vFyv6YF4Dh7xuJxMuE52ajXKwhbXoYlq9sZ1lvxOPCk6QjWDVQtRZ5X-WWLZwbwjE0czcEYTrPWE1GSy0D_gz6WfdBACs7AhZ_VNoUKaxdANmIBRaJT9PYGHKJZL-gr4WerbNpkyJ2lK-Qg9Lf75HtxXXXh7CRYLaSCAoypfGV1RggstrrV-JO-0S9cEgUy96yamuV82FfddCSSewfUy8dfASraqCo2ma7dTRr06FpL9gNqLEC2_2pMJVt5VEllmVp6eafTItE4VFqTLsty340QOaWI7yurgvWKpBnBVj5SwVZMv7nGrxOyv5ymEID99HbQm2-pteiPPc0g3BABSi9gWtaDsHD4EpdnS2vVUpEbccIJAfn90_jaCiJUWpjPzoI524Lbaz4xCLXQsMN25ZFDQfUo2Pvszr87E1JUTXSZuftjGszFvQ2UvuLUITp9y0btbs-YLIJvaPFG22yoDcyqFRYhG0H5BlWxcsgAA&state=DChfqXaiLVRCPivB503yqti6sWewqk7S&session_state=de25b1c3-906b-4dbd-a20f-4b0c18122cdb'> /home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/base.py, line 179, in _get_response if response is None: wrapped_callback = self.make_view_atomic(callback) # If it is an asynchronous view, run it in a subthread. if asyncio.iscoroutinefunction(wrapped_callback): wrapped_callback = async_to_sync(wrapped_callback) try: response = wrapped_callback(request, *callback_args, **callback_kwargs) … except Exception as e: response = self.process_exception_by_middleware(e, request) if response is None: … -
Retrieve User's input from Django
I'd like to retrieve the user's input and process them, then render a result page, but it keeps throwing me in Exception !! models.py class MultiStepFormModel(models.Model): headline1=models.CharField(max_length=255) headline2=models.CharField(max_length=255) headline3=models.CharField(max_length=255) views.py def ad_gen(request): context ={} if request.method!="POST": return render(request , 'gen.html' , context) else: headline1=request.POST.get("headline1") headline2=request.POST.get("headline2") headline3=request.POST.get("headline3") try: if form.is_valid (): multistepform=gen_form(request.POST or None) multistepform.save() return render(request , 'Ad result.html' , context) except: messages.error(request,"Error in Saving Data") return render(request , 'homepage.html' , context) forms.py class gen_form(forms.ModelForm): class Meta: model = MultiStepFormModel fields = "__all__" gen.html <form method="POST"> {% csrf_token%} <input type="text" id="fname" name="headline1" ><br> <input type="text" id="fname" name="headline2" ><br> <input type="text" id="fname" name="headline3" ><br> <input type="submit" value="Submit"> </form> -
Django reverse (on_delete) protection on a model instance
Is is possible to protect a model in a reverse relationship. For instance in the models below:- class Foo(models.Model): foo_field1 = models.CharField(max_length=56, unique=True) class Bar(models.Model): bar_field1 = models.ForeignKey(Foo, on_delete=models.PROTECT, blank=True) bar_field2 = models.CharField(max_length=56, unique=True) If an attempt is made to delete an instance of Foo, it wont be deleted as the on_delete attribute on Bar is set to models.PROTECT. So, is it possible to extend that protection both ways? That is, if an attempt is made to delete an instance of Bar, so can it be protected just like Foo, can someone suggest a solution?. -
How to integrate stripe 3D secure payments, with Strong Customer Authentication (SCA) in django-oscar?
I have followed these steps as mentioned here for setting up stripe in Django-oscar, used this link of this answer I have integrated everything and the payment and checkout functionality is working. I assume the above code is using the "Stripe Checkout" as a Stripe Payment Option to accept one-time payments with Stripe. (I am not sure, correct me if I am wrong). Now I want to integrate the 3D secure, Stripe integration due to Strong Customer Authentication (SCA). for integrating the SCA, I checked that I will have to use "Payment Intents API" which supports SCA. I have a few questions here: Do I need to remove the existing flow and use the "Payment Intents API" instead? If yes, the 3d secure, banks interface which appears before the final checkout page, will appear after 3rd step(Payment) in Django-oscar or after 4th step(Preview) in django-oscar ? Most importantly, how can I integrate 3D secure in this existing checkout flow that I currently have. I also have dj-stripe installed in my application. Please suggest me the steps and approach I need to follow step by step. Please, point me in the right direction, I just shared my understanding, I need to … -
Django 3.1 websockets chat [closed]
I'm trying to implement connection between users in django. I know i can do it with django channels but i found WebSockets in Django 3.1 and now I'm wondering how to implement something like group_send in django channels to that solution. I tried something like this: async def room(socket, id): await socket.accept() user = await socket.user if user.is_authenticated: while True: message = await socket.receive_text() message = json.loads(message) await socket.send_text(json.dumps(message)) else: await socket.close() but this doesn't work. -
Django - managing and accessing background processes
I'm looking for the cleanest way to serve data in Django 3.1 from background processes and to manage those processes "in" Django 3.1. Problem: I have couple sensors/cameras in my network which I want to monitor -- pull data and process each one of them (that I've already got). Now in Django I want to manage them (add new sensors / delete old ones / set alarms if something happens and saving it all to database) and present their current values thorugh views. So I need them (sensor processes and django) to communicate so I can pull data from those processes. I was thinking about some kind of global singleton manager of those processes that would be initialized on start of django app. I don't know where is the best place to do it so I could pull information about sensors from database to initialize on start of django app and access it later i.e. in views. Another solution would be to run this manager as app and django app independently and communicate through named pipes or other IPC method. But then I would have to store information about sensors in this manager app and django would serve just as … -
Adding permission based on the logged in user. Django
How can i deny a user who did not create a post an ability to delete the post of another user and also how can i display various edit functions for a post based on the user? Meaning that if you are the creator of the post, only you can have access to editing that post. (for example, if you are logged in as the creator of the post, the post-view displays more options to edit/delete your post). Can i create this permission through admin-groups or do i have to use another library? views.py def ViewPostMain(request, pk): post = Post.objects.get(id=pk) # where id is taken as the field name from the DB submissions = Submission.objects.filter(post_id = pk) # post_id is taken from db. context = {'post' : post, 'submissions' : submissions} return render(request, 'view-post.html', context) view-post.html template {% extends 'base.html' %} {% block content %} <h1><i> {{ post.title }} by {{post.author }}</i></h1> {{ post.post_creation_time }} {{ post.genre }} {{ post.stage }} {{ post.optional_notes }} <div> <hr> <a href="{% url 'delete_post' post.id %}">(Delete Post)</a> <hr> </div> <h3><i>Submissions</i></h3> <h6>{{ submissions.count }} submissions total </h6> <h3><i><a href="{% url 'create_submission' post.id %}">Create a submission</i></a></h3> {% for submission in submissions reversed %} <ul> <p> post_id: … -
A way to count objects in Django
I need to create a view in Django to count every vehicle on my DB. count=Vehicle.objects.all().count() count=Vehicle.objects.all().count() -
How can i make a voice recorder for my Django chat app like whatsapp?
I want to add a voice message to my chat app which is made by Django, for now, users can upload Audio from their devices, but how can I allow users to record the voice directly from my website and send it to the server-side with ajax or even refresh the page? Here is my models.py class GroupMessage(models.Model): group = models.ForeignKey( ChatGroup, related_name='chat_group', null=True, on_delete=models.CASCADE) message_sender = models.ForeignKey( User, related_name='group_message_sender', null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) message = models.TextField(null=True, blank=True) # //////// Files file = models.FileField( upload_to='social/group_files', null=True, blank=True) video = models.FileField(upload_to='social/group_videos', null=True, blank=True) image = models.ImageField( upload_to='social/group_images', null=True, blank=True) audio = models.ImageField( upload_to='social/group_audio', null=True, blank=True) # Files //////// ... Here is my views.py that handles submitting group file def send_group_file_message(request, pk): group = get_object_or_404(ChatGroup, pk=pk) try: area = get_object_or_404(Area, pk=request.GET.get('area')) except: area = None message = GroupMessage( group=group, message_sender=request.user, file=request.FILES.get('file'), image=request.FILES.get('image'), video=request.FILES.get('video'), audio=request.FILES.get('audio'), area=area) message.save() return redirect('social:chat_group', pk=pk) I have been searching for this for about a week and I can't find anything, I would appreciate any help! -
DJANGO PYINSTALLER ISSUE
I'm trying to compile a Django (3) applications that uses pymongo and channels. I followed steps in a ticket in stackoverflow, I got the .exe file but when I try tu run it using app.exe runserver I got this error : \AppData\Local\Temp\_MEI149762\Test_Project\settings.pyc' Failed to execute script manage I've found nothing on the net discussing this issues. HELP PLEASE. -
Integrating java with django backend api
I am working on a project which uses django rest-framework as the rest-api and react as the frontend. While Python is a very good language and I was able to make most of my api work in django, there were a couple of features which I felt were lacking. I wanted to implement digital signature on a pdf in my api. I looked into Endesive which seemed like a good library in python for achieveing that. I would still like to prefer to use Java as a framework in my backend to implement this. So essentially I wanted to know if there is a compatibility of java and django to serve at the backend together? What I want to do is to: Get The data as a request in the rest api in django. Send the data to a java script for some processing and digital signature. From Java send the data back to django python which sends the data as a HTTPResponse to the client side. I have looked into Jython. But I was wondering if django would support such api calls or not.. Is there a library in django/python which would integrate java with Django Python? If, there … -
how to make a rows in column as a link in table created from djangotable2 and also apply django_filters
may i know how to get a link able column(particular,rest all will be normal table) in a table created from Django table 2 my previous html code was- {% for a in as %} <a href="{% url 'b' a.aid %}"><b>{{a.aname}}</b></a> {% endfor %} how will it work in a django table format my tables.py file class ATable(tables.Table): class Meta: model = A kindly help -
How to redirect to a dynamic url in django
I am working on a django project. in the project I have a dynamic url as follows app_name = 'test' urlpatterns = [ path('root', views.root, name='root'), path('output/<str:instance>', views.output_page, name='output_page'), ] There exists two pages in the application. In the root page there exists a form which when submitted should redirect to the output_page. But because the output_page is a dynamic url, I am not able to redirect. Here is my views file def root(request): if request.method == 'POST': name = request.POST.get('name') job = request.POST.get('job') return redirect("test:output_page") return render(request, 'test/root.html') def output_page(request, instance): record = Object.objects.all(Instance_id=instance) return render(request, 'test/output_page.html', {'record': record}) Here is the Model class Object(models.Model): Name = models.CharField(max_length=200, null=True, blank=True) Job = models.CharField(max_length=200, default="") Instance_id = models.CharField(max_length=200) When the redirect happens I want the url to be as follows http://127.0.0.1:8000/output/test-001 where test-001 is the instance_id in the model. The output_page should filter all the data in the model with instance_id test-001 -
Django {% translate %} does not work in project's base.html
I am internationalizing my app and need to translate nav links into their Italian counterparts. All the apps in my project share the same base.html file located in project_folder/templates/base.html. I also created a locale folder inside project_folder containing the .po file for base.html. Inside base.html I have the nav links I want to translate: {% load i18n %} <!doctype html> <html> <body> <nav> <a href="#">{% translate "Define" %}</a> <a href="#">{% translate "Profile" %}</a> ... </nav> </body> </html> Here is the corresponding portion of my .po file: #: project_folder/templates/base.html:32 msgid "Define" msgstr "Definisci" #: project_folder/templates/base.html:35 msgid "Profile" msgstr "Profilo" Despite this, when I switch the site to Italian, the links are all still in English. Other translations done similarly inside app folders in other parts of the website work perfectly. Also, in my settings.py I specified LOCALE_PATH = [ os.path.join(BASE_DIR, 'locale'), ] It seems that Django is not able to find the .po files at the project level, however, there is no error when I compile them and everything seems to be working until I render the nav. Can anybody help?