Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.10 converting question marks to percent signs in static file urls
I am upgrading Django from 1.7 to 1.10 in my project. All static files are loaded correctly. However, the ones with versions(or any other param) are not. The reason is that Django is converting question marks to % for some reason. Example: <script src="{% static 'dashboard/js/dashboard.js?v=1.11.0' %}"></script> is converted to /static/dashboard/js/dashboard.js%3Fv%3D1.11.0 Static files configuration: STATIC_URL = '/static/' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) What could be the reason? -
Display Django form fields on the "same line"
I would like to display two form fields on the same line and not each one after the other one. For the moment, I get : Choice a theme : . Datasystems . Cameroun But I would like to display this form like : Choice a theme : . Datasystems . Cameroun My .html file looks like : {% extends 'Base_Configurations.html' %} {% load staticfiles %} {% load static %} {% block title %} <h3> <span class="glyphicon glyphicon-file"></span> Choix du thème DatasystemsEC </align> </h3> {% endblock %} {% block content %} <form class="form" method='POST' action=''> {% csrf_token %} <br></br> {{ form }} <br></br> <input class="button" type="submit" value="Valider le thème" /> </form> {% endblock %} I have also a .css file : .form-fields { border-radius: 4px; margin-right: auto; width:50%; background-color: #f5f5f5; } .form { padding-left:8vw; } label { width: 35%; border-radius: 8px; margin-bottom: -20px; list-style: none; } For the moment, I don't find a way to solve my problem. I looked some tutorials or StackOverflow questions but nothing up to now. Do you have any idea about this handling ? -
passing form or its values to a function as the parameter
I have an html form, no Django forms (for some reason I don't want to use Django forms here). form method="GET" class="post-form" >{% csrf_token %} <label for="checkbox-2">1</label> <input id="checkbox-1" name="name_1" type="checkbox" > <label for="checkbox-2">2</label> <input id="checkbox-2" name="name_2" type="checkbox" > ... <input type="submit" id="qsrch" value="search"/> </form> The purpose of this form is to receive some input from the user and make a database query with the user input. In the views.py, I need to get the form (or all of the form's key-values) and send it to a function as its parameter - if such a thing is possible without the use of Django forms. There are so many fields in the form so I don't want to get the values by using request.GET['field_name']! Here's what the view is supposed to do: if request.method == 'GET': myform = #(get the form) #or formContents = #(get the form key/values) #pass myform or formContents to the function: search(myform) #or search(formContents) p.s. I'm not sure if I am supposed to use a GET or POST method for the <form>? Thanks in advance.. -
wagtail puput search not working as root site
We are having issues with a wagtail puput template. if we have the site as www.domain.com/blog the blog template works perfectly but the moment i make the template root www.domain.com/ the template works but we cant search correctly. I think that it something to do with this. action="{% routablepageurl blog_page "entries_search" %}"> www.domain.com/blog/ if in root action is action="/search/"> if as subfolder it www.domain.com/blog/ action="/blog/search/" (this works) for some reason the puput template does not like being root. Where am i going wrong here? -
how to automatic page break in long mixed html content
i have problem with my project when i need print long content. my project based on django framwork my content is mixed of table and etc ... my application should page break automatic when content is overfllow of my A4 page -
AttributeError: type object 'UserProfile' has no attribute 'objects'
I'm following documentation example about Inline formsets and have an error: 'UserProfile' has not attribute 'objects'. Why? Is there any alternative for getting this object from UserProfile? Please notice that I'm new to Django, so every explanation is welcome. My shell code: UserProfileFormSet = inlineformset_factory(User, UserProfile, fields=('city',)) city = UserProfile.objects.get(city='Salzburg') formset = UserProfileFormSet(instance=city) UserProfile from models.py: class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username -
Django Tastypie cascading Authorisations to relational objects
My problem is that updates to one tastypie resource seems to cascade to others that it has relations to. The authorisation on the foreign resource kicks in and makes the request return 401 UNAUTHORISED. However, if you do a GET the object I am trying to create, was created OK. I'm building a system which has an analogue of one where you can make a comment, and others can vote on your comment. You can edit (or delete) your own comments; but you can't vote yourself up. You can vote other comments up or remove your vote (i.e. post or delete), but you can't edit other people's comments. Simple enough? The issue occurs when I POST to the 'voter' resource. It always returns 401 UNAUTHORISED even though the 'voter' resource is successfully created. Here are the tastypie resources: class CommentaryEntryResource(ModelResource): user = fields.ForeignKey('decommentariis.api.resources.UserResource', 'user') voters = fields.ToManyField( 'decommentariis.api.resources.CommentaryEntryVoterResource', 'commentaryentryvoter_set', related_name='entry', null=True, full=True) class Meta: queryset = CommentaryEntry.objects.all() resource_name = 'sourcecommentary' list_allowed_methods = ['get', 'put', 'post', 'delete'] authentication = SessionAuthentication() authorization = UserObjectsUpdateOnlyReadAllAuthorization() filtering = { 'section': ALL_WITH_RELATIONS, 'user': ALL_WITH_RELATIONS, 'id': ALL, } class CommentaryEntryVoterResource(ModelResource): voter = fields.ForeignKey('decommentariis.api.resources.UserResource', 'user') entry = fields.ForeignKey(CommentaryEntryResource, 'entry', related_name='voters') class Meta: queryset = CommentaryEntryVoter.objects.all() resource_name = … -
How to use celery running task only once at a specific time?
I want to design a task queues in Django, the queues are ordered by a time tag with the task and the task will be executed only once at the specific time. So I want to use Celery to implement it. But what haunt me is that Celery only has the crontab ability which running tasks at every day, month, week, etc. So how to implelement the queue with Celery? -
JSON string parsing error in Python
I am sending a request to an API and it returns this JSON response '{"Reply":{"Header":{"Method":"mGSSCBetHistory","ErrorCode": "0","MerchantID":"BETSTARtest","MessageID": "H140201152657m6k3f"},"Param":{"TotalRecord":"1","BetDatas":"[{"Column1":""}]","ErrorDesc": ""}}}' when I try to convert it to dictionary whether ast.literal_eval or json.loads it returns this error: Traceback (most recent call last): File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/lib/python2.7/site-packages/celery/app/trace.py", line 367, in trace_task R = retval = fun(*args, **kwargs) File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/lib/python2.7/site-packages/celery/app/trace.py", line 622, in __protected_call__ return self.run(*args, **kwargs) File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/provider/KENO/tasks.py", line 127, in run ['Reply', 'Param', 'BetDatas'], 'post') File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/core/classes.py", line 217, in check_records self.result = response.json() File "/Users/deanchristianarmada/Desktop/projects/asian_gaming/radar/lib/python2.7/site-packages/requests/models.py", line 826, in json return complexjson.loads(self.text, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting ',' delimiter: line 1 column 169 (char 168) The reason for this is because of the value of the BetDatas which has a double quote inside a double quote.. Is there an easy workaround for this? Because the only proper solution that I can think of is to tell the third party that I've been sending request to change their JSON response. -
Python: Best IDE oft Text Editor Freeware to work with?
so, I know this is freequently asked. But im starting on Python and the focus is clearly on webdevelopment. So far, i've just been using pyCharm Edu, as it is free. But I don't want to get used to a tool only to find out that it isn't the right fit. Will the free Version of pyCharm also work for Webdevelopment (Django)? regards. -
Subclassing ModelForm
This question is about subclassing a ModelForm. I have a ModelForm like so: class ReplyForm(forms.ModelForm): description = forms.CharField(widget=forms.Textarea(attrs={'cols':30,'rows':2,'style':'width:98%;',\ 'class': 'cxl','autofocus': 'autofocus','autocomplete': 'off'})) class Meta: model = Reply exclude = ("submitted_by","answer_to","seen","submitted_on") fields = ("description",) def __init__(self,*args,**kwargs): self.user_id = kwargs.pop('user_id',None) super(ReplyForm, self).__init__(*args,**kwargs) def clean_description(self): description = self.cleaned_data.get("description") description = description.strip() if len(description) < 2: raise forms.ValidationError('write a longer reply') return description What's the best way to subclass it, given I solely want to override some attributes of the CharField description (autocomplete on, etc.) while keeping the clean method and relevant validation errors intact. Or would I have to write the clean method again? Should I just do: class ReplyMiniForm(ReplyForm): description = forms.CharField() def __init__(self,*args,**kwargs): self.user_id = kwargs.pop('user',None) super(ReplyMiniForm, self).__init__(*args,**kwargs) self.fields['description'].widget.attrs['autocomplete'] = 'on' Update: I checked the above code - works fine, except the validation errors aren't being shown on the template. I'm simply trying to access the same via {{ replyform.description.errors.0 }} -
How to Implement dynamic filters like Flipkart and Amazon?
I'm building a website on which I want to implement filters like Flipkart has. The checkbox options in other filters should change dynamically as I select something from 1 filter. I'm using mysql to manage my database. The entire platform is built on Django framework. So far I have only thought of building queries using python scripts. For every selection, all the other filters are sent an alert. Each filter would have a script associated with it that would help in building a relevant query. Then data would be fetched from mysql and options would be updated. Could anyone recommend a better and more efficient solution? -
Django error with heroku can't import something what to do now ooooo?
Problem with heroku django how to fix this? WITHOUT ENV for now/// why he can't import this? someone now why? (ideas) C:\Users\PANDEMIC\Desktop\ideas\src>heroku local web [WARN] No ENV file found 15:34:23 web.1 | Traceback (most recent call last): 15:34:23 web.1 | File "c:\users\pandemic\appdata\local\programs\python\python36-32\Lib\runpy.py", line 193, in _run_module_as_main 15:34:23 web.1 | "__main__", mod_spec) 15:34:23 web.1 | File "c:\users\pandemic\appdata\local\programs\python\python36-32\Lib\runpy.py", line 85, in _run_code 15:34:23 web.1 | exec(code, run_globals) 15:34:23 web.1 | File "C:\Users\PANDEMIC\Desktop\ideas\Scripts\gunicorn.exe\__main__.py", line 5, in <module> 15:34:23 web.1 | File "c:\users\pandemic\desktop\ideas\lib\site-packages\gunicorn\app\wsgiapp.py", line 10, in <module> 15:34:23 web.1 | from gunicorn.app.base import Application 15:34:23 web.1 | File "c:\users\pandemic\desktop\ideas\lib\site-packages\gunicorn\app\base.py", line 12, in <module> 15:34:23 web.1 | from gunicorn import util 15:34:23 web.1 | File "c:\users\pandemic\desktop\ideas\lib\site-packages\gunicorn\util.py", line 9, in <module> 15:34:23 web.1 | import fcntl 15:34:23 web.1 | ModuleNotFoundError: No module named 'fcntl' [DONE] Killing all processes with signal null 15:34:23 web.1 Exited with exit code 1 -
best practice for custom authentication api in django
I want to make custom authentication api for my app in django. I do not want to use REST framework. Registering a user seems bit easy but what might be the best approach to handle login and logout ? For now, I am registering a user and creating a access token in a model attached to the user. I would like to know the correct way or approach for custom api for authentication Thanks in advance ? -
Django: defining a generic manager in an Abstract model
Using the following code and defining suitable NATURAL_KEY per every class fails (instead of defining different mangers in every class, which replicate the same code): class NexchangeManager(models.Manager): def get_by_natural_key(self, param): if param == "*": return self.all() lookup = {self.NATURAL_KEY: param} return self.get(**lookup) class NexchangeModel(models.Model): class Meta: abstract = True objects = NexchangeManager() Djagno complains about fields replication, although NexhcnageModel is an Abstract model. Should I use a mixin instead? -
Django Registraion redux how to override auth\views.py function
I want to override the Django Redux auth\views.py function to create my custom validations in my django app? -
(django) static file for the whole project
When I use {% load static %} and then add an image like this to my template: <img src="{% static 'logo.png' %}"> I only get the image if it's stored in a direction called static which is in the same app. But I want to use the logo for the whole project, and, also in a template for the whole project. It doesn't work when the image is stored in a static direction which is in the inner project folder. How do I use static files for the whole project? And how to acces them from the template? (I'm a hobby developper and so not in production ;-)) My settings are nearly the one they were when I created the project. (I only added some additional template direction.) Thank you for reading this -
Fill ManyToMany field automatically with data from other M2M fields
I have Project model with ManyToMany fields like 'members', 'managers' and 'developers'. I want to make every manager and developer be a member of the project. In other words, I'm trying to make "members" field automatically filled with data from other fields like 'managers' and 'developers'. What the best way to realise it and fix this error? Thats what I am tring right now and have next error below when try to create new project in admin. ERROR: TypeError: str returned non-string (type proxy) models.py class Project(models.Model): *** managers = models.ManyToManyField(User, related_name='managers') developers = models.ManyToManyField(User, related_name='developers') members = models.ManyToManyField(User, related_name="members") admin.py class ProjectAdminForm(ModelForm): class Meta: model = Project fields = ('members', 'managers', 'developers') def clean(self): members = list(self.cleaned_data['members']) managers = list(self.cleaned_data['managers']) developers = list(self.cleaned_data['developers']) for manager in managers: if manager not in members: members.append(manager) for developer in developers: if developer not in members: members.append(developer) return self.cleaned_data class ProjectAdmin(admin.ModelAdmin): model = Project form = ProjectAdminForm admin.site.register(Project, ProjectAdmin) -
Date picker is not loading while handling the request on 2 different domains
I am working as django developer where our website is running between 2 different domains between larvel-php and django-python. The first request is from larvel is calling django URL through ajax and on success of ajax request they are reinitializing the datepicker script, so its working in python form. Now i want to set ajax request to update a form with different data, so i written ajax i reinitializing datepicker which was in larvel template. Its not working in 2 form. How to solve this issue? -
How to provide an extra argument to model constructor (or make a non-saved field)?
I'm trying to pass an extra (non-stored) parameter to the model constructor, from which I expect to calculate the value of a stored field. Here's what I tried: class Party(models.Model): # ... invitee_hash = models.CharField(max_length=16, editable=False) def __init__(self, *args, **kwargs): print("INIT IS INVOKED") invitee_names = kwargs.pop('invitee_names', False) if invitee_names: self.invitee_hash = calculate_invitee_hash(invitee_names) super(Patry, self).__init__(*args, **kwargs) Now I would have thought that this should allow me to do this: Party(..., invitee_hash=['Alice', 'Bob']) However, I find that my __init__ is not even invoked (as seen, or rather not seen, from the standard output), and I get this message instead: ... Party(..., invitee_hash=['Alice', 'Bob']) File "/usr/local/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py", line 473, in get_or_create return self.get(**lookup), False File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py", line 376, in get clone = self.filter(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py", line 796, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py", line 814, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1227, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1253, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1133, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1019, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1327, in names_to_path "Choices are: %s" … -
How do I tell django "{% if request.get_full_path|stringify *ends in a number* %}"?
Trying to make an if statement in my template. How do I tell django {% if request.get_full_path|stringify *ends in a number* %}? So the get_full_path string would be something like /news/324/. This should equal to True in the if statement. {% else %} would be a string with just: /news/ Any idea if I can do this? -
Creating django models in the right way
I have django models as follows : class Type(models.Model): limit = models.IntegerField() name = models.CharField(max_length=50) default = models.BooleanField() def __str__(self): return self.name class Subscription(models.Model): started = models.DateField() type = models.OneToOneField(Type) def __str__(self): return self.type.name class Member(models.Model): user = models.ForeignKey(to=User) number = models.CharField(max_length=10) address = models.CharField(max_length=255) postcode = models.CharField(max_length=10) city = models.CharField(max_length=100) active = models.BooleanField() subscription = models.OneToOneField(Subscription, on_delete=models.CASCADE) def __str__(self): return self.name Thus, member and subscription need to be OneToOneField relation, and subscription and type also OneToOneField relation. But I want that member gets subscription of type default=true, if he creates a new account. This is maybe not the question like is should be, but however, I want to hear advice. Thanks. -
NameError (form not defined) although it is correctly imported from forms.py
While performing a POST request, I'm consistently getting a NameError that my form (ReplyForm)is not defined, although I'm explicitly importing it from the forms module. Here's how my code is laid out: Template code (simplified): {% for comment in object_list %} {% with replyforms|get_item:comment.id as replyform %} <form method="post" action="{% url 'process_reply' pk=comment.id %}"> {% csrf_token %} {{ replyform.description }}<br> <button type="submit">Submit</button> </form> {% endwith %} {% endfor %} View code (simplified): from .forms import ReplyForm, ParentPostForm @csrf_protect def process_reply(request, pk=None,*args,**kwargs): if request.method == 'POST': form = ReplyForm(data=request.POST,user=request.user) if form.is_valid(): # do something else: # do something else else: return redirect("show_comments") def show_comments(request,*args,**kwargs): form = ParentPostForm() page_num = request.GET.get('page', '1') page_obj = get_page_obj(page_num,link_objs,COMMENTS_PER_PAGE) list_of_dictionaries = retrieve_home_links(page_obj.object_list) replyforms = {} for obj in list_of_dictionaries: replyforms[obj['l']] = ReplyForm() context={'form':form,'replyforms':replyforms,'page':page_obj,'object_list': list_of_dictionaries, return render(request,"show_comments.html",context) In case you feel I've missed something, do ask for more information. I might have flubbed something while simplifying my code for the question. -
Django Ajax Form Error - TypeError: the JSON object must be str, not 'bytes'
I have a newsletter signup form that sends data to AgileCRM.com and creates a new contact. The form partly works; it creates the new contact in Agile, but doesn't send the EmailMessage notification and I get the TypeError: the JSON object must be str, not 'bytes' error in console. There are more than a few SO posts on the subject, but I have no idea how to apply the fix to my situation. Ajax let fields = { first_name: 'null', last_name: 'null', phone_number: 'null', email_address: 'null', }; // Footer Form $('#footerFormBTN').click(function (e) { console.log("create post is working!"); e.preventDefault(); fields.first_name = $('#id_first_name').val(); fields.last_name = $('#id_last_name').val(); fields.phone_number = $('#id_phone_number').val(); fields.email_address = $('#id_email_address').val(); $('#loader').show(); $.ajax({ type: "POST", url: $('#footerForm').attr('action'), data: { csrfmiddlewaretoken: getCookie('csrftoken'), first_name: fields.first_name, last_name: fields.last_name, phone_number: fields.phone_number, email_address: fields.email_address, }, cache: false, success: function (data) { $('#id_first_name, #id_last_name, #id_phone_number, #id_email_address').val(''); $('#loader').hide(); $("#order_message").html('<div class="alert alert-success"><button type="button" class="close">×</button>Thank you for joining.</div>'); window.setTimeout(function () { $(".alert").fadeTo(500, 0).slideUp(500, function () { $(this).remove(); }); }, 3000); console.log(data) }, error: function (jqXHR, textStatus, errorThrown) { $('#id_first_name, #id_last_name, #id_phone_number, #id_email_address').val(''); $('#loader').hide(); console.log(jqXHR); console.log(errorThrown); } }); e.preventDefault(); }); View def footer_form(request): if request.method == "POST": form = FooterForm(request.POST or None) if form.is_valid(): first_name = form.cleaned_data.get('first_name', '') last_name = form.cleaned_data.get('last_name', … -
json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig)
So my goal is to find a name of a country using its ISO Alpha-2 country code. I figured this would be a good time to try out a RESTful API (the World Bank API to be exact) for the first time. I started to use this tutorial in trying to achieve my goal and it seems like requests.get() is the answer to my problem, I tried it out and got this: (InteractiveConsole) >>> import requests >>> resp = requests.get('http://api.worldbank.org/countries/br') >>> resp <Response [200]> >>> resp.json() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\requests\models.py", line 866, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\json\__init__.py", line 315, in loads s, 0) json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0) I'm not really sure what went wrong or what it's telling me to do (I'm not that familiar with JSON). Any explanations to this and how to fix it? I am using: Windows 7 64-bit Python 3.5.1 Django 1.10 requests package 2.13.0