Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use javascript to remove a property defined by django?
I am trying to make password fields required only if a checkbox is checked. Initially, the check box is checked so the fields are defined required in Django: forms.py class SampleForm(forms.ModelForm): check = forms.BooleanField(required=False) password1 = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model=MyModel def __init__(self, *args, **kwargs): super(SampleForm,self).__init__(*args, **kwargs) self.fields['check'].widget.attrs.update({'onclick':"hidePass()",'id':"check"}) self.fields['password1'].widget.attrs.update({'id':"password1"}) self.fields['password2'].widget.attrs.update({'id':"password2"}) I tried the following: <script> function hidePass() { var checkBox = document.getElementById("check"); var password1 = document.getElementById("password1"); var password2 = document.getElementById("password2"); if (checkBox.checked == true){ password1.disabled = false; password1.required = true; password2.disabled = false; password2.required = true; } else { password1.disabled = true; password1.required = false; password2.disabled = true; password2.required = false; } } </script> but it didn't work. It could disable the fields but they were still required. I tried to replace password1.required = false; by: password1.removeAttribute("required"); bu I got the same result. -
Django - Celery send task to remote rabbitmq broker
I want to separate my celery server from the Django server. I tried to install rabbitmq and celery on a different server and tried to send tasks from my django server.I am not receiving any tasks into the remote celery server. I have done some research, but didn't get any working answer. How can i send my tasks to the remote rabbitmq server? The celery server has all the code base and i'm able to connect to remote rabbitmq server from my local as well.i configured celery in celery.py file, and i am able to connect to the remote rabbit mq server from localhost. i push celery task like this def dummy_task(request): dummy_celery_task.delay() return JsonResponse({'success': True}) @shared_task def dummy_celery_task(): print("celery task recieved")``` -
How to upload multiple files with django rest api?
I'm trying to upload multiple images with django rest api. I followed the following approach. But when I select one or more files and try to send them to the server as form data, I get the following error message: AttributeError at /api/photo/ 'bytes' object has no attribute 'name' Model: class Photo(models.Model): image = models.ImageField(upload_to='audio_stories/') Serializer: class FileListSerializer ( serializers.Serializer ) : image = serializers.ListField( child=serializers.FileField( max_length=100000, allow_empty_file=False, use_url=False ) ) def create(self, validated_data): image=validated_data.pop('image') for img in image: photo=Photo.objects.create(image=img,**validated_data) return photo class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo View: class PhotoViewSet(viewsets.ModelViewSet): serializer_class = FileListSerializer parser_classes = (MultiPartParser, FormParser,) queryset=Photo.objects.all() URL router.register('api/photo', PhotoViewSet, 'photocreate') I dont know how to approach the error, as i have nothing in my code that relates to "name"? -
Django: Problems collecting static files
I have: STATIC_URL = "/statics/" STATIC_ROOT = os.path.join(BASE_DIR, "static") And I have another app that has a static folder, so I collect static files from all the apps with python manage.py collectstatic, this creates a folder named statics with admin, frontend, rest_framework folders. Each of these are the apps, but right now I need the frontend. Inside the frontend folder, there's a main.js file which is the react js app. So I have a frontend app, inside the templates I have my frontend folder and inside the folder I have index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"></div> {% load static %} <script src="{% static 'frontend/main.js'%}"></script> </body> </html> But the problem is that I get 404 not found, what could be the problem?? The URL for the main.js file as I can see is - http://192.168.0.52:8000/statics/frontend/main.js Although in the HTML you can see {% static 'frontend/main.js'%}, I used this before to collect the file inside the app, but now I have used collectstatic, so I have the main statics folder and should I get the files from it? or what? -
Getting django signals to work between applications
I have a Django app called receipt_printer which should be printing an order when it is received using a signal. There are two apps here called: Orders and receipt_printer. However, whenever an order is processed and fully charged I can't get the signals to work. The example below just prints out something to the console for simplicity. If I do everything inside the models.py in the Orders app it works fine. receipt_printer/apps.py from django.apps import AppConfig class ReceiptPrinterConfig(AppConfig): name = 'receipt_printer' def ready(self): from . import signals receipt_printer/signals.py from django.db import models from saleor.order.models import Order from django.db.models.signals import post_save def order_fully_paid_signal(sender, instance, created, **kwargs): if instance.get_payment_status() == "fully-charged": print("This signal is working for fully paid order") else: print("This signal won't working for fully paid order") post_save.connect(order_fully_paid_signal, sender=Order) receipt_printer/init.py default_app_config = 'receipt_printer.apps.ReceiptPrinterConfig' -
How to send and receive email in django from and to
am having a problem in sending and receiving emails from a Django def home(request): if request.method == "POST": name = request.POST['name'] l_name = request.POST['l-name'] email = request.POST['email'] message = request.POST['message'] #send an email send_mail( name, #subject message, #message body email, #from email ['myemail@domain.com'], #To email ) return render(request,'home.html',{'name':name}) else: return render(request,'home.html',{}) I have used my gmail email(isme@gmail.com) to set up EMAIL_HOST_USER and every thing works fine, but the issue come when a from email(means someones email put in the form ) has @gmail.com extension the email i receive BOTH TO and FROM IS MY Email address(isme@gmail.com) ,However when the from email has other extensions like @domain.co or .com both FROM AND TO appears as expected. what am i missing here help please. -
Not sure how to specify the app for Celery
Below is the structure for my app: - anp_tasks - __init__.py - celery.py - tasks.py - platform - webapp - app [entire django project] - manage.py - Dockerfile - requirements.txt - docker-compose.yml Dockerfile contents FROM python:latest LABEL maintainer="Akrogoniaios Technologies Corp." ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install --upgrade pip RUN ln -s /usr/bin/pip3 /usr/bin/pip RUN apt-get update && apt-get install -y gcc libjpeg-dev libc-dev musl-dev zlib1g zlib1g-dev apt-utils RUN pip install -r ./requirements.txt #copy the app files and proceed RUN mkdir /app WORKDIR /app COPY ./webapp /app RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static requirements.txt Django>=3.1 djangorestframework>=3.12 psycopg2==2.8.3 celery>=5.0.2 init.py inside anp_tasks from __future__ import absolute_import, unicode_literals __all__ = ['anp_tasks'] contents of celery.py from celery import Celery app = Celery('anp_tasks', broker='amqp://', backend='rpc://', include=['anp_tasks.tasks']) app.conf.update( result_expires=3600, ) if __name__ == '__main__': app.start() Contents of tasks.py inside *anp_tasks from .celery import app @app.task def print_hello(): print ("hello there") Contents of docker-compose.yml specific to celery broker: image: rabbitmq:latest env_file: - ./platform/anp_rabbitmq.env volumes: - "./rabbitmq:/data" worker: build: context: ./platform command: "celery -A .\anp_tasks worker -l INFO " environment: - DEBUG=1 depends_on: - broker However, when I run docker-compose up, it throws the below error. worker_1 | Usage: celery [OPTIONS] COMMAND [ARGS]... … -
Docx to pdf using pandoc in python
So I a quite new to Python so it may be a silly question but i can't seem to find the solution anywhere. I have a django site I am running it locally on my machine just for development. on the site I want to convert a docx file to pdf. I want to use pandoc to do this. I know there are other methods such as online apis or the python modules such as "docx2pdf". However i want to use pandoc for deployment reasons. I have installed pandoc on my terminal using brew install pandoc. so it should b installed correctly. In my django project i am doing: import pypandoc import docx def making_a_doc_function(request): doc = docx.Document() doc.add_heading("MY DOCUMENT") doc.save('thisisdoc.docx') pypandoc.convert_file('thisisdoc.docx', 'docx', outputfile="thisisdoc.pdf") pdf = open('thisisdoc.pdf', 'rb') response = FileResponse(pdf) return response The docx file get created no problem but it not pdf has been created. I am getting an error that says: Pandoc died with exitcode "4" during conversion: b'cannot produce pdf output from docx\n' Does anyone have any ideas? -
How to add ruby with bundler to a heroku python app?
I am trying to add a buildpack for a django app, but I get this error after the server starts: bin/start-nginx: line 37: bundle: command not found I've tried the following, but the error persisted: heroku config:add PATH=bin:vendor/bundle/1.8/bin:/usr/local/bin:/usr/bin:/bin GEM_PATH=vendor/bundle/1.8 How to add this bundler and the ruby Gem file to my python app in heroku? -
create manytomany in the same form like the main model
I have the following models: class Topping(models.Model): name = models.CharField(max_length=50) class ToppingAmount(models.Model): topping = models.ForeignKey(Topping, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=6, decimal_places=2) class Pizza(models.Model): name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) Now I want that an user can create a pizza, with selecting the Topping that already exist and giving the amount manually (not selecting). Pizza -> Input: name ToppingAmount1 -> Select: topping from database Input: manually amount of the selected topping ToppingAmount2 -> Select: topping from database Input: manually amount of the selected topping ToppingAmountN -> Select: topping from database Input: manually amount of the selected topping Is it anyhow possible to create a form of the Pizza with selecting the Topping and manually the amount so that its automatically created if not already saved in the database? How can I make a many to many field in that way that it can also create new ToppingAmounts instead of selecting them which already exist? -
Django RawQuerySet attribute for sum
I have created a result that displays the default between two dates, but I don’t understand how I can display the result of the total price between two dates. I tried using agrregate (Sum) but got the error: RawQuerySet object has no aggregate attribute. I have no idea what else can be used for this views.py def service(request): if request.method == 'POST': fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') searchresult = Service.objects.raw( 'select id, date_of_treatment, price from service_db where date_of_treatment between "'+fromdate+'" and "'+todate + '"') context = {'service': searchresult} return render(request, 'main/service.html', context) else: service = Service.objects.all().order_by('date_of_treatment') myFilter = ServiceFilter() context = {'service': service} return render(request, 'main/service.html', context) HTML <form method="POST"> {% csrf_token %} <strong> <p>от : <input type="date" name="fromdate" /></p> <p>до :<input type="date" name="todate" /></p> <p><input type="submit" value="применить" /></p> </strong> <table class="table"> <tr> <th>дата</th> <th>доктор</th> <th>пациент</th> <th>услуга</th> <th>цена</th> <th>изменить</th> <th>удалить</th> </tr> {{myFilter.form}} <tr> {% for works in service %} <td>{{works.date_of_treatment}}</td> <td>{{works.attending_doctor}}</td> <td>{{works.patient}}</td> <td>{{works.treatment}}</td> <td>{{works.price}}</td> <td> <a class="btn btn-sm btn-info" href="{% url 'update_service' works.id %}" >изменить</a > </td> <td> <a class="btn btn-sm btn-danger" href="{% url 'delete_service' works.id %}" >удалить</a > </td> </tr> {% endfor %} </table> </form> <td> <strong>итого:</strong> <h3>{{total_price_service}}</h3> </td> -
CSRF token not validated via Fetch (Django)
i'm making this post because i couldn't solve my problem following similar posts/solutions. I'm trying to send data via POST using fetch in javascript. And for some reason the csrf token is not being validated. Here are the codes for my project. HTML <div class="post-edit" id="post-edit-{{ post.id }}"> <form method="post" id="edit-form-{{ post.id }}"> <div class="form-group"> <p>Edit this post:</p> <input type="hidden" id="post_id-{{ post.id }}" value="{{ post.id }}"> <textarea class="form-control" id="editbody-{{ post.id }}">{{ post.body }}</textarea> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Save"> </div> </form> </div> JavaScript function function getCookie(name) { if (!document.cookie) { return null; } const token = document.cookie.split(';') .map(c => c.trim()) .filter(c => c.startsWith(name + '=')); if (token.length === 0) { return null; } return decodeURIComponent(token[0].split('=')[1]); } function post_edit(id) { event.preventDefault(); // Hide all previous visible divs of post-edit reset_views(); // Show the edit textarea and hyde the post_view document.querySelector(`#post-edit-${id}`).style.display = 'block'; document.querySelector(`#post-comment-${id}`).style.display = 'none'; document.querySelector(`#post-view-${id}`).style.display = 'none'; document.addEventListener('DOMContentLoaded', function() { document.querySelector(`#edit-form-${id}`).onsubmit = function () { event.preventDefault(); const editbody = document.querySelector(`#editbody-${id}`).value; const post_id = document.querySelector(`#post_id-${id}`).value; // VER PORQUE NO FUNCIONA ESTA MIERDA fetch('/edit', { credentials: 'include', method: 'POST', mode: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') }, body: JSON.stringify({ editbody: editbody, post_id: post_id }) }) .then(response => … -
Django - How to show image, after uploading file (.jpg) directly to MEDIA_URL folder
just to clarify my question: Let say I have a csv file to upload my list of products to the database. How I can tell Django to look at the MEDIA_URL folder. If the name of the image file is equal to the product name, then use that image file for the product. Thanks in advance -
Adding a Like button to Django Blog Project not working properly
In my Blog Django Project I am trying to create a Like Feature, but currently facing the below error: Reverse for 'post-detail' with no arguments not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/$'] What should I do to prevent this error and to return back to the same Post-detail page after pressing the like button? Here is the urls.py path('blog/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('blogs/like', like_post, name='like-post'), Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views: class PostListView(ListView): model = Post template_name = "blog/post_list.html" # <app>/<model>_<viewtype>.html ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 1 class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_create(user=user,post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return redirect('blog:post-detail') <------------ Error Showing from Here Here is the template: <form action="{% url 'blog:like-post' %}" method="POST"> {% csrf_token %} … -
FileNotFounderror [Errorno 2] : No such file or Directory 'C:/Users/dhruven/Desktop/Publish/DiabetesPred/myapp/model.pkl'
I'm getting this error while pushing my app to "heroku" server, I am Using Django Version 3 -
WAYS TO PROTECT THE SECRET_KEY? [closed]
How to protect the SECRET_KEY in settings.py ( Ways to protect the SECRET_KEY ) ? -
How to use both Django Auth and DRF Token auth?
I am building a Django web app where I want two things: Use Django's in-built User model for Django's Admin app usage (store owner) Use DRF's Token Auth on a custom User model that I will be naming "Customer" (store customer) How do I keep both the Authentication systems for the above stated purposes. From what I have read every one asks to override the User model but I don't want to do that. Instead I want to keep both. What strategy should I take up? PS: It might be me, but I am not able to find any solution for this in DRF's Documentation. If there is please do point me in the right direction. -
Django POST request 403 response status
i am using django rest framework to make POST request , this is the view : @api_view(['GET', 'POST', 'DELETE']) @csrf_exempt def tutorial_list(request): if request.method == 'POST': tutorial_data = JSONParser().parse(request) tutorial_serializer = TutorialSerializer(data=tutorial_data) if tutorial_serializer.is_valid(): tutorial_serializer.save() return JsonResponse(tutorial_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) i am getting this response : { "servlet": "Stapler", "message": "No valid crumb was included in the request", "url": "/api/tutorials", "status": "403" } i am using postgresql database -
get how many times a query is called in Graphene?
I'm trying to build something like a visits counter in a profile. Let's say how much time a profile is visited in total and in the last 30 days. my query looks something like this: class ProfileQuery(object): profile = graphene.relay.Node.Field(ProfileNode) it's a simple graphene relay query and I'm not quite sure how to proceed. Any advice? -
External Python Scripts and Django Virtual Env
I run an external script from my Django app using subprocess this way: class ExecutePythonFileView(View): def get(self, request): # Execute script script_path = os.path.join(settings.BASE_DIR, '/Code/zenet/zenet/workers/stats_scraper.py') subprocess.call(['python', script_path]) # Return response return HttpResponse("Executed!") I would need to execute it through the Django virtual environnement though, how could I proceed? -
read and edit a csv file in django
i am trying to read and edit some cvs file in my models my model: class chart(models.Model): name = models.CharField(max_length=10) char = models.FileField(null=True, blank=True) the csv file are in char filed now in views.py: def home(request): context ={ } return render(request, 'home.html', context) how I can read csv file in views and open with pandas or matplotlib? -
Django cannot update second field with signal
When i add client to Client table, it's added automatically with signals to ClientsBalance. But the company field on ClientsBalance table is not updated to the current company (company=user.company), i would like that this field contain the current user company. class Company(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=64) class Client(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=256) class ClientsBalance(models.Model): company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.CASCADE) client = models.OneToOneField('Client', on_delete=models.CASCADE,related_name='Client') def create_client(sender, **kwargs): if kwargs['created']: client = ClientsBalance.objects.create(client=kwargs['instance']) post_save.connect(create_client, sender=Client) -
Django download of pdf file redirects to login page
I try to generate and download the generated file but once the file is generated I'm redirected to the login page. The CBV looks like: class BilanStudentGeneratePdfView(LoginRequiredMixin, generic.View): def get(self, request, pk): # https://www.bedjango.com/blog/how-generate-pdf-django-weasyprint/ bilan_student = BilanStudent.objects.get(pk=pk) html_string = render_to_string('bilan/bilan_student_pdf.html', {'bilan_student': bilan_student}) html = HTML(string=html_string) filename = '{}/bilan/bilan_{}_Student_{}.pdf'.format(MEDIA_ROOT, bilan_student.bilan.pk, bilan_student.student.pk) html.write_pdf(target=filename) response = FileResponse(filename=filename, as_attachment=True, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename={}'.format(filename) return response The file is generated but what I see is that I have a redirect to my splash page which is the login page and I don't know why: [11/Nov/2020 17:05:11] "GET /bilan/pdf/student/71/ HTTP/1.1" 200 0 [11/Nov/2020 17:05:11] "GET /bilan/pdf/student/71/ HTTP/1.1" 302 0 [11/Nov/2020 17:05:11] "GET /splash/?next=/bilan/pdf/student/71/ HTTP/1.1" 200 3270 Any help will be appreciated. -
QuerySet django . How to write a function correctly to make tests pass
how returns in tree_downwards the root organization with the requested org_id and all its children at any nesting level and returns in tree_upwords the root organization with the requested org_id and all its parents at any nesting level to make tests pas??? I will only be able to return either the parents or the organization itself models.py class OrganizationQuerySet(models.QuerySet): def tree_downwards(self, root_id): """ :type root_org_id: int """ return self.filter(???) def tree_upwards(self, child_id): """ :type child_org_id: int """ return self.filter(???) class Organization(models.Model): objects = OrganizationQuerySet.as_manager() name = models.CharField(max_length=1000, blank=False, null=False) parent = models.ForeignKey( "self", null=True, blank=True, on_delete=models.PROTECT ) class Meta: ordering = ["name"] verbose_name = "organization" def __str__(self): return self.name tests.py def test_get_tree_downwards_cluster(make_organization): org_1 = make_organization() org_2 = make_organization(parent=org_1) children = Organization.objects.tree_downwards(org_1.id) assert org_1 in children assert org_2 in children def test_get_parents_chain(make_organization): org_1 = make_organization() org_2 = make_organization(parent=org_1) org_3 = make_organization(parent=org_2) parents = Organization.objects.tree_upwards(org_3.id) assert org_1 in parents assert org_2 in parents assert org_3 in parents -
Django Connecting To Quickbooks Online Via Backend
I'm trying to push data into Quickbooks online from my backend django app but Oauth is pretty tough for me to understand. I'm attempting to use requests-oauth and the backend application workflow. https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow I am able to generate a token but i'm getting a 401 back when I try to use it. I can't tell whether the code that is being returned is bad because the code that I generate via the QBO developer playground also does not work for my request. The request does work in the developer playground. Can anyone show me an example of connecting to quickbooks via a backend workflow. It doesn't seem to make sense to have a user "authenticate" with this being a backend service. Here's my attempt: class QuickbooksOnlineService: def __init__(self): self.integration_credential = IntegrationCredential.objects.get( agent_company_id=1, partner=IntegrationCredential.QUICKBOOKS ) self.auth_client = AuthClient( client_id=self.integration_credential.client_id, client_secret=self.integration_credential.client_secret, environment='sandbox', redirect_uri='https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl' ) def build_client(self): auth_client = self.auth_client url = auth_client.get_authorization_url([Scopes.ACCOUNTING]) # This URL takes me to the devleoper playground and lets me generate a token and make a successful request in the developer play print(url) auth = HTTPBasicAuth(self.integration_credential.client_id, self.integration_credential.client_secret) client = BackendApplicationClient(client_id=self.integration_credential.client_id, scope=['com.intuit.quickbooks.accounting']) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url='https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer', auth=auth ) print(token) import requests url = "https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365154174550/companyinfo/4620816365154174550" headers = { …