Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python How to GET Image and then POST (via requests library)
I am using python to try and get an image from one API, and then post it to a separate API. So far I have this code: def create_item(token, user_id): url = '<api_url_to_post_to>' headers = {"Authorization": "Token {0}".format(token)} image_url = '<some_random_image_url>' image_obj = requests.get(image_url) data = { "image": image_obj.content } r = requests.post(url, headers=headers, files=data) response = r.json() print(response) return response The issue is that when I try to post it to the second API, I get a "File extension '' is not allowed." error. This is obviously a custom error message, but it signifies that there is something wrong with the file that I am posting. Any suggestions on what I may be doing wrong? -
Django clickjacking middleware and Firefox embedded PDFs
I recently added clickjacking protection to a Django app with django.middleware.clickjacking.XFrameOptionsMiddleware but found that PDFs no longer load in Firefox. While Chrome, Safari, and Edge embed the PDF as expected, Firefox throws the following console error: Load denied by X-Frame-Options: <site_base>/<file_path>.pdf does not permit framing. I found the @xframe_options_exempt decorator that I thought would help, but that just wraps a view whereas these are served directly through Apache. The only fix I've found is to get the "Ignore X-Frame-Options Header" browser plugin which isn't really a customer friendly solution. I've tried using <embed>, <object>, and <iframe> to embed the PDF and all cause the same browser console error, and if I remove the clickjacking middleware the PDFs load just fine again. Anyone run into something like this before? Relevant code: <select id="pdf_graph_selection" onchange="updatePDF()"> {% for pdf_graph in pdf_graphs %} <option value="{{pdf_graph.url"}}>{{pdf_graph.name}}</option> {% endfor %} </select> <div id="pdf_container"></div> function updatePDF() { let new_source = $("#pdf_graph_selection").val(); let new_graph = "'<embed src='" + new_source + "' width='70%' height='900px' class='pdf_embed'></embed>; $("#pdf_container").html(new_graph); } -
Django: generate the value of a field form based on value entred in another field
i have a form in which i have two fields field_A and field_B the field_A is a choice list i want to trigger the value of field_B display and show it in a textinput field based on the values choosen in field_A note that field_A is a foreign key in model B how to do this in django as long as i utilize django model field -
Django function execution
In views, I have a function defined which is executed when the user submits the form online. After the form submission there are some database transactions that I perform and then based on the existing data in the database API's are triggered: triggerapi(): execute API to send Email to the user and the administrator about the submitted form def databasetransactions(): check the data in the submitted form with the data in DB if the last data submitted by the user is before 10 mins or more: triggerapi() def formsubmitted(request): save the user input in variables Databasetransactions() save the data from the submitted form in the DB In the above case, the user clicks on submit button 2 times in less than 5 milliseond duration. So 2 parallel data starts to process and both trigger Email which is not the desired behavior. Is there a way to avoid this ? So that for a user session, the application should only accept the data once all the older data processing is completed ? -
importing models inside django application
I have made an app inside my django application. I'm trying to create a file(testabc.py) in the same directory as views.py and I want to import models in that file. The name of model is "Example" Now, in views.py, I import models in the following way: from .models import Example a = Example.objects.get() Here, I am getting proper output However, in my testabc.py file when I write the same code I get the following error from .models import Example ValueError: Attempted relative import in non-package -
Why my ajax function are not working on infinite scrolling?
I am building a webpage having infinite scroll using waypoints.js with backend as Django.The problem is, my jquery and ajax functions are not working on newly generated content while they are working with content on first page. <div class="infinite-container"> {%if result %} {% for c in result %} <div class="infinite-item"> <!-- some arbitrary code--> </div> {% endfor %} {% if result.has_next %}<a class="infinite-more-link" href="?page={{ result.next_page_number }}"></a><div class="loading">loading...</div>{% endif %} {% endif %} </div> <script type="text/javascript"> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); Now suppose if every page contains 5 entries, then my jquery and ajax functions are working on first 5 entries only. -
Django file field how to fill with stream io
I'm trying to attach in a model a file that is currently not on the disk, but exist in memory. The model use django-filer, if I pass a regular file it works, with io stream it fails. def test_save_bytesio(): from PIL import Image import io from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile img = Image.new("RGB",(4,4)) thumb_io = io.BytesIO() img.save(thumb_io, format='JPEG') # thumb_file = InMemoryUploadedFile(thumb_io, None, '{}_da_ordine.jpg'.format(1), 'image/jpeg', # thumb_io,None) thumb_file = DjangoFile(thumb_io.getvalue(), name='gigi') #thumb_file = DjangoFile(thumb_io, name='gigi') mymodel = MyModelTosave.objects.create( name='gigi', file=thumb_file ) this is the error stack: return field.pre_save(obj, add=True) ../../.local/share/virtualenvs/--M2Y9QA9/lib/python3.7/site-packages/django/db/models/fields/files.py:288: in pre_save file.save(file.name, file.file, save=False) ../../.local/share/virtualenvs/--M2Y9QA9/lib/python3.7/site-packages/filer/fields/multistorage_file.py:121: in save content.seek(0) # Ensure we upload the whole file _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <File: gigi> > seek = property(lambda self: self.file.seek) E AttributeError: … -
Celery using SQS on Amazon Elastic Beanstalk frequently pauses for long periods while there's messages waiting
I'm currently working on porting an existing single server Django based web project to Amazon Elastic Beanstalk. So far, I've successfully setup the project to use RDS, Elastic Search, Simple Email Service, and S3 without too much trouble. I'm using Code Deploy to build a Docker container for the Django project and deploy to an Elastic Beanstalk environment. All of this works beautifully but I'm running into an issue trying to get a Elastic Beanstalk worker environment to work well with this setup. I'm deploying the same Docker container to my worker environments but with a different start point to run celery instead of gunicorn. This seems to work; the worker consumes messages and processes them just fine, but it frequently appears to stop work for minutes at a time, even when there's a backlog of messages waiting in the queue. During my testing, I'm trying to run my invoice generation routine that queues up a message for each account's invoice by using a Celery group in a chain so it will process the invoices, then email me a "completed" notice. In total, I have about 250 messages in the queue at the outset. Tailing the celery logs for the … -
extjs getting data from django rest api
I'm trying to get data from a django rest api using Extjs. My Data represents a Tree which have a one-to-one relation to itself. I have this model: Ext.define('mypackages.model.MyData', { extend: 'Ext.data.Model', idProperty: 'myid', fields: [ { name: 'name', type: 'string', mapping: 'name' }, { name: 'family_name', type: 'string', mapping: 'family_name' } ] }); And this is my store: Ext.define('mypackages.store.MyData', { extend: 'Ext.data.TreeStore', alias: 'store.files', model: 'mypackages.model.MyData', autoLoad: true, proxy: { type: "rest", url: "/myurl/", reader: { type: 'json' }, actionMethods: { read: 'GET' }, extraParamas:{ 'myid': '' } }, constructor: function (config) { config = Ext.apply({ root: Ext.clone(this.rootData) }, config); this.callParent([config]); } }); The api is working as expected, but, when I ran this and I went into the network inspector of my browser I can see a 404 due to this: http://127.0.0.1:8000/myurl/root/?_dc=1553095552422 How can I remove the root/?_dc=1553095552422 from the request url, or what am I missing here in order to get this sending the correct request url? -
In Django Admin, how to allow a field to be writeable when the object is being created, but only readable after that?
I've made multiple attempts to achieve my objective. When adding an object, I want the "value" field to be writeable. When changing the object, I want it to be readable, like so : So far, I've achieved two different solutions that don't actually work. The first one is to override the widgets with a disabled attribute : @admin.register(MyObject) class MyObjectAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): if obj is not None: kwargs['widgets'] = { 'value': forms.TextInput(attrs={'disabled': True, }), } return super().get_form(request, obj, **kwargs) At first glance, this seems to work : However, if I try to save my changes to the object, Django will return an error saying that the fields are required, as the disabled fields can't be saved. The other option I've found is to alter the fields in get_form : @admin.register(Batch) class BatchAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): if obj is None: kwargs['fields'] = ['name', 'value',] else: kwargs['fields'] = ['name',] return super().get_form(request, obj, **kwargs) This correctly gives me the ability to write the value field when adding an object, but it hides the value field altogether in the change form. How can I make a field writeable when added, and read-only when changed ? -
Django: get specific value from queryset
I´m trying to get the media of sales per month. I can do the calculation but then I can´t get just the value instead a the queryset. I found different options and some work in some context but not in other. I guess there is some missunderstanding of different querysets data and dictionaroes too. Here goes my example. for este in inventario_diferencia: este['stock_valor_venta'] = este['existencias'] * este['valor_venta'] este['diferencia'] = inventario_original.filter(fecha=diferencia_fecha, codigo_kinemed=este['codigo_kinemed']).values()[0]['existencias'] - este['existencias'] media_venta_mes = Ventas.objects.filter(prod_codigo=este['codigo_kinemed']).values("prod_codigo").annotate(media=Sum("uds")/Count(TruncMonth('fecha'), distinct=True)) If a print media_venta_mesI get the correct calculation. For example: <QuerySet [{'prod_codigo': 'TP3 SHOULDER', 'media': 24}]> Then I want to insert that media value in the general inventario_diferenciadictionary. If I do media_venta_mes = media_venta_mes.values("media") I get <QuerySet [{'media': 24}]>. If I try media_venta_mes = media_venta_mes.get("media"), which works for me in aggregates, I get too many values to unpack (expected 2). If I try media_venta_mes = media_venta_mes.media I get 'QuerySet' object has no attribute 'media'. I tryied something more I can´t document now. I know I´m beign a dumb newbie here, sorry and thanks for the help. Extra Besides this specific code help, I would appreciate some reading reccomendations about querysets and dictionaries. I passed through the basic documentations but it´s clear I´m not … -
Adding id = "" in the template to 'HttpResponseRedirect (reverse ('name_view'))'. Django
Can I add an id to my method 'HttpResponseRedirect (reverse ('name_view'))'? I have a simple form, the user can see the message ('!All is good! :).') after sending it. But it is at the bottom of the page and the user is redirected to the top of the page. Can I do a redirection to the bottom of the page (after saving the form)? If so, how to achieve it. Any help will be appreciated. views.py if request.method == 'POST': contact_form = ContactForm(request.POST) if contact_form.is_valid(): contact_form.save() messages.success(request, '!All is good! :).') return HttpResponseRedirect(reverse('app:home')) else: contact_form = ContactForm() In my case, I am looking for something like: return HttpResponseRedirect(reverse('app:home#message_sending_section')) home.html <section class="module divider-top" id="message_sending_section"> [...] {% if messages %} <div class="alert alert-success alert-dismissible fade show" role="alert"> {% for message in messages %} {% if message.tags %} <span class="alert-inner--icon"><i class="fas fa-check"></i></span> <span class="alert-inner--text"></strong>{{ message.tags }}</strong></span> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {% endif %} {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %} {{ message }} {% endfor %} </div> {% endif %} [...] </section> -
Django: Break query result into multiple lists of common elements
I have model Data: class Data(models.Model): sensor_param = models.ForeignKey(SensorParameter, on_delete=models.CASCADE) time = models.DateTimeField(db_index=True) value = models.FloatField() And model SensorParameter has links to parameters (temperature, vibration, etc) and a sensor instance (serial number, etc): class SensorParameter(models.Model): sensor = models.ForeignKey(Sensor) parameter = models.ForeignKey(Parameter) I can query the Data table for a certain time range period from a certain Sensor by doing a double backwards lookup and ordering the resulting query the way I'd like to have my lists broken down, first by sensor_parameter, then by time: sensor = Sensor.objects.get(serial_number=request["data_source"]) range_period = [request['start'], request['end']] data_query = Data.objects.filter(sensor_parameter__sensor=sensor, time__range=range_period).order_by('sensor_parameter', 'time') This results in a list of all data points, for the time period requested, for the sensor requested. How can I then break down the resulting list into several lists by SensorParameter (and still arranged by time of course)? Example from: queryset_overall_result = [ {data_point_1: sensor: X, sensor_parameter: temp, value: 188, time: 00:01} {data_point_2: sensor: X, sensor_parameter: vibration, value: 5, time: 00:01} {data_point_3: sensor: X, sensor_parameter: temp, value: 185, time: 00:02} {data_point_4: sensor: X, sensor_parameter: vibration, value: 6, time: 00:02} ] To: list_temp = [ {data_point_1: sensor: X, sensor_parameter: temp, value: 188, time: 00:01} {data_point_3: sensor: X, sensor_parameter: temp, value: 185, time: 00:02} ] … -
In Django, can you run seed data without always generating a migration?
I'm using Django and Python 3.7. I have created a YAML file with seed data for my db ... ./myapp/fixtures/seed_data.yaml How do I run this without generating a new migration for it, as is specified here -- Loading initial data with Django 1.7 and data migrations ? I think theoretically there may be times when I add data to the file and my need to re-run it so it would be a little cumbersome to generate a new migration every time. -
Django Registering two different types of users with different fields
I want to create two users: patient and doctor. Both users will share some of the standard fields like first_name, last_name, etc. However, they should have different fields. Only the doctor, for example, will have fields like expertise and days_available. I reviewed a similar question but it doesn't quite address what I need specifically. I don't necessarily need custom permissions/authentication as I simply need separate fields for each user. I've tried the last approach, extending the user model, but when I create the the user, it's not linked to the patient/doctor. I have to manually create a doctor and the link it to the user. How can the doctor/patient be automatically created when a user is created? class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_patient = True pid = models.AutoField(unique=True, primary_key=True) #patient identification class Doctor(models.Model): upin = models.AutoField(primary_key=True) #unique physician identification number user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_doctor = True expertise = models.CharField(max_length=20) days_available = models.DateTimeField(null=True) -
Overriding a template in Django
I'm using this library to add a sessions tab on my django project. I'm calling the module's template from my project using this line: <li><a href="{% url 'user_sessions:session_list' %}">Sessions</a></li> It works, but now i'd like to style the page, and to do that i need to override the module's template with my own template. So, as the module says here, i inherited the module's SessionListView on my own views.py to overrided the template: from user_sessions.views import SessionListView class MySessionList(SessionListView): template_name = 'user_sessions/session_list.html' .. then i added the url to my urls.py url( regex=r'^account/sessions/$', view=MySessionList.as_view(), name='sessions', ), ... And then i created my template on my own project which is located like this: templates/user_sessions/session_list But for some reason, i still can't see MY template appearing, the module's template keeps appearing instead. Can anyone help me finding what i'm doing wrong? -
unable to get post params from axios
I want to make a Visual search interface with keywords and category to search sth. Obviously, It needs front-end and back-end data interaction. So after weighing some tools, I have choosed Vue and axios to implement data interaction in the front-end, and django view in the front-end. In my index.html page, I defined my axios like this. var param = new URLSearchParams(); param.append('searchKey',this.searchKey); param.append('category',this.selected); axios.post("{% url 'main:getCommodityInfo'%}", param, {headers:{'X-CSRFToken': this.getCookie('csrftoken')}},) .then(response=>{ console.log(response); }) .catch(error=>{ console.log(error); alert("connection has error") }) searchKey and category could be acquired by Vue object. Then I post the data to my back-end django view. def getCommodityInfo(request): if request.method=="POST": # To get the POST paramaters searchKey = request.POST.get('searchKey') category = request.POST.get('category') # unique ID for each record for DB uniqueId = str(uuid4()) print("Enter the view! ",searchKey,category) # set setting settings = { 'unique_id': uniqueId, 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } # task Id to indentify each spider task task = scrapyd.schedule('JDSpider', 'getCommodityInfo', settings=settings, searchKey=searchKey, category=category) print("It seems everything is running well? ") print(task,uniqueId) print("-"*100) return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False) Well, the view could acutally get the POST paramaters. But When I am trying to return the status json from view to the axios function, error … -
How to save image in local or cloud in DRF + mongoDB?
I'm having DRF application with MongoDB(DRF mongoengine) as database. So i was planned to save the image in local and save the image path in DB. So i'm writing some custom function for saving the image. Models.py class Course(Document): thumbnail_img = fields.StringField() custom function def download_image(image_obj, org_name): if not os.path.exists(settings.MEDIA_URL+org_name): os.makedirs( settings.MEDIA_URL+org_name ) img_path = os.path.join(org_name, 'image', image_obj.name) img_obj = Image.open(image_obj) img_obj.save(settings.MEDIA_URL+img_path) I'm writing function like this. But i don't think this is proper way. Can anyone suggest some better option to do this. -
Django: update with conditions
i want to update an object through a form in django but befor doing form.save in the view i want to do some conditions about the data for example : ire = get_object_or_404(Ire, id_IRE=pk) if request.method == 'POST': form = IreForm(request.POST or None, instance=ire) if form.is_valid(): if ire.get_att1()==form.cleaned_data.get('att1') and ``ire.get_att2()==form.cleaned_data.get('att2'): form.save(update_fields=['type']) #just update the field type else form.save() #create a new object` when i did this in my view just the first condition works but when i change the att1 or att2 in the form it does not do any changes please help me how can i do conditions befor saving!!! -
Get data objects that do not have onetoOne relationship
My problem is that i need to get the unmatched data objects from both Table1 & Table2. class Table1(models.Model): client_id = models.IntegerField(primary_key=True) spend = models.DecimalField(max_digits=5, decimal_places=2) target_impressions = models.CharField(max_length=255) date_start = models.DateField(auto_now=False) date_stop = models.DateField(auto_now=False) impressions = models.IntegerField() client_name = models.CharField(max_length=250) bill_date = models.DateField(auto_now=False) app_tag = models.CharField(max_length=10, default='na') days = models.IntegerField(null=True, blank=True) cpm = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) status = models.CharField(max_length=2, choices=STATUS, default='na') percentage = models.IntegerField() objects = models.Manager() def __str__(self): return self.client_name class Table2(models.Model): kid = models.OneToOneField(Campaign,primary_key=True, on_delete=models.CASCADE, related_name='hubs') vid = models.IntegerField(null=True, blank=True) lastbd = models.DateTimeField(blank=True, null=True) nextbd = models.DateTimeField(blank=True, null=True) gviews = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.kid) So here are my models and they get populated from different source then i need to check if both of them have common PK i.e client_id & kid. If these two are same then i fetch them out using select_related. But i can't really seem to get the unmatched instances. views.py qs = Hubspot.objects.select_related('kid').distinct() this is the query that gets me the data objects having common Pk. Tried using set's diffrence and many other but no luck. TIA -
How to create view for random url?
I'm in the process of accepting payments on my site and I have chosen to use Stripe. The way it works is that when the payment is finished or cancelled it redirects to a page depending on what happened. How can I create a view that checks for the GET parameter of my randomly generated url, so I can do my code stuff? payment = stripe.checkout.Session.create( success_url="https://myurl.com/dashboard/payment/accepted/id=MyvariableID", cancel_url="https://myurl.com/dashboard/payment/declined", payment_method_types=["card"], client_reference_id= stripeUID, line_items=[ { "amount": 2000242, "quantity": 1, "name": "Blender rendering", "currency": "usd", } ] ) So let's say that the users payment is confirmed and he's redirected to success_url="https://myurl.com/dashboard/payment/accepted/id=MyvariableID", How can I create a dynamic view that checks for the GET parameter ID so I can query some database stuff? If there's a better way to do this then feel free to let me know. Any help is greatly appreciated. -
django url_for equivalent
I'm trying to find a django method that is equivalent to Flask's url_for. I'm not looking for the jinja equivalent (as shown here) -- I'm talking about on the python side of the house in my flask app I send an HTML string as follows: my_picture = '<img src="{}">'.format(url_for('static', filename=r'images/myPic.jpg')) I know I could do this in the html as <img src={{ my_picture }}> but that's not my goal. What I've been doing is from my_project.settings import STATIC_URL my_picture = '<img src="{}">'.format(os.path.join('static', 'images/myPic.jpg')) but there has to be a better way Thanks! -
jQuery not finding a `span` element returned by Django
I'm having trouble using jQuery to retrieve a HTML string retuned by Django. In a Django template I have the line {{ generated_files.exercise_instructions.content | safe}} which when expanded contains the string 2. Määritä luvun <span class="inline-math"> -6 </span> vastaluku. I would like to be able to use KaTeX to render the contents of the span element as math, but $(".inline-math").each( function(i, element) { console.log("Rivimatikkaa: " + element.innerHTML); katex.render(element.innerHTML,element); } ); does nothing towards this end. The span element of class inline-math is not detected by jQuery, as the console.log(element.innerHTML) does nothing, nor is the math rendered. My question therefore is, how could I render a string containing math returned by Django using KaTeX? -
Django trouble using image form
Ive been trying to create a profile page for a project, where the user can upload a profile pic and some basic personal information using Django as framework. The text based information I pass in my code seem to work, but I cant get the user to upload a profile pic from the profile page. But if I go to django-admin page, I can upload and display the profile pic from there. So to models.py file seem to work, and the issue seem to be in forms.py file... Ive search the net for some time and various turtorials, but nothing seem to work. Please help :) models.py file class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) email_confirmed = models.BooleanField(default=False) image= models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username forms.py file class ProfileUpdateForm(forms.ModelForm): YEARS= [x for x in range(1900,2021)] birth_date = forms.DateField( initial="21-06-1995", widget=forms.SelectDateWidget(years=YEARS)) image = models.ImageField(upload_to='profile_image',blank=True) class Meta: model = Profile fields = ('bio','birth_date','location','image') views.py file @login_required def profile_edit(request): form = ProfileUpdateForm(request.POST) if request.method == 'POST': if form.is_valid(): user = request.user user.profile.bio = form.cleaned_data.get("bio") user.profile.birth_date = form.cleaned_data.get("birth_date") user.profile.location = form.cleaned_data.get("location") user.save() return redirect('profile') else: form = ProfileUpdateForm() context = { 'form' : … -
Django render to pdf with button
I have def that render to pdf with action on django-admin. def Print(self, request, obj): data = { 'obj':obj } pdf = render_to_pdf('daa/imprimir/pdf.html', data) if pdf : response = HttpResponse(pdf, content_type='application/pdf') filename ="Avaria_%s.pdf" %("123451231") content = "inline; filename='%s'" %(filename) response['Content-Disposition'] = content download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and on my actions I have: class ModelAdmin(admin.ModelAdmin): actions = [Print] and it is working all good, I select what objects I want to render and in my html I have cicles that make a list of all fields I want of those obj's. But right now I don't want to render to pdf a list. I want to render only 1 obj. So I create a custom button to do that. http://prntscr.com/muijhl So when I click on button I want to render to pdf the obj which is open. I don't know what I need to do to take my def and but inside of button