Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access to file uploaded with FileField Django
I'm trying to create a Django form with a filefield to upload a pdf based on a model. #models.py class ProductionRequest(models.Model): ... contract_file = models.FileField('Contract file (PDF)', upload_to='contracts/') ... I can upload the file and save it in my object, but when I try to show the file in my template with this code {{ prod_req.contract_file }} it only show me the path to the file "contracts/file_uploaded.pdf". How can I make a link to download (or open in a new tab ) the file ? Plus : when I try to open the file from Django admin, with this link Contract file (PDF) : Currently: contracts/file_uploaded.pdf I don't show me the file, i got this : Page not found (404) Request URL: http://127.0.0.1:8000/admin/appname/productionrequest/1/change/contracts/file_uploaded.pdf/change/ How can I access to my file ? -
Heroku + GA, wrong city
I have Django app deployed on Heroku. When I analyse data on Google Analytics and use city dimension, I see a lot entries with "Ashburn" city. When I made a research, I found out this: Server info - Heroku.com Where is heroku.com hosted? IP: 54.243.150.141 Binary IP: 110010100001001001001100100100111101 Octal IP: 624111144475 Hexadecimal IP: ca124c93d Decimal domain: 110101 Registrar: MarkMonitor Inc. Country: United States City: Ashburn Latitude: 39.043701171875 Longitude: -77.487503051758 So as I understand Heroku passes its server location to GA. How I can get real user location? -
Javascript vs Python Django for web development
For a beginner who wants to start learning web development. What is the differences between Javascript and Python Django. I have a good background in Python. The main question is: can I do everything with Python Django or I may need Javascript later ? Which one should I start with? Thanks! -
Filtering django rest framework query set using a custom filter backend
I'm having problems with filtering the query set. Here is a simplified data model: Entry - id - broadcast_groups User - id - groups So an entry can be broadcasted (shared) in a group. I have a GET /entries/ endpoint that returns entry objects. I want to filter a query set to return entries that fulfill following requirements: are not broadcasted in any group OR are broadcasted in groups the user is member of. I'm scratching my head how to achieve this. I figured that maybe writing a custom FilterBackend is a good idea. Here is what I have so far: class CanViewPublicOrGroupMemberEntriesFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): user = request.user return queryset.filter(broadcast_groups__in=user.groups.all()) However, this does not yield results that I am expecting. What would be a filter() syntax to achieve such filtering? Or maybe I'm approaching the problem from the wrong side? -
How to call specific textfield from model in templatetag?
Sorry if this question is very noobish but I have only been learning Python/Django for a month. I have Googled and searched on Stack Overflow for hours now but can't find a solution to my problem. I am basically trying to parse a URL from a TextField and then present it in a template. So far I have: models.py class Thing(models.Model): youtube_link = models.TextField(blank=True, null=True) I created templatetags/embeds.py with the following code: from django import template from urllib.parse import urlparse register = template.Library() from ..models import Thing @register.simple_tag def youtube_parse(): ytparse = urlparse('https://www.youtube.com/watch?v=bnKaOo67mLQ') # URL test return yt_parse And in my html template: {% load embeds %} {% youtube_parse %} So far so good. The template shows the parsed URL (although it's not very pretty yet). But what I am having trouble with is calling the field "youtube_link" from the model Thing in embed.py. Basically I want embed.py to do this: ytparse = urlparse(Get youtube_link from model Thing and parse it) But I have problems calling youtube_link. I have tried Thing.youtube_link and many other code snippets that I found after Googling for a while, but nothing seems to work. What am I missing? -
Django Crispy form set model feild as required
i have a modelform in which i want to set required attribute to True for email validation field:-email class RegisterMyBuisinessForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = '/registermybuisness/' Field('email', type='email') self.helper.add_input(Submit('submit', 'Submit',css_class="btn c-theme-btn c-btn-square c-btn-bold c-btn-uppercase")) super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs) class Meta: model = RegistermyBusiness fields = ['name','email', 'org_name', 'contact','business_description','store_address','message','store_landmark','business_type','city'] i tried self.fields['email'].required=True this resulted in class RegisterMyBuisinessForm doesnot have fields error -
How to add Fields to the forms in Django through JavaScript
I'm trying to make a to-do list kinda app and want to add Fields to the the form through JavaScript NOTE - I don't wanna use formsets -
How to convert nested JSON object to Python in Django
I'm working on a Django application that posts data to the server. Here is the Python snippet: def save(request): if request.method != 'POST': return HttpResponse('Illegal Request') print(request.POST.get('dataObj')) return JsonResponse({'status':200}) JQuery on the client side: function submitQuoationClicked() { dataObj = getQuotationInJSON() console.log(dataObj) token = $("input[name=csrfmiddlewaretoken]").val() $.ajax({ type:"POST", url:"/quotations/save", data: { 'csrfmiddlewaretoken': token, 'dataObj' : dataObj, }, success: function(data){ if(data.status === 200) console.log("Good Work Falak!") //TODO Remove this line, FOR DEBUGGING ONLY } }); function getQuotationInJSON() { var data = {}; data['title'] = $("#title").val() data['companyName'] = $("#company").val() data['addressLine1'] = $("#addressLine1").val() data['addressLine2'] = $("#addressLine2").val() data['city'] = $("#city").val() data['country'] = $("#country").val() data['date'] = $("#date").val() data['number'] = $("#number").val() data['validTill'] = $("#validTill").val() sections = getItemsData(); data['sections'] = sections return data } function getItemsData() { sections = [] $("tr[id^='section']").each(function(index, element) { sectionId = $(element).attr('id').split('section')[1] name = $(element).find("#sectionName" + sectionId).val() section = {} section['name'] = name //Now get section items rowElems = $(".section" + sectionId) rows = [] $(rowElems).each(function(index, row){ if($(row).attr('id').indexOf('itemRow')>=0) { description = $(row).find("#description").val() quantity = $(row).find("#quantity").val() unitPrice = $(row).find("#unitPrice").val() margin = $(row).find("#margin").val() if(quantity!="" && unitPrice!="" && description!="" && margin!="") { row = {} row['description'] = description row['quantity'] = quantity row['unitPrice'] = unitPrice row['margin'] = margin rows.push(row) } } }); section['items'] = rows; sections.push(section) }); return sections … -
get_context_data - self.request.user with domain?
I'm attempting to use a simple view in Django that ties my username as a formatted username with the Domain\ prior to my username. I.E. (Domain\UserName). Below is the view that i've defined, but when I attempt to link my model with the view. I can hard code the domain since it will never change, but is there a way to just pull Domain\UserName? def applicationdetail(request, ntname, report_id): user = get_object_or_404(User, pk=self.request.user) applicationlist = QvReportList.objects.all(report_id=report_id) applicationaccess = QVReportAccess.objects.filter(ntname=ntname) context = {'user' : request.user, 'applicationdetail' : applicationaccess} return render(request, 'accounts/profile.html', context=context) -
Django UpdateView form with multiplechoicefield going to form in_valid when posted without selecting the multiple choice field?
I have a update view for my model and this model has a many to many relation with another model. Due to some filtering requirements I created a custom multiplechoicefield and am saving it by modifying the form_valid. But if this multiple choice field is not selected form is getting posted to form_invalid. This field is not required. My view and form look as follows: class Updatemodel(UpdateView): template_name = ... def get_success_url(self): return .. def get_from_class(self): .. .. def form_valid(self,form): kwargs = super(Updatemodel, self).get_form_kwargs() m2m_initial = kwargs['instance'].model_m2m.filter( .. ) chosen_m2m = model_m2m.objects.filter(pk__in = form.cleaned_data.get('model_m2m')) m2m_add = chosen_m2m.exclude(pk__in = m2m_initial.values_list('pk, flat = True)) m2m_remove = m2m_initial.exclude(pk__in = chosen_m2m.values_list('pk,flat = True)) form.instance.model_m2m.add(*m2m_add) form.instance.model_m2m.remove(*m2m_remove) return super(Updatemodel, self).form_valid(form) def get_form_kwargs(self): kwargs = super(Updatemodel, self).get_form_kwargs() kwargs['m2m_initial'] = kwargs['instance'].model_m2m.filter( ..) kwargs['m2m'] = model_m2m.objects.all().filter( .. ) .................. form ...................... class m2m_update_form(forms.ModelForm): def __init__(self, *args, **kwargs): m2m = kwargs.pop('m2m',None) m2m_initial = kwargs.pop('m2m_initial',None) super(m2m_update_form, self).__init__(*args, **kwargs) choices = [(M2M.pk, M2M.Name) for M2M in m2m ] self.fields['m2m_field'] = forms.MultipleChoiceField(choices = choices, widget = FilteredSelectMultiple("M2M", False, choices = choices)) self.initial['m2m_field'] = [M2M for M2M in m2m_initial] class Media: .. class Meta: model = model1 fields = ['field1', 'field2','field3'] widgets = { 'field3' = FilteredSelectMultiple("Field", False), } -
How correctly handle 2 forms on one page with NOT clearing one form handling other
I'm trying to create temlate with PhotoForm for Profile.image and ProfileForm for other Profile data. I found lots of answers how to handle 2 forms on one temlate, also found how to clear data when form is submitted, but I'm trying NOT to clear data of ProfileForm when PhotoForm is submitted. Here is my template( deleted all style staff to show the object of the question): <form method='post' enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ image_form }} <button type="submit" class="js-crop-and-upload" name="crop">Crop</button> </form> <!--container for uploaded image --> <form method='post'> {{ profile_form.as_p }} {% csrf_token %} <button type="submit" class="btn" name="save_profile">Submit</button> </form> And here is my view: @login_required def profile_new(request): if Profile.objects.filter(user=request.user): return redirect('profile_edit') created_image = Photo.objects.filter(created_by=request.user) if request.method != "POST": profile_form = ProfileForm() image_form = PhotoForm() return render(request, 'personal_page_platform/edit_profile.html', { 'profile_form': profile_form, 'image_form': image_form, 'title': 'New profile', }) if request.method == 'POST' and 'crop' in request.POST: profile_form = ProfileForm(request.POST) image_form = PhotoForm(request.POST, request.FILES) if not image_form.is_valid(): return render(request, 'personal_page_platform/edit_profile.html', { 'profile_form': profile_form, 'image_form': image_form, 'title': 'New profile', 'created_image':created_image }) created_image = image_form.save(request=request) return render(request, 'personal_page_platform/edit_profile.html', { 'profile_form': profile_form, 'image_form': image_form, 'title': 'New profile', 'created_image':created_image }) if request.method == 'POST' and 'save_profile' in request.POST: profile_form = ProfileForm(request.POST) image_form = PhotoForm() if not profile_form.is_valid(): … -
DJANGO app loose path from batch file
I try to learn more about Django celery and rabbitmq to create some async tasks and I have some question. Some programs can provide PYTHON API to can some development to use modules from this program in python. one most way to take that PYTHON API from this program is to use batch file like this : @echo off SET PROGRAM_ROOT=C:\main-folder call "%PROGRAM_ROOT%"\bin\some-batch-file.bat SET PYCHARM="C:\Program Files\JetBrains\PyCharm 2017.1.5\bin\pycharm64.exe" set PYTHONPATH=%PYTHONPATH%;%PROGRAM_ROOT%\python; set PYTHONPATH=%PYTHONPATH%;%PROGRAM_ROOT%\site-packages; start "PyCharm aware of PROGRAM" /B %PYCHARM% %* if I run this batch file can I use all imports and modules from this program. that to release if add celery in my app and broker url rabbitmq server then if i use some module or some import from this python api then I take error message : no module name some_module_from_program (for all other modules celery and rabbitmq app work fine). that mean in celery and rabbitmq server loose that paths from batch file and I take this error. my question how to can define rabbitmq server to start server with that paths like batch file before to avoid this error? -
Should I constantly use Django select_related and prefetch_related?
Should I constantly use Django select_related or prefetch_related every time when use models with OneToMany relations? Should I use it if I have multiple Foreign keys? class A(models.Model): pass class B(models.Model): pass class C(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) # example usage for entry in C.all().select_related('a').select_related('b'): pass -
Celery, Django and S3 Default Storage causes file reading issues
I have a process whereby a webserver injests a file (via an upload), saves that file to S3 using default_storages, then creates a task for that file to be processed by the backend via celery. def upload_file(request): path = 'uploads/my_file.csv' with default_storage.open(path, 'w') as file: file.write(request.FILES['upload'].read().decode('utf-8-sig')) process_upload.delay(path) return HttpResponse() @shared_task def process_upload(path): with default_storage.open(path, 'r') as file: dialect = csv.Sniffer().sniff(file.read(1024])) file.seek(0) reader = csv.DictReader(content, dialect=dialect) for row in reader: # etc... The problem is that, although I'm using text-mode explicitely on write and read, when I read the file it comes through as bytes, which the csv library cannot handle. Is there any way around this without reading in and decoding the whole file in memory? -
Django 1.7.11 :render_to_string() got an unexpected keyword argument 'context'
There are a few related questions, such as this one, but the answers do not appear to work. I have the following in my views.py def pilab(request): return render(request, 'pilab.html',{'foo':'bar'}) Running this and going to it's corresponding url returns the following error: Traceback: File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data_nfs/opensurfaces2/server/home/views.py" in pilab 31. return render(request, 'pilab.html',{'foo':'bar'}) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/shortcuts.py" in render 50. return HttpResponse(loader.render_to_string(*args, **kwargs), Exception Type: TypeError at /pilab/ Exception Value: render_to_string() got an unexpected keyword argument 'context' Strangly enough, removing the context string returns virtually the same error: Traceback: File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data_nfs/opensurfaces2/server/home/views.py" in pilab 31. return render(request, 'pilab.html') File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/shortcuts.py" in render 50. return HttpResponse(loader.render_to_string(*args, **kwargs), Exception Type: TypeError at /pilab/ Exception Value: render_to_string() got an unexpected keyword argument 'context' How can this error be fixed? -
django formset with initial values from an iterator
I'm trying to generate a formset through the inlineformset_factory, with a initializing a field with a value from a (cycling) iterator. !pseudo code <form> <field foo/> <field bar/> <formset> <row> <field "day of week" value="MON"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="TUE"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="WED"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="THU"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="FRI"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="SAT"/> <field "formset_foo"/> <field "formset_bar"/> </row> <row> <field "day of week" value="SUN"/> <field "formset_foo"/> <field "formset_bar"/> </row> </formset> <submit button/> </form> Basically, I ld like to initialize each rows of the formset with a different value, values are taken from a choices list, this list is passed to the formset field widget. I've tryed some different ways with this, mainly from http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset, adapting it with cycle as iterator function on my choices list. WORKING_DAY_CHOICES = (('MON', _('Monday')), ('TUE', _('Tuesday')), ('WED', _('Wednesday')), ('THU', _('Thursday')), ('FRI', _('Friday')), ('SAT', _('Saturday')), ('SUN', _('Sunday')),) days_iterator = cycle(WORKING_DAY_CHOICES) My problem is that I've to be sure the FIRST element of my choices list is called by the … -
Finding all objects that have the same type object in a ManyToMany relationship
I have a model that has a ManyToMany relationship with itself (a "following" list). I can pull the list of people any particular person is following (i.e. obj.following.all() ), but I am trying to figure out how to get a list of objects that contain this particular object within THEIR following list. In other words, I have a following list, and now I want to parse a followers list. -
Django models, set unqiue attribute for M2M field per object
Currently, have a database with an Item table and a Stock table. There is a many to many relationship between the two. A single item object can have many sizes. The next step is to assign an 'inStock' options to the item per size. Any thoughts on acheiving this? Current models.py class Stock(models.Model): size = models.CharField(max_length=30) stock = models.BooleanField(default=False) def __str__(self): return self.size class Item(models.Model): title = models.CharField(max_length=250, null=True, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) aw_product_id = models.CharField(max_length=11, null=True) # Removed because multiple products has similar identifer url = models.URLField(max_length=250) # Removed 'unique=True'as the aw_prod_id will throw an integrity error image = models.CharField(max_length=1000) retailer = models.CharField(max_length=250) category = models.CharField(max_length=100) featured = models.CharField(max_length=10, default='NO') gender = models.CharField(max_length=100, null=True) sizes = models.ManyToManyField(Stock) uniq_id = models.CharField(max_length=11, null=True, unique=True) # Removed because multiple products has similar identifer def __str__(self): return self.title -
Python server-agent application design with sockets or maybe REST?
I am currently trying to design a bit complex Python project that would consist of muliple applications/scripts. First, a central engine (server) that receives data from multiple remote and/or local agents, at the time when they process some tasks. The engine would be constantly connected with a database on the host, where the information about all remote tasks is stored. Plus, additional tools (like desktop client for the server or a web application) could connect to the engine or db to show current situation of the whole infrastructure. At first, I thought of using multi-threaded sockets, which I am going to discover more deeply. However, I have also come across the idea of REST API. Since I am fairly new to both of these subjects and I am still trying to find the right solution that would suit my project, what would be your opinion on using a REST API framework in such case? REST provides extra solutions in terms of security and it would be really flexible for the engine, database and mention tools to operate with. While with sockets, I would have to get known with a lot of network concepts i.e. how to utilize sockets in the … -
Django many-to-many reverse of the same model?
Is it possible to get the reverse of a django many-to-many of the same model? For example, I have a product that is called Product Range of XY that is part of Product Range X and Product Range Y. So far I have the following: model.py class HeadwallRange(Product, ContentTyped): child_ranges = models.ManyToManyField("HeadwallRange", blank=True, related_name="child_range_products") views.py range = HeadwallRange.objects.filter(child_range_products = page.id).first() I can go in the "normal" direction (i.e from Product Range X I can get Product Range XY) but given Product Range XY is there any way to get Product Range X? -
Django transaction atomic not save commit on exception
I have a function where I want to save some data in one transaction, but log messages i want to save directly with autocommit. I wrote this code: @transaction.atomic def sync_transactions(): wm_log = WMLog.objects.get(pk=1) wm_log.create_message(message='Test') sid = transaction.savepoint() try: with transaction.atomic(): some_func_with_creating_updating_objects() raise Exception('my test eception') except Exception as e: print(sid) transaction.savepoint_commit(sid) raise e create_message method: def create_message(self, message): wm_log_message = WMLogMessage.objects.create( wm_log=self, message=message ) wm_log_message.save() return wm_log_message But my log messages not created. I also tried savepoints, not helped. -
Django form as table td with readonly fields
I want to display all objects for model in a form with information as readonly fields in a table, with each field as a cell of the table. Currently I can render a table like I want like this... <form action="" method="POST">{% csrf_token %} <table> <thead> <tr> <th>Record</th> <th>Date</th> <th>Comment</th> <th colspan="2">Attached</th> </tr> </thead> {% for record in schedule_projects %} <tr> <td>{{record.projectname}}</td> <td>{{record.date_edited|date:"d-m-Y H:i"}}</td> <td>{% if record.project_details %}{{record.project_details}}{% else %}{%endif%}</td> <td>{{record.attached_files|default_if_none:'0'}}</td> <td><input type="checkbox" name="record" value="{{record.plan_delete}}"></td> </tr> {% endfor %} </table> <button type="submit" name="plan_delete">Add to delete schedule</button> Instead of doing it manually, I wanted to do it with ModelForm. I want the form to render each field without a label, and as readonly text fields, not as input fields. I also want the records that have the boolean field plan_delete=True to be activated with a tick if the value is true in the initial form, so that I can add more records with the plan_delete boolean in the view if the form is submitted. I've tried playing around with form as_table, and modelform, but it seems that something so simple gets really complicated quite quickly. So my question is, is my way the 'best' way to do it - or am … -
Show object ID (primary key) in Django admin object page
Assuming I have the following model.py: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, unique=True) I register this model in the admin.py using: admin.site.register(Book) When viewing an existing Book in admin, only the name field is visible. My question is: Can the ID also be visible in this page? Most of the answers I find are related to the admin list rather than the object instance page. One way to show the ID field is to make it editable by removing editable=False from the model definition. However, I would like to keep it read-only. -
Applying bootstrap to django forms not working on all fields
Applying widgets to class Meta in forms.py is not applying widgets to all fields in form The form is inherited from UserCreationForm. Fields like username, first_name, and last_name are getting styled by widgets but email, password1, and password2 are not getting styled. forms.py from django import forms from django.forms import TextInput, PasswordInput, EmailInput from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class SignupForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) widgets = { 'username': TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}), 'first_name': TextInput(attrs={'class': 'form-control'}), 'last_name': TextInput(attrs={'class': 'form-control'}), 'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Address'}), 'password1': PasswordInput(attrs={'class': 'form-control'}), 'password2': PasswordInput(attrs={'class': 'form-control'}), } def save(self, commit=True): user = super(SignupForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user Signup.html <form class="form-signin" method="post"><span class="reauth-email"> </span> {% csrf_token %} {{form.as_p}} <button class="btn btn-primary btn-block btn-lg btn-signin" type="submit">Register</button> </form> -
Mathjax in django-template renders all of text .
I am building a quiz website in django which includes some mathematical word problems. example Simplify (14.2)²+ (16.4)² − (17.9)² = ? + 32.99 And I am using mathjax to render math in templates, the problem is it's not responsive and "Simplify" or any other text with math equations is also converted by mathjax beacause of a query like this $$ {{question}} $$ which includes the whole text and math from database .Now because of this, normal english text is also distorted and math is not responsive. I have tried linebreaks and other CONFIG variables in mathjax but it's not solving the problem. So is there a way to render only math and not other text with it and also make it responsive ? Thanks.