Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a task to Celery without waiting?
I have the following code in my tasks.py file: @app.task(bind=True) def create_car(self, car): if car is None: return False status = subprocess.run(["<some_command_to_run>"]) return True It should run the command <some_command_to_run> but for some reason the website waits it to finish. I thought the whole point of Celery that it will be run in the background and return status. How can I submit this task in asynchronous way? The wanted behaviour: user asked to create a new car instance, it will add a task to the queue and return true that indicating that the car was requested correctly. In the background it will run that command and return (somewhere - not sure yet where) that status. How to do it? -
i use command location.reload() but its not working
im still new to django and i was trying to make my cart icon to have numbers that show how many items. when i press the add button its didnt work and i must to self reload before see the numbers + or -. can someone found the mistake and write in comment, that will really help me . function updateUserOrder(productId, action) { console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'productId': productId, 'action': action }) }) .then(response => response.json()) .then((data) => { console.log('data:', data) location.reload() }) } -
ERROR: Your view return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view
I am working on a Django Project where i add an event to the database and then send an email to all the subscribers after adding event. I want to do the sending email task async, i followed some blog post and come up with this. from asgiref.sync import sync_to_async import asyncio This is the add event view @login_required(login_url='/login/') async def add_event_view(request): if request.method == 'POST': title = request.POST.get('title') description = request.POST.get('editor') menu = request.POST.get('menu') tags = request.POST.get('tags') banner = request.FILES.get('banner') data = request.FILES.get('data', None) organised_by = request.POST.get('organised_by', None) sponsored_by = request.POST.get('sponsored_by', None) event_date = request.POST.get('event_date', None) uploaded_at = request.POST.get('uploaded_at') Event.objects.create(user_id=request.user, event_title=title, event_description=description, event_category=menu, event_tags=tags, event_banner=banner, event_data=data, organised_by=organised_by, sponsored_by=sponsored_by, event_date=event_date, uploaded_at=uploaded_at) await sync_to_async(send_email(title)) return redirect(etab_view) This is the email sending function async def send_email(title): event = Event.objects.get(event_title=title) content = render_to_string("email.html", {'et': event}) subs = Subscriber.objects.values_list('email_address', flat=True) email = EmailMultiAlternatives('Emagazine Update', content, settings.EMAIL_HOST_USER, list(subs)) email.attach_alternative(content, "text/html") email.fail_silenty = False email.send() I am getting the following error: The view EMAG_APP.views.add_event_view didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view. Can anyone help me out? -
how can in render specific column of uploaded excel file?
by this HTML code, the users can upload files. {% block content %} <form method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple="multiple" /> <p class="container" style="margin-top: 10px"> <input type="submit" value="upload" class="btn btn-primary" /> </p> </form> {% endblock%} and in the views.py I am trying to get the uploaded file. views.py: def MyView(request): if method == "POST": file = request.FILES.get('files', False) #get the file if file: with open('uploads/files/'+file.name, 'wb+') as destination: #create file path for line in file.chunks(): destination.write(line) #save file data else: return render(request, 'template.html') how can I extract the specific column of uploaded excel and render it to another template? and i want to delete the uploaded file after 1 day. -
How should I add WSGIPython path in VirtualHost for Windows server?
I am trying to add WSGIPythonPath in VirtualHost but it's throwing me an error: Syntax error on line 549 of /etc/httpd/conf/httpd.conf: WSGIPythonPath cannot occur within section I tried to resolve it by following: Where should WSGIPythonPath point in my virtualenv? But, on researching more, I found that WSGIDaemonProcess and WSGIProcessGroup are not supported on Windows according to Why WSGIDaemonProcess isn't available on Windows?. So, How should I add WSGIPythonPath and where so that I can host multiple Django site on my Apache24 server. Any help would be beneficial. Here is my httpd.conf file: LoadFile "c:/python37/python37.dll" LoadModule wsgi_module "c:/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/python37" WSGIPythonPath "E:/edukon/" Listen 7020 <VirtualHost *:7020> ServerName 000.000.000.000 # Django Project WSGIScriptAlias / "E:/edukon/edukon/wsgi.py" <Directory "E:/edukon/edukon"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "E:/edukon/static/" <Directory "E:/edukon/static/"> Require all granted </Directory> Alias /media "E:/edukon/media/" <Directory "E:/edukon/media/"> Require all granted </Directory> </VirtualHost> -
Django ForeignKeyField assign one field with only one another field
I'm trying to create model TravelAgentDocumentType which consists of two ForeignKey's i.e travel_agent and document_type the plan is to have one travel agent can have only one document type, below is my models class TravelAgentDocument(BaseModel): travel_agent = models.ForeignKey(TravelAgent, null=True, on_delete=models.CASCADE) document_type = models.ForeignKey( DocumentType, on_delete=models.SET_NULL, null=True ) TravelAgent model is class TravelAgent(BaseModel): name = models.CharField( max_length=100, unique=True, validators=[validate_travel_agent_name] ) office_location = models.CharField( max_length=100, validators=[validate_location], ) office_land_line_number = LandLineNumberField(blank=True) slug = models.SlugField( unique=True, blank=True) office_phone_number = PhoneNumberField(unique=True) and DocumentType model is class DocumentType(BaseModel): name = models.CharField( max_length=20, unique=True, validators=[validate_document_name] ) how can I assign one travel agent with only one document type? -
Django keeps adding "app" to MEDIA_URL in heroku even though DEBUG = True
This is a new error which was never present before when I had the app running on Heroku. However I am now using the Heroku Postgres SQL so that might causing the issue. Anyways, I have my MEDIA_URL and MEDIA_ROOT set as such STATIC_ROOT = os.path.join(BASE_DIR, "portfoliosite", "staticfiles") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "portfoliosite", "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') THis works fine on my local server. However in production mode, Django keeps adding "app/" to the start of MEDIA_URL. Does anyone know what could be happening here? Here is the 404 error Request Method: GET Request URL: https://www.remosingh.ca/media/images/newlogo_1_TlcOlPh.png Raised by: django.views.static.serve “/app/media/images/newlogo_1_TlcOlPh.png” does not exist -
'Package' object has no attribute 'reviews'
I am trying to build a list api where comments of the blog post are shown on same api but it generates following error. Got AttributeError when attempting to get a value for field reviews on serializer PackageDetailSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Package instance. Original exception text was: 'Package' object has no attribute 'reviews'. My models: class Package(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) featured = models.BooleanField(default=False) price = models.IntegerField() duration = models.IntegerField(default=5) discount = models.CharField(max_length=255, default="15% OFF") discounted_price = models.IntegerField(default=230) savings = models.IntegerField(default=230) special_discount = models.BooleanField(default=False) rating = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5)) ) image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) content =RichTextField() highlights = RichTextField() itinerary = RichTextField() image_1= models.ImageField(blank=True,null = True) image_2= models.ImageField(blank=True,null = True) image_3= models.ImageField(blank=True,null = True) date_created = models.DateField() def __str__(self): return self.package_name # def is_featured(self): # return self.featured class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='review') full_name = models.CharField(max_length=255) review = RichTextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Meta: ordering = ('created_at',) My view: class AllPackageDetailAPIView(RetrieveAPIView): queryset = Package.objects.all() serializer_class = PackageDetailSerializer My serializers: class ReviewSerializer(serializers.ModelSerializer): … -
Connect web framework to Azure Analysis Services
This is not a code question, more of suggestion type one. I am also new at this so keep your torches away. My company wants to create something more flexible then using BI tools like Tableau for our front-end, so we want to build our own web app. So my question here is which web framework would be good to use to connect to Azure Analysis service for data as we still want to keep our data models? I am currently looking into Django because, as I read, speed and security (which is really important) and I am familiar with Python, but is this way to go? Or something not Python based. -
I am trying to pass row value between 2 tables but somehow last jquery onclick is not working at all. What am i missing?
With this i was able to pass row value from one to other and hide the row i clicked $('.js-report-delete').unbind('click').click(function() { var report_num = $(this).closest('tr').find('.report_no').text(); var row = '<tr style = "background-color : #ed962b;"><td class="report_no">'+ report_num +'</td></tr>'; $('#report_delete').append(row); $(this).closest('tr').hide(); }); And after that i am trying undo it, when i click the row that recently added on the other table which will remove that row and unhide original row from the first table but somehow this query not working at all. What am i missing? $('#report_delete tr').not('thead tr').on('click',function() { var report_num = $(this).closest('tr').find('.report_no').text(); $(this).closest('tr').remove(); $('#report_out tr').not('thead tr').each(function() { if($(this).closest('tr').find('.report_no').text() == report_num) { $(this).closest('tr').show(); } }); }); -
Django Aws Ses email send issue b'Invalid MAIL FROM address provided'
In my settings.py i have a mail congiguration Like : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_PORT = os.getenv('EMAIL_PORT') //465 EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS') And in my code i am using like : connection = get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASSWORD, use_tls=settings.EMAIL_USE_TLS, ) print('11111111') print(connection) print('222222222') mail = send_mail('diditwork?', 'test message', settings.EMAIL_HOST_USER, [userObj.email], connection=connection) But in Result i am getting the error Like : File "/var/www/html/gelmeko/myenv/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 125, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/lib/python3.6/smtplib.py", line 867, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (501, b'Invalid MAIL FROM address provided', 'AKI**************') Can any one please help me related this ?? what i am doing wrong here i am sending the mail through AWS SES credentials. -
Crontab in django uploads last 10 every 3minutes
In my views, I have this to upload a table with a list of the last 10 Model.objects.all().order_by('-id)[:10] I'm trying to make a cronjob, so at every 3minutes, it adds 1 to the top and removes the last one, so to make the list continue to be 10 -
Django - SImple left join between 2 tables
I have been searching for LEFT JOIN of Django on Stackoverflow, however, most of solution are just too complicated. My models: class Voucher(models.Model): code = models.CharField(unique=True, max_length=255) delivery_type = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True, null=True) start_at = models.DateTimeField() end_at = models.DateTimeField() discount_type = models.CharField(max_length=255) discount_amount = models.FloatField(blank=True, null=True) class VoucherCustomer(models.Model): voucher_code = models.OneToOneField(Voucher, models.DO_NOTHING, db_column='voucher_code', primary_key=True) customer_id = models.IntegerField() times_used = models.BigIntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) This is what I tried: from django.db.models.sql.datastructures import Join #I thought this one is like from VoucherCustomer left join Voucher on VoucherCustomer.voucher_code = Voucher.code j=Join(VoucherCustomer, 'voucher_code', Voucher,"LEFT JOIN" ,'code', True) j.objects.filter(voucher_code ='SAIGONS247').values('code', 'delivery_type', 'description', 'times_used').values However, I got this result in the end: AttributeError: 'str' object has no attribute 'get_joining_columns' -
How do I move a local Postgres database to Heroku to make it public? After that how do I connect to the Heroku Postgres database from Django?
I am currently running a Django application on my local Postgres database. However, I would like to make it remote so that other group members can also read from the database. So how would I migrate my local Postgres database to a Heroku Postgres database? After that, how would I change settings.py in Django to connect to the Heroku Postgres remote database? Thank you! -
For Loop for Django Ajax Form Submission
Hi I have a for loop which creates multiple modal popups and its corresponding form inside the modal pop up. I am submitting the form via Ajax method so as to not have the page refresh. However i am facing the problem that if i have multiple forms only the first form gets submitted correctly. The subsequent forms will submit the first form's value. Can anyone help me i have been trying to solve this for a long time. Currently i have put my javascript in the for loop after the end form tag between{% for form,post in zipped %} and {% endfor %}. My thinking was that when the value {{post.pk}} changes i will listen in on a different form because i have used a unique form id formy{{post.pk}} as the selector in the javascript. However it is not working. My script is: <script> $('#formy{{post.pk}}').on("submit" , function(e){ e.preventDefault(); $.ajax({ type:"POST", data:{ tag:$('#tag').val(), author:$('#author').val(), file_name:$("#file_name").val(), file_path:$("#file_path").val(), unique_id:$("#key").val(), csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val(), }, success:function(){ alert("UPDATED!!!!"); } }); }); </script> My html code is : {% for form, post in zipped %} <tr> <td><img src={{post.file_path}} style="width: 300px;"></td> <td>{{post.tag}} {{post.pk}}</td> <td><button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal{{post.pk}}"> Edit Tag </button></td> <form id="formy{{post.pk}}"> {% csrf_token %} <div … -
Can we use multiple serializers for a single django post API?
I have implemented an API which accepts a set of inputs from serializers and validates them. I have to differentiate the set of inputs based on category which is included in the context of URL. currently I am validating the fields and making them mandatory based on the category. I want to know if we have multiple sets of serializers to differentiate them based on the category. -
How to set the id of an HTML element with Django variable?
Right now, I'm displaying a bunch of elements using data from a Python dictionary, which looks something like {"id", "content", "id2": "content2"}. I'm then passing that to an HTML template through Django, and running a for loop to create an element for every item in the dictionary. The problem is, I'm going to add other front-end features via javascript, that require each element created to have a unique id in HTML, which I want to be set to the key of the python dictionary (So the first element has id of 'id', second element has an id of 'id2'...) So, how do I set the id of the element to be the Django variable? I know it isn't the for loop's problem, since I can print out the id variable just fine. Python code objects = {"A1": "xxx", "B2": "yyy", "C3": "zzz"} return render(request, "website/index.html", { "objects": objects }) index.html {% for object, specs in objects.items %} <div class="status"> Chunk of irrelevant code here </div> {% endfor %} I want each div with class status to also have an id of "A1" or "B2" and so on, but I don't know how to assign this -
Permission denied: 'd:/upload/'
Error Page PermissionError at /insert [Errno 13] Permission denied: 'd:/upload/' Request Method: POST Request URL: http://localhost/insert Django Version: 2.1 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'd:/upload/' Exception Location: C:\Users\cocoa\PycharmProjects\myweb2\board\views.py in insert, line 25 Python Executable: C:\python study\myweb2\Scripts\python.exe Python Version: 3.8.5 insert part from django.views.decorators.csrf import csrf_exempt from django.shortcuts import redirect UPLOAD_DIR = 'd:/upload/' @csrf_exempt def insert(request): frame='' fsize=0 if 'file' in request.FILES: file=request.FILES['file'] fname=file._name with open('%s%s' % (UPLOAD_DIR, frame), 'wb') as fp: for chunk in file.chuncks(): fp.write(chunk) fsize=os.path.getsize(UPLOAD_DIR + fname) row = Board(writer=request.POST['writer'], title=request.POST['title'],content=request.POST['content'], filename=fname, filesize=fsize) row.save() return redirect('/') Perhaps django has no authority to access the 'upload' folder. Changed from security in upload folder to all permissions. Should this problem be solved in sql? Help me.... -
"Cannot resolve keyword 'created' into field" on new DRF list view
I made a new list view in my Django REST Framework app: class ColumnView(ListCreateAPIView): queryset = Column.objects.all() serializer_class = ColumnSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) When I try to access it, I get the following error: FieldError at /my/new/endpoint Cannot resolve keyword 'created' into field. Choices are: _order, fields, from, my, model There's no created field anywhere in sight - not in the ColumnSerializer, not in the Column Django model, nowhere. The stacktrace is really opaque, too - my app doesn't appear anywhere in it. What's going on? -
Connecting AWS RDS MySQL instance to Django application
So I have created a Django backend application and have just put on the finishing touches. Now I would like to make my app use an MySQL instance I have created with my AWS account. I have entered all the credentials into my setting.py file but I get a strange error. I'm not sure what I'm doing wrong as there is almost no documentation of how connect it and it is my first time doing it. Here is the error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on {AWS ENDPOINT} -
Validating Sum of InlineFormSet against Total in ParentModel
Let's assume I have a main model called Bill. There I have a field total_amount and a many-to-many relationship to the UserModel through an intermediate model, where the share of the total bill per User can be recorded. See the following snippets. Finally, the sum of the share of the totall bill per User's shall equal the total_amount. I like to validate within the form, inlineform (or model) that the sum of the amounts in the Model BillDebitor equals the total_amount of the Bill Model. If anyhow possible this shall be evaluated within the form itself and raise a ValidationError if the amounts are not equal. Can somebody assist in how to solve this? I tried throgh custom clean methods, but for some reason neighter the parent form nor the inline formsets are available in the respective forms. models.py class Bill(modles.Model): total_amount = models.Decimalfield() debtor = models.ManyToManyField(settings.AUTH_USER_MODEL, through='BillDebtor') class BillDebtor(models.Model): bill = models.ForeignKey(Bill) debtor = models.ForeignKey(settings.AUTH_USER_MODEL) amount = models.Decimalfield() forms.py class BaseBillForm(models.ModelForm): class Meta: model = Bill fields = ['total_amount'] class DebtorForm(models.ModelForm): class Meta: model = BillDebtor fields = ['debtor', 'amount'] class DebtorFormSet(models.BaseInlineFormSet): pass DebtorInlineFormSet = inlineformset_factory(Bill, BillDebtor, form=BaseBillForm, formset=DebtorFormSet, extra=2) view.py class SplitBillView(CreateView): model = Bill from_class = BaseBillForm … -
Python DJANGO 3.0 issue with passing arguments to @register.simple_tag
I have the following tree: apps templatetags pyos.py templates index.html In pyos.py I have the following code: import os from django import template register = template.Library() @register.simple_tag def listdir(path): d = os.listdir return d(path) def test(): pass Then in index.html, inside templates I have the following already working: {%extends 'principal.html'%} <div> {%load pyos%} {%listdir 'C:/'%} </div> I need to pass some static path as argument, is there any way to do something like that? <div> {%load pyos%} {%load static%} {%listdir {%static 'img/image.png'%}%} </div> -
Django: Annotate table with field across a M2M mapping to another table
I want to get competition.name from a list of submissions. In my setup, competitions and teams share a M2M relationship (with an associated competition-team object. Each competition-team pair can submit any number of submissions. I now have a dashboard page which I am trying to create a table of all submissions by the team accompanied by the respective competition's name. The output should look like: | Submission Name | Submission Date etc. | Competition Name | | Sub01 | 2020-12-30 2000 | Competition01 | I have trouble retrieving the competition name from the submissions. Here are my models: class Competition(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) class CompetitionTeam(models.Model): competition_id = models.ForeignKey('Competition', on_delete=models.CASCADE, to_field='id', db_column='competition_id') team_id = models.ForeignKey('Team', on_delete=models.CASCADE, to_field='id', null=True, db_column='team_id') class CompetitionSubmission(models.Model): competitionteam_id = models.ForeignKey(CompetitionTeam, on_delete=models.CASCADE, db_column='competitionteam_id') I wish to annotate a set of submissions with their respective competition names. I tried with: submissions.annotate(competition_name=Subquery(Competition.objects.filter(id=Subquery(CompetitionTeam.objects.get(id=OuterRef('competitionteam_id')).competition_id)).values('name'))) "ValueError: This queryset contains a reference to an outer query and may only be used in a subquery." I also tested with the following command: CompetitionSubmission.objects.prefetch_related('competitionteam_id__competition_id') It runs but the command seems to do nothing. I will update this post with other methods I try. Thank you. -
GET API with Django code working in Postman but not in React JS
The GET API works in Postman with the correct JSON response, but doesn't work in React when I try to show the JSON response on the webpage. I also don't know how to handle this CORS error: from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I tried many ways, but I ended up getting some sort of error every time so for now, I just used a temporary solution, which is a Chrome extension, to get rid of this error for now, but I have to solve it eventually. Here is my code in views.py: class get_events_1st_alg(APIView): def get(self, request, format=None): import pandas as pd import numpy as np import psycopg2 import sqlalchemy from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics import pairwise_distances import requests from sqlalchemy import create_engine engine = create_engine('postgresql://postgres:postgres@localhost/postgres') # pd.read_sql_query('''SELECT * FROM arts_user_interaction LIMIT 5;''', engine) events = pd.read_sql_query('''SELECT * FROM arts_event;''', engine) Ratings = pd.read_sql_query('''SELECT * FROM arts_user_interaction;''', engine) Mean = Ratings.groupby(by="User_ID", as_index = False)['User Rating'].mean() Rating_avg = pd.merge(Ratings, Mean, on = "User_ID") Rating_avg['adg_rating']=Rating_avg['User Rating_x']-Rating_avg['User Rating_y'] check = pd.pivot_table(Rating_avg,values='User Rating_x',index='User_ID',columns='Event_ID') final = pd.pivot_table(Rating_avg,values='adg_rating',index='User_ID',columns='Event_ID') final_event = final.fillna(final.mean(axis=0)) final_user = final.apply(lambda row: row.fillna(row.mean()), axis=1) cosine = cosine_similarity(final_event) np.fill_diagonal(cosine, 0 … -
Why do you test a model's field label name and when do you use the label name?
This article recommends testing your model's fields label name. Why would you test a field's label name when it is already set by Django? When in your code do you use the label name for a field?