Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix upload file from angular 7 to djago rest
I'have rest api devlopped with djago and application front devlopped with agular7 and i try to upload image to my rest api when i try to send it with form data the form data is empty in the api. for angular i try to send form data with file. Angular: getPredictionImage(file): Observable<any> { const HttpUploadOptions = { headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data'}) } const f = new FormData(); f.append('image', file, file.name); console.log(f); return this.http.post(this.urlapiimage, file, HttpUploadOptions); } Django: def post(self, request, format=None): print("heloooo") print(request.data) serializer = MammographySerializer(data=request.data) print(serializer) if serializer.is_valid(): result='hi' serializer.save() return Response(result,status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) the request.data is empty -
What is the difference between these two methods of serving static files in Django?
I have a Django app that uses different static files such as images, css files, and js files. That being said, the documentation https://docs.djangoproject.com/en/2.2/howto/static-files/ shows two different ways to serve static files, and I've also seen developers follow both methods. I'm currently doing it like this: #settings.py STATIC_URL = '/static/' # whatever.html {% load static %} <img src="{% static "my_app/example.jpg" %}" alt="My image"> With all my images inside the same folder as my main.css file. But I've also seen developers following the second method of the documentation: #settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When using the second method, they'll have a different folder called media that is located at the same level as all main apps. Supposedly I'd leave my images in there. I'm wondering if it's okay to follow the first method (using {% load static %}) which is what I'm doing, and what the difference between the two methods is. Thank you! -
How does one create a Factory with foreign key instances that share certain attributes - but that attribute does not exist on parent?
I'm looking to use FactoryBoy to ensure that a model with foreign keys to other models that indirectly share foreign keys are generated with the same instances (I realize that’s pretty hard to grok, here’s a code example): from django.db import models import factory class Foo(models.Model): name = models.CharField(max_length=32) class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.PROTECT) class Baz(models.Model): foo = models.ForeignKey(Foo, on_delete=models.PROTECT) class HasBarAndBaz(models.Model): bar = models.ForeignKey(Bar, on_delete=models.PROTECT) baz = models.ForeignKey(Baz, on_delete=models.PROTECT) class HasBarAndBazFactory(factory.django.DjangoModelFactory): class Meta: model = HasBarAndBaz bar = factory.SubFactory(BarFactory) baz = factory.SubFactory(BazFactory) The desire here would be to ensure that the following occurs has_bar_and_baz = HasBarAndBazFactory() has_bar_and_baz.bar.foo === has_bar_and_baz.baz.foo # should be True I can think of a couple solutions, but I’m curious to know if there’s a “FactoryBoy” way to do this, without needing to write a wrapper function that accepts a product_line kwarg and passes it. I thought about using a RelatedFactory, and then referencing that as the default foo kwarg to the SubFactories, but a RelatedFactory gets generated after the base factory. -
Filling MS Word Template from Django
I found some python docs relating to docxtpl at this link: https://docxtpl.readthedocs.io/en/latest/ I followed the instruction and entered the code found at this site into a view and created the associated URL. When I go to the URL I would like for a doc to be generated - but I get an error that no HTTP response is being returned. I understand I am not defining one, but I am a bit confused about what HTTP response I need to define (I am still very new to this). The MS word template that I have saved is titled 'template.docx'. Any help would be greatly appreciated! VIEWS.PY def doc_test(request): doc = DocxTemplate("template.docx") context = { 'ultimate_consignee' : "World company" } doc.render(context) doc.save("generated_doc.docx") I would like accessing this view to generate the doc, where the variables are filled with what is defined in the context above. -
{% load static %} Shown as a text line in html opened on browser
Im trying to use templatetags, but when i write {% load static %} on top of html document and run, it takes this as a text, and does not load the static. I set the static config in settings.py but stills not working {% load static%} <!DOCTYPE html> <html> ... </html> when i open the file on browser or when i send the template via email, as expected in the proyect, the css works, but the images doesnt. I realized i'd use the static dir, but the line: {% load static %} is shown in the browser as text. -
Invalid credentials raises exception on auth mutation
I'm using graphene-django and django-graphql-jwt in my django project. When I set invalid credentials server raises 'Invalid credentials' exception. Are invalid credentials supposed to raise an exception on the server? When I test tokenAuth mutation with wrong data Django server raises exception. Django server log: File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/promise/promise.py", line 487, in _resolve_from_executor executor(resolve, reject) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/promise/promise.py", line 754, in executor return resolve(f(*args, **kwargs)) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise return next(*args, **kwargs) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/graphql_jwt/decorators.py", line 106, in wrapper result = f(cls, root, info, **kwargs) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/graphql_jwt/decorators.py", line 89, in wrapper _('Please, enter valid credentials')) graphql.error.located_error.GraphQLLocatedError: Please, enter valid credentials -
Channels 2 uWSGI/Daphne/Workers configuration
Trying to get a uWSGI ini file to bring up Channels 2 properly. Channels 1, looked like: attach-daemon = %(release)/env/bin/daphne -u /opt/sock.ws --ws-protocol "graphql-ws" --proxy-headers -v 1 asgi:channel_layer attach-daemon = %(release)/env/bin/python manage.py runworker --thread=2 --only-channels=websocket.* With Channels 2, I tried: attach-daemon = %(release)/env/bin/daphne -u /opt/sock.ws --ws-protocol "graphql-ws" --proxy-headers -v 1 asgi:channel_layer attach-daemon = %(release)/env/bin/python manage.py runworker websocket Of course asgi:channel_layer now points to the application as I've fixed up asgi.py, but it seems the workers never seem to receive the messages (websocket is of course the name of my route) Any ideas? -
Why is Django app redirect_uri = 'web' and not my domain?
I'm setting up Oauth sign in on my django web app and am getting a redirect_uri error because my django app is using 'web' instead of my domain. How can I change the redirect uri of my django app? I think it has to do with nginx and my configuration file but I'm not too sure what to change. Here's my mydjango.conf file: upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /src/static/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; client_max_body_size 1000M; } For slack authentication, expecting the passed URI to be http://[my domain]/accounts/slack/login/callback/ but instead am getting http://web/accounts/slack/login/callback/ -
django messages after dataframe export to excel
I have a Django view that perform a long qry in the back-end. Once the qry result is available, it exports the data to a csv file. I am using this logic, which is working fine: response = HttpResponse(content_type='text/csv') # Format response as a CSV filename = 'some_file_name' + '.csv' response['Content-Disposition'] = 'attachment; filename="' + filename + '"' # Name the CSV response df.to_csv(response, encoding='utf-8', index=False) return response I need to add a response message that displays on the current page without needing to refresh the page: for that I have the following: if df is None or df.shape[0] ==0: messages.warning(request, 'failure message.') else: messages.success(request, 'success message.') and in the html I have: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %} id="export_messages">{{ message }}</li> {% endfor %} </ul> {% endif %} The problem that I am facing is that the message appears only if I refresh the page after export button is clicked and the file is successfully exported. I am looking for an advise or guidance how to make the message appears right after the button click event. Please note that the action is a form … -
TypeError: getattr() takes no keyword arguments
here my models.py @python_2_unicode_compatible class TaggedItem(models.Model): content_type = models.ForeignKey( ContentType, related_name=getattr( settings, 'USER_TAGS_RELATED_NAME', 'user_tags_tagged_items', on_delete=models.CASCADE), ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') user_tags = models.ManyToManyField( 'user_tags.UserTag', verbose_name=_('User tag'), ) def __str__(self): return str(self.content_object) -
Iterate through dict keys in Django Templates
i have a dict that im passing to my template from my view, but i cant get the dict to show data correctly, if at all. the dict is as follows: context_dct = { 'product0': { 'totalentries': '6', 'type': 'hammers', 'brandname': 'DEWALT', 'price': '$25.84'}, 'product1': { 'totalentries': '5', 'type': 'hammers', 'brandname': 'DEWALT', 'price': '$25.84'}, 'product2': { 'totalentries': '8', 'type': 'hammers', 'brandname': 'DEWALT', 'price': '$25.84'} } using django 2.2 and python3, i passed the dict to my template via render(), and attempted to access it like so: <h1>Results:</h1> {% for key, value in context_dct.items %} <h1>{{ key }}</h1> <h1>{{ value }}</h1> </br> {% endfor %} but the only thing that shows up is "Results" in the h1 tags. i've also tried several other ways of accessing the dictionary, similar to normal python dictionary access, to no avail. i can get it to work correctly when i dont use a nested dictionary, but using it this way, i havent been able to get it to work. is there something im missing here? -
Populating django inline admin fields with javascript
I'm trying to write an importer for populating admin model fields with existing model data: This is my approach: I modified the admin view for the specific model and added a form including select boxes to choose the existing model and a button to start the import. As I'm using drf for many other stuff I wrote an endpoint which delivers the model data via get request. When clicking the button some javascript logic is populating the fields with the given data. For inline models I'm simulating a 'click' to add the necessary rows before filling the fields. This is working as expected. But after clicking the save button, the classic error please correct the errors below appears. After implementing some logging, I could figure out the actual error message which is related to the the inline model fields. The inline value did not match the parent instance. Is django doing some other "magic" I'm missing when filling the inline admin fields? Thanks in advance -
Recieve multiple rows data from html to python using request.form?
i am trying to send data from html to python using POST method and 1 row works fine code is below for python def InsertData(): if request.method == 'POST': conn = pyodbc.connect('DRIVER={SQL Server};''SERVER=.;''DATABASE=Store;''TRUSTED_CONNECTION=yes;') try: unit = request.form['unit'] head = request.form['head'] headname = request.form['headname'] vocabid = request.form['vocabid'] cursor = conn.cursor() cursor.execute("SELECT MAX ([HEAD_ID])FROM [Store].[dbo].[Head] ") row = cursor.fetchall() id = row[0] temp = str(id) lent = len(temp) r_id = temp[2:lent-4] rr_id = int(r_id) + 1 ctypes.windll.user32.MessageBoxW(0, str(rr_id), "Test Box Ali Azeem", 1) type= request.form['type'] cursor.execute("insert into [Store].[dbo].[Head] values ( ?,?,?,?,?,? )",(rr_id,unit,head,type,headname,vocabid) ) conn.commit() msg = "Record successfully added" except: conn.rollback() msg = "error in insert operation" finally: conn.close() return render_template("index.html") but i have dynamic fields as i can add multiple rows then how can i handle it ? As now the field names are type0,unit0,head0.....type1,unit1,head1....and so on... Html and js code is below </form> <!-- project team & activity start --> <form method="POST" id="form111" action="\insertdata"> <div id="cont"></div> <input type="button" class="btn bg-primary" id="addrow" value="Add New Row" onclick="addRow()"/> <button type="submit" class="btn bg-primary">Submit</button> </form> and in javascript i am adding multiple rows. -
Django quering foreign key from backward
I am trying to query from backward: at fist see my models: from django.db import models class Blog(models.Model): title = models.CharField(max_length=100, unique=True) body = models.TextField() category = models.ForeignKey('blog.Category', on_delete=models.CASCADE) def __unicode__(self): return '%s' % self.title class Category(models.Model): name = models.CharField(max_length=100, db_index=True) I have many category and many post, one category name is tech I am trying to get all the post those are in tech category. I tried like this. Category.objects.filter(contain__exact='tech') but it is not work anymore. Can anyone help me to figure get it done? -
How can I fix this conflict of packages while using Django, Channels, and Heroku?
I am following this tutorial on how to deploy a Django+Channels webapp on Heroku, and I've come across a problem when I run the following line: daphne chat.asgi:channel_layer --port 8888 I get the following: ERROR: daphne 2.3.0 has requirement asgiref~=3.0, but you'll have asgiref 1.1.2 which is incompatible. ERROR: channels 2.2.0 has requirement asgiref~=3.0, but you'll have asgiref 1.1.2 which is incompatible. Based on that, I went on to install: pip install asgiref~=3.0 However, when I run the daphne line I again, I got: ERROR: asgi-redis 1.4.3 has requirement asgiref~=1.1.2, but you'll have asgiref 3.0.0 which is incompatible. It's my first time tampering with web servers, asynchronicity, and these more complex libraries, so does anyone know how I can fix this problem? The tutorial I am following is this one in case you need: https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django -
Reference ManyToMany Field in Django Model Method
I am attempting to reference the ManyToMany connection between Units and Add-Ons in my code to enable a method that provides the price, but I seem to be unable to reference the relationship in a Model method, can somebody point me in the right direction? class Unit(models.Model): class Meta: permissions = ( ('generate_unit_csv', 'can generate unit csv'), ) unique_together = ['building', 'unit_number', 'property'] add_ons = models.ManyToManyField( 'properties.RentalAddOns', related_name='add_on_units') ... def get_add_on_price(self): total_price = 0 # there is no self.add_on_units or self.add_ons for add_on in self.add_on_units: total_price += add_on.price return total_price When I call the method I get an Attribute Error: 'Unit' object has no attribute 'add_on_units' -
How can i filter between two models?
I have two models. One is a Partner. Another is Contact. Partner is the companys information. Contact is a contact for that company. How can I get a list of contacts from a company by comparing the name of the company to the foreign key partner which is who the contact belongs to. I have tried using querys but the result was not what i expected. class Partner(TimeStampedModel, StatusModel): name = models.CharField(blank=False, help_text="Name of the role or function", max_length=64, verbose_name="Partner Type", ) parent = models.ForeignKey( 'self', blank=True, help_text="Parent Company name (if necessary)", null=True, on_delete=models.CASCADE, max_length=200 ) class Contact(ContactModel, TimeStampedModel): partner = models.ForeignKey( Partner, blank=True, null=True, on_delete=models.SET_NULL, related_name="contacts",) What i want is a list of contacts belonging to that company. Lets say the company name is Shell. on The contact i would fill out the partner being shell. and i want to query all the partners shell has. -
How to use model one objects in model two in Django?
I have created a model that is used to create user using form. i want to use the objects of model one in model two in form to create new user id Models.py: class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Rooms(models.Model): name = models.CharField(max_length=200) room_num = models.IntegerField() def __str__(self): return str(self.name) class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.OneToOneField(Rooms,on_delete=models.CASCADE, blank=False) investigation = models.CharField(max_length=300) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,null = False) Forms.py: from .models import Patient,Ipd class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','investigation'] views.py: @login_required def ipd (request,patient_id): patient = Patient.objects.get(pk=patient_id) if request.POST: data = dict(request.POST) data['patient']=Patient.Patient_id formtwo = IpdForm(request.POST) if formtwo.is_valid(): if formtwo.save(): return redirect('/', messages.success(request, 'Patient is successfully updated.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: formtwo = IpdForm(request.POST) return render(request, 'newipd.html', {'form2':formtwo ,'form':patient}) I want to create new ipd_id using Patient Model and Ipd Model but I am ending with Invalid Form -
Setting DEBUG = False causes 500 Error in Django
I change the DEBUG = False in setting, my site generate 500 error code. I have tried all changes in my setting but still error 500. I'm using Django 2.1, Python 3.6 and Heroku Here is my setting file Setting file database Static, Root Path heroku logs --tail -
Filter cyclical relations
I have couple of models, Data, which contains different versions of some data and Master, which keeps track of all versions, and a current_version. Like this: class Master(models.Model): current_version = models.OneToOneField('Object', related_name='+') class Data(models.Model): master = models.ForeignKey('Master', related_name='data') I would like to get all instances of Data which are only a current_version of Master. As in: Data.objects.filter(Q(master__current_version=???)) How do I construct such a filter? -
How to write an if statement based on a request path
I know I can do the following to display the word "active" in a template using an if function to check the url vs the request.path: {% url 'dashboard' as dashboard %} {% if request.path == dashboard %}active{% endif %} How do I call the url object within the if statement? Eg: {% if request.path == url.dashboard %}active{% endif %} -
How to write a get endpoint returned data from file multiplied by parameters from query
I try to write a get endpoint for data from file. I also want to multiply data by parameters from query, unfortunately I get an error. Is there any way to avoid it? Error I get: AssertionError at /data/ 'DataView' should either include a serializer_class attribute, or override the get_serializer_class() method. # Views.py class DataView(ListAPIView): def get_queryset(self): mult = self.request.query_params.get('mult', None) y = np.loadtxt('media/data_vv.txt')[:10] x = list(range(len(y))) print(mult) if mult is not None: y *= float(mult) data = {'x': x, 'y': y} return data I want to avoid the error and get the data. -
Why is JS code in HTML file not working after adding type and src?
<script type='text/javascript'src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var forValue = $(this).attr('for'); if (forValue) { forValue = forValue.replace('-' + (total-1) + '-', '-' + total + '-'); $(this).attr({'for': forValue}); } }); total++; $('#id_' + prefix + '-TOTAL_FORMS').val(total); $(selector).after(newElement); var conditionRow = $('.form-row:not(:last)'); conditionRow.find('.btn.add-form-row') .removeClass('btn-success').addClass('btn-danger') .removeClass('add-form-row').addClass('remove-form-row') .html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>'); return false; } function deleteForm(prefix, btn) { var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); if (total > 1){ btn.closest('.form-row').remove(); var forms = $('.form-row'); $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length); for (var i=0, formCount=forms.length; i<formCount; i++) { $(forms.get(i)).find(':input').each(function() { updateElementIndex(this, prefix, i); }); } } return false; } $(document).on('click', '.add-form-row', function(e){ e.preventDefault(); cloneMore('.form-row:last', 'form'); return false; }); $(document).on('click', '.remove-form-row', function(e){ e.preventDefault(); deleteForm('form', $(this)); return false; }); I tried changing the script type and src … -
Django with DEBUG = True and django.contrib.staticfiles not finding static files
I am running Django with DEBUG = True and staticfiles in the INSTALLED_APPS. However my program is not finding the static files. I don't really want to do collectstatic... Is there any common reason why this may happen? -
When to start the google cloud profiler in a Django project?
I'm attempting to add the google cloud profiler to my Django App Engine project, and would like to know where the best place to call it is? Google Cloud Platform's documentation says to start the profiler as early as possible: You should call start one time, and as early as possible in your application. In a Django project, running on GCP App Engine Flex, where is the best place to call this so that 1. It is called only once, 2. It is not called on things like tests, migrations etc. My initial thought was to place it in manage.py under execute_from_command_line, but I realised that this would call the profiler for simple things like manage.py test. Django 2.2, App Engine Flexible, Gunicorn.