Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PipeDrive - how to avoid loops when using WebHooks?
I'm working with PipeDrive API and I've started to use their webhooks. The problem is that it cause loops. Simple example: There is a model Deal which has two methods - Deal.sync(), Deal.backsync() Deal.sync() sends updated or created Deal object to the PipeDrive Deal.backsync() fetches Deal object from the PipeDrive But the problem is that when I call sync, the Deal object is sent to the PipeDrive which invokes webhook so my server receives this webhook and automatically invokes Deal.backsync() etc. I have some ideas but maybe there is some elegant way I don't know. Ideally, for example sync would send some uuid which would be sent in webhook so I know it was caused by sync. Do you know how to make this work? -
Send Email html with iterated model data
I am trying to set up an email alert that sends once a week. I intend to set a cronjob for a this function so it will do so. import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(): try: msg = MIMEMultipart('alternative') msg['From'] = "<email>" msg['To'] = "<email>" msg['Subject'] = "sub" html = """ <html> <head></head> <body> <p> hello</p> </body> </html> """ part1 = MIMEText(html, 'html') msg.attach(part1) mail = smtplib.SMTP("smtp.email.client", 587, timeout=20) mail.starttls() recepient = ['<email>'] mail.login('<email>', '<password>') mail.sendmail("fromemail@domain.com", recepient, msg.as_string()) mail.quit() except Exception as e: raise e I am trying to have the html mirror one of my templates in my project, and in this template I am iterating over model data to create charts. <body> <h1>4.2.0 Test Plan</h1> {% for x in testrail %} <h3>{{x.component}}</h3> <table class="tg"> <tr> <th class="tg-baqh"></th> <th class="tg-0lax">#</th> </tr> <tr> <td class="tg-hmp3">Total</td> <td class="tg-hmp3">{{x.total_count}}</td> </tr> <tr> <td class="tg-hmp3">Passed</td> <td class="tg-hmp3">{{x.passed_count}}</td> </tr> <tr> <td class="tg-0lax">Untested</td> <td class="tg-0lax">{{x.untested_count}}</td> </tr> <tr> <td class="tg-0lax">Failed</td> <td class="tg-0lax">{{x.failed_count}}</td> </tr> <tr> <td class="tg-0lax">Reviewed</td> <td class="tg-0lax">{{x.reviewed_count}}</td> </tr> <tr> <td class="tg-0lax">Harness Failures</td> <td class="tg-0lax">{{x.test_harness_issue_count}}</td> </tr> <tr> <td class="tg-0lax">Product Failures</td> <td class="tg-0lax">{{x.bug_failure_count}}</td> </tr> <tr> <td class="tg-0lax">Coverage %</td> <td class="tg-0lax">{{x.coverage_percentage}}%</td> </tr> <tr> <td class="tg-0lax">Passed %</td> <td class="tg-0lax">{{x.passed_percentage}}%</td> </tr> <tr> <td class="tg-0lax">Reviewed %</td> … -
Success message in generic views doesn't work
I am using Django generic views to create a success message, I searched a bit in stack overflow and seems like similar solution is not working in my case. views.py class PostCreateView(CreateView): model = BlogPost template_name = 'blogs/blog-form.html' fields = [ 'title', 'content', 'image' ] success_message = 'Post added successfully!' and here is the template wherein the messages should pop up. <div class="wrapper"> {% if messages %} {% for message in messages %} <div class="alert alert-success my-3"> {{ message }} </div> {% endfor %} {% endif %} <a href="{% url 'blog:blog_update' object.slug %}" class="btn btn-success btn-sm">Update</a> <a href="{% url 'blog:blog_delete' object.slug %}" class="btn btn-danger btn-sm">Delete</a> <br><br> <img src="{{ object.image.url }}" class="image_in_list" alt=""> <h2 class="display-4">{{ object.title }}</h2> <p>{{ object.content }}</p> </div> any help would be appreciated so much, thanks. -
CKeditor incorrect display in Django admin panel
I've just installed CKEditor 5.6.1 and it works fine on Django 2.2 website. But in admin panel it shows incorrectly. The field label overlap textarea. I've attached the screenshot. CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', ... 'height': 360, 'width': '100%', Anybody knows how to prevent this? admin.py from ckeditor_uploader.widgets import CKEditorUploadingWidget class PostAdminForm(forms.ModelForm): description = forms.CharField(widget=CKEditorUploadingWidget()) class Meta: model = Post fields = '__all__' class PostAdmin(admin.ModelAdmin): form = PostAdminForm https://i.imgur.com/DDDEHlx.png -
Is it a bad idea to save POST information without using django Forms?
I am currently developing a student survey app. when the student clicks the submit button on the form, activate the view with the following code: for key, value in request.POST.items(): if key != 'csrfmiddlewaretoken': # I don't want to save the token info item = Item.objects.get(pk=key) # I get the question(item) I want to save if item == None: return render(request, "survey/error.html") Answer.objects.create(item= item, answer=value, user = request.user) Since all the fields in the form are obligatory, I use the required value attribute in html. This code works and stores the information in the DB. However, I am concerned that because it is very "manual", it may generate errors when it is in production. However I do not know how to use django forms, so I would like to avoid having to learn it, if it is not necessary. -
How can I sort serializer data on serializer MethodField while using ListViewSet?
I have a class say GetStudentDetails and I am using a serializer having serializer MethodField say postal_address and I want my result to be sorted on based of this field I ahve tried adding ordering = ('postal_address',) and since it is not a model field, I encounter error. class GetStudentDetails(viewsets.GenericViewSet, mixins.ListModelMixin): model = Student queyset = Student.objects.all() serializer_class = StudentCreateSerializer filter_backends = (filters.OrderingFilter,filters.DjangoFilterBackend,) class StudentCreateSerializer(serializers.ModelSerializer): postal_address = serializers.SerializerMethodField() def get_postal_address(self, obj): return obj.city+obj.state class Meta: model = Vehicle fields = ('name','city','state',postal_address') class Student(models.Model): name=models.CharField(max_length=45) city=models.CharField(max_length=10) state=models.CharField(max_length=10) def __str__(self): return name actual result: [{"name":test", "city":"abc", "state":"def", "postal_code":"abcdef" }, { "name":"test2", "city":"aa", "state":"bb", "postal_code":"aabb" }] expected result: [{ "name":"test2", "city":"aa", "state":"bb", "postal_code":"aabb" }, {"name":test", "city":"abc", "state":"def", "postal_code":"abcdef" }] -
request.session[] variables allowed size
Im trying to write images on my disk from a request.FILES.getlist('file') but in the proccess i show the user three pages, every page i used to full diferent information in my second page i use a <input type="file" id="file" name="file" accept="image/*" multiple> that allow the user upload images but the save on disk is done until the tird page so i pass the images to a session variable to use it until the tird page, and works fine every time that the imeges size are below the 2.5 MB, but whe one or more images in the request are bigger than that gives me this error I/O operation on closed file and to write the images i try with this: #to save the request.FILES in a session variable on page two request.session['imgfiles'] = request.FILES.getlist('file') #now to write the images on disk on page 3 images = request.session.get('imgfiles') direc = '\\some\\directory\\' #using PIL for img in images: i = Image.open(img) i.save(direc+str(img)) #or for img in images: with open(direc + str(img), 'wb') as dest: for chunk in img.chunks(): dest.write(chunk) #or dest = open(direc + str(img), 'wb+') for chunk in img.chunks(): dest.write(chunk) dest.close() The three ways works when images are below than 2.5 … -
How upload files to AWS only with a few models filtered in django models?
I have this code in a models.py of my Django app. I got the default file storage saving my Files on the remote server. But it store ALL the File objects/models to the remote server. Is there any option to set the upload on the remote server AWS only in the models that I want? class Attachment(models.Model): file = models.FileField(upload_to=log_att_path) log_sender = models.ForeignKey( LogSender, related_name='attachments', on_delete=models.CASCADE ) timestamp = models.DateTimeField(auto_now_add=True) attachment_url = models.TextField(default=False) ``` -
Server running on a loop and reloading the same file again and again
I am running a project in my virtualenv on Django but constantly getting this issue the error I get is Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. /Users/Saujan/Desktop/FinalProject/netscan/apps/core/ templatetags/general_info.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 23, 2019 - 15:48:31 Django version 2.2, using settings 'config.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. /Users/Saujan/Desktop/FinalProject/netscan/apps/core/ templatetags/general_info.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 23, 2019 - 15:48:33 Django version 2.2, using settings 'config.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. /Users/Saujan/Desktop/FinalProject/netscan/apps/core/ templatetags/general_info.py changed, reloading. (netscan_venv) Saujan:netscan Saujan$ -
JavaScript/jQuery downloading PDF file returned from Django view
I have a celery task that creates PDF files on the click of a button. When the button is clicked, the javascript side will keep checking until the task is done, and when it is, it will download the file. I figured some recursivity would do: $(".getPdf").on('click', function(event) { // Grab the clicked object ID and the filename stored on the data attributes var thisId = $(this).data('runid'); var filename = $(this).data('filename'); var taskID = "None"; var pdfStatus = "None"; // Run download function downloadPdf(filename, taskID, pdfStatus); function downloadPdf(filename, taskID, pdfStatus) { // Send a POST request to Django's RunsView with the Run ID, pdf filename, task ID and pdfStatus (if any) $.post({ url: "{% url 'runs' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", id: thisId, filename: filename, task_id: taskID, }, success: function(data) { // Split the returned string to separate the task ID [0] from the status [1] var taskID = data.split(";")[0]; var pdfStatus = data.split(";")[1]; // Convert the pdfStatus Python bools into JavaScript bools if (pdfStatus == "False") { pdfStatus = false; } else if (pdfStatus == "True") { pdfStatus = true; }; if (!pdfStatus) { console.log("Repeat function."); downloadPdf(filename, taskID, pdfStatus); } else { console.log("Download PDF"); window.open("data:application/pdf;base64," + data); … -
Django's NotImplementedError: aggregate() + distinct(fields) not implemented
I have quite simple models: class Profile(models.Model): name = models.CharField(max_length=100, unique=True) age = models.IntegerField(default=18) class Place(models.Model): name = models.CharField(max_length=100, blank=True, null=True) address = models.CharField(max_length=100, blank=True, null=True) class ProfilePlaceFeedback(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='feedback_set') place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='feedback_set') review = models.TextField(blank=True, null=True) rating = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) ProfilePlaceFeedback - is model to store each rating leaved by user's. And to count the rating for some place, I need to retrieve all last User feedbacks and sum up all rating values. Here're the code for retrieving all last feedbacks by each user: place.feedback_set.order_by('profile', '-timestamp').distinct('profile') But making querying: place.feedback_set.order_by('profile', '-timestamp').distinct('profile').aggregate(Sum(rating)) Raises exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/PATH_TO_VIRTUALENV/lib/python3.6/site-packages/django/db/models/query.py", line 357, in aggregate raise NotImplementedError("aggregate() + distinct(fields) not implemented.") NotImplementedError: aggregate() + distinct(fields) not implemented. Please help me with this problem :) -
How to merge two object of rest api in django rest framwork?
This my views.py file class NewsChannelListView(ObjectMultipleModelAPIView): def get_querylist(self, *args, **kwargs): userId = self.request.user.id queryset = [ {'queryset': News_Channel.objects.all(), 'serializer_class': NewsChannelSerializers}, {'queryset': Count.objects.filter(userId=userId), 'serializer_class': CountSerializers}, ] return queryset I am getting following respose from my this views { "News_Channel": [ { "id": 2, "name": "Republic", "info": "Arnab Goswami News channel", "image": "https://fourthpillar-static.s3.amazonaws.com/media/repiblic_1bRFWNZ.png", "website": "https://www.repu", "total_star": 10, "total_user": 2 }, { "id": 1, "name": "NDTV", "info": "India News Media", "image": "https://fourthpillar-static.s3.amazonaws.com/media/ndtv_WH67OhA.png", "website": "https://ndtv.com", "total_star": 18, "total_user": 2 } ], "Count": [ { "userId": 1, "channelId": 2, "rate": 6 }, { "userId": 1, "channelId": 1, "rate": 8 } ] } Is there any way I can get single object.Channel id 2 in count merge with the id 2 in news channel and Channel id 1 in count merge with the id 1 in news channel. So final Response shoule be like this { "News_Channel": [ { "id": 2, "name": "Republic", "info": "Arnab Goswami News channel", "image": "https://fourthpillar-static.s3.amazonaws.com/media/repiblic_1bRFWNZ.png", "website": "https://www.repu", "total_star": 10, "total_user": 2, "userId": 1, "rate": 6 }, { "id": 1, "name": "NDTV", "info": "India News Media", "image": "https://fourthpillar-static.s3.amazonaws.com/media/ndtv_WH67OhA.png", "website": "https://ndtv.com", "total_star": 18, "total_user": 2, "userId": 1, "rate": 8 } ], } I am using django 2.1.7 and the djangorestframework==3.9.2. -
Django RelatedObjectDoesNotExist After Upgrade to 2.2
I've recently upgraded one of my Django projects from 1.9.6 to 2.2 and in doing so I'm getting a strange error around a specific ForeignKey relation. models.py class MyObject1(models.Model): myobject2 = models.ForeignKey(MyObject2, on_delete = models.CASCADE) views.py def my_view(request, id): try: my_object = MyObject1.objects.get(id = id) except: # do some stuff else: print (my_object.myobject2) result RelatedObjectDoesNotExist MyObject1 has no myobject2 at line print (my_object.myobject2) I have confirmed via the Django shell that the instance in question does have a valid myobject2 and I don't get that error when performing the same actions in the shell. All other ForeignKey relations in the application work as expected except for this one. This is quite puzzling and all help is appreciated. Thanks! -
Why does this indefinite character appear when doing a line break in reportlab pdf of django and how to remove it?
Two months ago I tried to make a PDF report with ReportLab in Django and everything worked fine until we started managing text areas. When you make a line break in HTML and it is shown in PDF, the following undefined character appears: Duro■ dasfgq■ asg■ asgag I have already tried to find solutions, both in Spanish OS and in English OS and I really do not know what else I can do. Here are some links that I found and try to use but seeing that I do not use paragraphs, I do not know how to handle it in tables: reportlab issue with line breaks using XPreformatted - additionall question mark printed Why does this character ▯ appear? def tabla(self, participante_id, pdf,y): try: participante = Participante.objects.get(id=participante_id) except Participante.DoesNotExist: participante=False datosnew = Despedida.objects.filter(participante=participante) a = 200 for despi in datosnew: a += 200 y -= 140 encabezados = ('Sesión', 'Fecha') detalles = [(despi.sesion, despi.fecha)] encabezados1 = ('¿Qué significa para mi despedirme?:',) detalles1 = [(despi.despedida1,)] encabezados2 = ('¿Qué duele de las despedidas?:',) detalles2 = [(despi.despedida2,)] encabezados3 = ('¿Qué hago cuando no quiero despedirme?:',) detalles3 = [(despi.despedida3,)] encabezados4 = ('Menciona 5 cosas, personas o etapas de las que te costó despedirte',) … -
Python requests inside a view hags out and needs timeout
I'm seeking help for this rather strange behaviour. I have a view that gets called after a button click @require_http_methods(['GET', 'POST']) @login_required @transaction.atomic def create_key(request, slug): #some unrelated code try: r = requests.post( some_url, data={ #some_data }, auth=(client_id, client_secret), timeout=(req_to, res_to) ) if r.status_code == 200: return True else: return False except ReadTimeout as to: # handle exception return True except Exception as e: # handle exception return False #some unrelated code that basically calls an API endpoint to create a key. Now the request with Postman works fine, taking out that python snippet and running it alone also works, but when put inside this Django view it hangs until reaches response timeout. Does anybody has any idea or pointer on where the problem might be? Thank you in advance! -
How do I transfer the Sum of several model fields to a django template and how can I total them by type?
This community has different gas-tank (bombonas in Spanish) providers in three different size and different colors based on the provider (a specific color for each one). For every provider--if I use the DJango API--I can obtain, the total of each individual color of gas-tank by size and color, Using queryset.aggregate(Sum(specific gas-tank field)). HOW CAN I DISPLAY THIS RESULTS IN MY TEMPLATE (bombona_list.html)? I am new to django and python...enter image description here My model... class Perfil(models.Model): is_active = models.BooleanField('Activo', default = True) familia = models.ForeignKey(Familia, on_delete=models.CASCADE, related_name='cod_clap') bombona_peq = models.BooleanField('Tiene bombonas pequeñas', default = False) peq_pdvsa = models.PositiveIntegerField('PEQUEÑAS PDVSA-GAS', default = 0) peq_amarilla = models.PositiveIntegerField('PEQUEÑAS AMARILLAS', default = 0) peq_verde = models.PositiveIntegerField('PEQUEÑAS VERDES', default = 0) peq_roja = models.PositiveIntegerField('PEQUEÑAS ROJAS', default = 0) peq_azul = models.PositiveIntegerField('PEQUEÑAS AZULES', default = 0) peq_marron = models.PositiveIntegerField('PEQUEÑAS MARRONES', default = 0) bombona_med = models.BooleanField('Tiene bombonas medianas', default = False) med_pdvsa = models.PositiveIntegerField('MEDIANAS PDVSA-GAS', default = 0) med_amarilla = models.PositiveIntegerField('MEDIANAS AMARILLAS', default = 0) med_verde = models.PositiveIntegerField('MEDIANAS VERDES', default = 0) med_roja = models.PositiveIntegerField('MEDIANAS ROJAS', default = 0) med_azul = models.PositiveIntegerField('MEDIANAS AZULES', default = 0) med_marron = models.PositiveIntegerField('MEDIANAS MARRONES', default = 0) bombona_gra = models.BooleanField('Tiene bombonas grandes', default = False) gra_pdvsa = models.PositiveIntegerField('GRANDES PDVSA-GAS', default … -
How to obtain an object from a queryset of another object list in django
i am developing a project with django and i have a little problem. I am trying to get an array from a querySet of another object. Trying to obtain the "articulo" who has the "carro_det.id_articulo_fk" field, and after send it to the context of my template: But in the querySet i am getting the error 'int() argument must be a string, a bytes-like object or a number, not 'Articulo'' Specifically in the line: articulo[i]=Articulo.objects.get(pk=carro_det[i].id_articulo_fk) This is from my views.py: def index(request, id_user): carro=Carro.objects.get(id_usuario_fk=id_user) carro_det=Carro_det.objects.filter(id_articulo_fk=carro.id) #HERE IS THE PROBLEM for i in range(len(carro_det)): articulo[i]=Articulo.objects.get(pk=carro_det[i].id_articulo_fk) contexto = {'articulo':articulo, 'carro_det':carro_det} return render(request, 'cart/cart.html', contexto) And this is from my models.py, as you can see everything is fine here: class Carro(models.Model): total = models.FloatField(default=0, null=True, blank=True) #llaves foraneas id_usuario_fk=models.ForeignKey('myuser.Usuario', null=True, blank=True, on_delete=models.CASCADE, db_column='id_usuario_fk') def __str__(self): return "id_carro_cliente: " + str(self.id) class Carro_det(models.Model): cantidad = models.IntegerField(default=0) precio_venta = models.FloatField(default=0) total = models.FloatField(default=0) #llaves foraneas id_carro_fk=models.ForeignKey('Carro', null=True, blank=True, on_delete=models.CASCADE, db_column='id_carro_fk') id_articulo_fk=models.ForeignKey('article.Articulo', on_delete=models.CASCADE, db_column='id_articulo_fk') def __str__(self): return "numero de carro asociado: " + str(self.id_carro_fk.pk) I hope anyone can help me with this, Thank you!. -
Security-concerns about Django email-host-data in settings.py
I've set up my e-mail settings for my Gmail-account like it's described in the django-documentation: settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'me@gmail.com' EMAIL_HOST_PASSWORD = 'password' So, maybe I'm to concerned about this, but I have some doubts due security while writing this kind of sensitve data into my settings.py-file. So, is there a more secure way to set that up? -
After running python manage.py createsuperuser nothing happened
I am trying to createsuperuser. I'm in my project. When I type python manage.py createsuperuser nothing happens, it looks like POWERSHELL has hung up. After this command I only see blank page without next line to enter next command. I'm learning from tutorial: https://www.youtube.com/watch?v=F5mRW0jo-U4&t=1752s Step on which I got suck: 17 minutes 45 seconds (trydjango) PS C:\Users\piotr\dev\trydjango\src> python manage.py createsuperuser -
Django error "Reverse for 'x' not found. 'x' is not a valid view function or pattern name.", but x is a pattern name
I've been building a Django app with Celery, and I'm using Javascript to poll a local database using a URL. For some reason, I keep getting an error from the url template tag in my script. What am I doing wrong? I've looked through about every variation of this question on SO, and they all boil down to bad names. As far as I can see, my names are correct and I'm not using any namespaces. The line in urlpatterns path('render_status', app.views.render_status, name='render_status'), The offending Javascript (layout.html). <script type="text/javascript">// <![CDATA[ function get_status() { fetch('{% url 'render_status' %}').then(function(response) { response.json().then(function(data) { if(data.status) { // show render link // don't forget to hide on click } else { // show loading gif } }); }); get_status(); // ]]></script> Finally, the views function that it's all leading to def render_status(request): result = db_API.get_render_status(request.user.id) return HttpResponse({'status': result}, content_type='application/json') I expected it to continually check my database for the status of the users latest job, but instead it errors out. -
How do I pass query parameters to the django rest api javascript client
I would like to limit the list of logins returned by the django rest framework javascript api client based on the foreign key linking the login to the member table. It seems that I should be using query parameters, but I'm not sure how to pass a query parameter to the javascript api. Here is the javascript code I currently am working with: var auth = new coreapi.auth.SessionAuthentication({ csrfCookieName: 'csrftoken', csrfHeaderName: 'X-CSRFToken' }) var client = new coreapi.Client({auth: auth}); let action = ["login", "list"]; client.action(schema, action, params).then(function(result) { console.log(result); }); How do I tell the javascript api to pass: member_id=5 to this request? On the django side of things: models.py (simplified): class Member(models.Model): name = models.CharField(max_length=64) disk_quota = models.PositiveIntegerField(default=50000000000) class Login(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) username = models.CharField(max_length=254) password = models.CharField(max_length=64, blank=True) serializers.py: class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = '__all__' class LoginSerializer(serializers.ModelSerializer): class Meta: model = Login fields = '__all__' urls.py router = routers.DefaultRouter() router.register(r'member', views.ApiMemberViewSet, base_name = 'Member') router.register(r'login', views.ApiLoginViewSet, base_name = 'Login') urlpatterns = [ path('api/docs/', include_docs_urls(title='Petal API service')), path('api/schema/', get_schema_view(title='Pastebin API')), path('api/', include(router.urls)), } views.py: class ApiLoginViewSet(viewsets.ModelViewSet): serializer_class = LoginSerializer def get_queryset(self): return Login.objects.filter(member=request.query_params['member_id']) -
Django WhiteNoise configuration is incompatible with WhiteNoise v4.0
I am trying to deploy my Django webapp on Heroku. I have been facing this same error everytime I try to deploy. ImportError: Your WhiteNoise configuration is incompatible with WhiteNoise v4.0 This can be fixed by following the upgrade instructions at: http://whitenoise.evans.io/en/stable/changelog.html#v4-0 ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed I visited the link to make the changes as the documentation suggests. It required me to remove any mention from the the wsgi.py file and I had to add it to the middleware in settings.py and change the static storage. #settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', . . . . STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I am following this tutorial (https://simpleisbetterthancomplex.com/tutorial/2016/08/09/how-to-deploy-django-applications-on-heroku.html) I'm not sure what is causing this error. Whitenoise updates are applied and the static files are in place as well. The project works like a charm on local server but im just not able to deploy it. Thanks in advance! -
Django test for POST always returns 400
Form and view all work just fine in browser and time to add tests to make sure the view continues to work. Problem is the test always returns 400 view: class DogRequestView(LoginRequiredMixin, TemplateView): template_name='dog_request.html' def get(self, request): form = DogForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = DogForm(request.POST) process_status = 'initial' if form.is_valid(): stuff() return render(request, self.template_name, {'form': form, 'status': process_status}) test: class LabTests(TestCase): def test_DogForm(self): form_data = { 'dog_name': 'Test name', 'dog_type': 'k9' } self.client.login(username="test@acme.com", password="test") response = self.client.post("/kenel/dog-catalog/dog-request", form_data) self.assertEqual(response.status_code, 200) url: url(r'^kenel/dog-catalog/dog-request$', dog_catalog.DogRequestView.as_view()), test output: self.assertEqual(response.status_code, 200) AssertionError: 400 != 200 -
How to redirect to previous form
Context: An updateview for a payroll. In the updateview for employee's payroll details, there is a button to add/edit/delete an overtime record. The model for payroll updateview is "Cur_Payroll". The model for Overtime is "Cur_OT" After user click "Add" overtime button, I want to send them to a new page where Cur_OT instance will be created to add an overtime. And in that model i want the some fields from Cur_Payroll as default value like employee number,payperiod. What good way to approach this problem? class OvertimeCreate(LoginRequiredMixin,CreateView): model = Cur_OT template_name = 'payroll/transaction/otcreate.html' fields = [ 'empno', 'dtpay', 'cd_ot', 'ot_hrs', 'ot_amt', 'ty_ot', ] def get_context_data(self,**kwargs): from Home.models import hrm,t_pay context = super(OvertimeCreate,self).get_context_data(**kwargs) context['m_tpay'] = t_pay.objects.get(pk=self.kwargs['pk']) return context def post(self, request, *args, **kwargs): # What to put here? return super().post(request, *args, **kwargs) I tried to: <form method="post" href="{% url 'payrollTransactionUpdate' m_tpay.id %}"> in the createview for overtime. It redirects back to update but behavior is weird, updating doesnt work again. Tried this on Cur_OT model: def get_absolute_url(self): return reverse('payrollTransactionUpdate', kwargs={'pk': self.pk}) but this is not helpful since Cur_OT may have different pk than my Cur_Payroll Im thinking create a new form.Forms and do Formview instead, modify post method, import Cur_OT and Cur_Payroll … -
Dynamically add ProhibitNullCharactersValidator into the form's __init__ in Django. Need an advice
Quite a simple question for someone who knows the answer. Is it possible to dynamically add validator to a form’s field in froms init ??? I want to do something like this: class SomeForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.pk = kwargs.pop("pk", None) forms.ModelForm.__init__(self, *args, **kwargs) if self.pk == some integer: self.fields[field].validator(s)…….. # and I don’t know what to type here else: do something else… Goal is to add ProhibitNullCharactersValidator dynamically depending on the self.pk to self.fields[field] (one field of the form) Thank you in advance and sorry if this questions is dumb.