Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ratelimit vs Django throttling
What are the differences between Ratelimit and throttling? Does AnonRateThrottle block calls based on IP addresses or just blocks the url for all IP Addresses based on the rate? Is there a benifit of using one over the other? -
Django alias redirect on wrong url to the correct url
The question may have been asked many times, but I couldn't find something about this which is a basic stuff to do. I have a problem with my website one of the sub urls of google search redirects to the wrong page. Here are the urls : www.example.com/login/user/ #wrong url www.example.com/accounts/login/ #correct url urls.py : url(r'^accounts/login/$', auth_views.login, name='login'), I'd like the user to be redirected to the correct url if he access the wrong one. I know that it is possible to do that with views using redirect(reverse('...')) but doing it just for this purpose doesn't sound like the best way. Is there a way to redirect an user when he enters a wrong url to another one only by using urls.py ? -
How to serialize a self recursive many-to-many model using a through table in django rest_framework?
i am developing a rest API using django rest framework and i am stuck at a serializer the idea is to serialize a self recursive many to many model using a through table my code is: model.py: class Patient(models.Model): class Meta: db_table = 'patients' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) id_card = models.CharField(max_length=45) dob = models.DateField() gender = EnumChoiceField(enum_class=Gender) patientscol = models.CharField(max_length=45) fk_user = models.ForeignKey(Users, related_name='user_patient', on_delete=models.CASCADE) relative = models.ManyToManyField("self", through='PatientHasRelative') class PatientHasRelative(models.Model): class Meta: db_table = 'patients_has_relatives' fk_patient = models.ForeignKey(Patient, related_name='patient_has', on_delete=models.CASCADE) fk_relative_patient = models.ForeignKey(Patient, related_name='patient_relative', on_delete=models.CASCADE) relationship = EnumChoiceField(enum_class=Relationship) my serializer.py is: class PatientSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = ('__all__') id = serializers.UUIDField(read_only=True) id_card = serializers.CharField(required=True, max_length=45) dob = serializers.DateField(required=True) gender = EnumChoiceField(enum_class=Gender) fk_user = serializers.PrimaryKeyRelatedField(required=True, queryset=Users.objects.all()) relative = PatientSerializer(read_only=True, required=True)#problem is here i cant use PatientSerializer here class PatientHasRelativeSerializer(serializers.ModelSerializer): class Meta: model = PatientHasRelative fields = ('__all__') fk_patient = serializers.PrimaryKeyRelatedField(required=True, queryset=Patient.objects.all()) fk_relative_patient = serializers.PrimaryKeyRelatedField(required=True, queryset=Patient.objects.all()) relationship = EnumChoiceField(enum_class=Relationship) a little help would be appreciated -
Django models - html/render attribute?
I use the same models in many different templates and tables. I'm looking for a way to tell Django how to render those objects in templates so I don't have to write the same html again and again. For example model Url - when I want to display it inside a template or table, I have to write (sometimes much more): <a href="{{ url.url }}">{{ url.site.name }}</a> which renders: <a href="http://stackoverflow.com/questions/ask">Stackoverflow.com</a> It would be better if I could just do something like: {{ url }} # url is Url model object I think that I can add methods like def render_object(self) like this: def render_object(self): return mark_safe("""<a href="{}">{}</a>""".format(self.url,self.site.name)) and in templates: {{ url.render_object }} but I'm curious if it is there some built in function. As far as I know __unicode__(self) would do the work but it would mess admin and shell display names. -
How to use Django Ratelimit with generics.ListAPIView?
I want to use Django Ratelimit to limit the number of calls to a view. I am using generics.ListAPIView for a view; Is there a way to use Ratelimit with generics? -
Drawing meteorological maps in python
I found a user friendly way plotiing meteorological maps with python. I found this flight path tool, http://www.aviationweather.gov/flightpath2?gis=off , and i want to make something like this in python. I have made the scripts retrieving the data and plotting the maps but i want to make the interface. Is it difficult? Do you have any ideas? -
Cache._cache.flush_all () not working, How can I clear the cache with django and memcached?
Cache._cache.flush_all () not working How can I clear the cache with django and memcached? -
dynamic modal popups with django
Okay so I am having an issue with django, jquery and boostrap. Essentially, what I'm trying to do is take a dictionary passed into the template from views. Output truncated input into a table then have a modal with the remaining data. The issue I am currently having is, I can't figure out how to dynamically partition the data on the key to dynamically create the modal tables. So what I have now is in my view I am returning a dictionary containing a a id corresponding to a study id and three sets of values which are lists of lists. What I am doing is putting that truncated data into a bootstrap table then allowing for an expansion onclick which will bring up a modal with the full table corresponding to each row in the parent table. I'm hung up because I can get all of the data into a single modal but I would like to have it broken down by study so each modal displays only the results from that field. my view: ... study_ids = [] p = Triple.objects.values('studies').distinct() for item in p: for l,m in item.iteritems(): study_ids.append(m) occoruence_dict = {} occoruence_dict2 = {} test_dict = … -
_lte, __name, __startswith etc. queries in django - where are documented?
I don't know if I am blind or something, I am checking django documentation, query sets and I see practice of using __let, __name etc, but I don't see where this terms are defined? Can you help me with this? I am checking all this: https://docs.djangoproject.com/en/dev/ref/models/ -
does not template render, url expresion regex
[Imagem error look here][1] [1]: https://i.stack.imgur.com/AL5wd.pngenter code here **Template-html** <p> <a href="{% url 'courses:enrollment' courses.slug % }" class="pure-buttonprimary-button">Inscreva-se</a> </p> URLS.py urlpatterns = [ url(r'^$', index, name = 'index'), #url(r'^(?P<pk>\d+)/$', details, name = 'details'), url(r'^(?P<slug>[\w_-]+)/$', details, name = 'details'), url(r'^(?P<slug>[\w_-]+)/inscricao/$', enrollment, name = 'enrollment'), ] Url does not find the path specified, please help me -
Remove whitespaces from a url in Urlpatterns (django)
I'm new to Django and I'm developing a project in which there are profile pages. Well, the problem is that the primary key has whitespaces but I don't want them to show in the url, neither like "%20%", I want to join the words. For example: website.com/Example Studios --> website.com/examplestudios I've tried this: url ( (r'^(?P<studio_name>[\w ]+)/$').replace(" ", ""), views.StudioView, name = 'dev_profile') But didn't work (it seems like it turns the raw part to string before reading the url) and with 're' happens the same. I've been searching for solutions but I'm not able to find them (and slugify doesn't convinces me). What's solution to this or what do you recommend? -
Loading decimal numbers from django form (formset) into number input
I am creating a simple django app where you can create recipes with ingredients. On my RecipeCreate view I have a simple formset with a select input (where you select a product) and a input type="number" with the product count. So my form and model are quite simple: class Ingredient(models.Model): product = models.ForeignKey(Product) count = models.DecimalField(max_digits=4, decimal_places=2) class IngredientForm(forms.ModelForm): class Meta: model = Ingredient fields = ('product', 'count') Now when i want to display my recipe on my RecipeEdit view everything loads fine except for the count input. I get the following jQuery validation error: The specified value "12,00" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)? Because I'm writing a Polish website I would like to have our national standard decimal separator, which is a , not a . (but the dot should also be a separator). One of the solutions would be to use an input type="text" but it would mean I have to validate my number manually, which is troublesome. Is there any way to pass my number 12,00 so that it is accepted by the input field. Probably changing/overwriting the standard jQuery validation? Another curious fact is that when … -
Django Migrations not working
I don't know what's going on. Migrations always worked fine for me, but seems to me that now something is wrong. It's the second time that my python manage.py migrate does not work when I have just installed a third party app and want to migrate. This time it is happening with my django-crispy-forms. I did pip installed it and put it settings.py INSTALLED_APPS list. Did anybody ever dealt with something similar? Thanks! -
Django. Filter users by permissions / groups
programming experts! ;) I am a newbie in django programming and i can't find any relevant information about how to get a list of users by their permissions. I have spend literally like two hours looking all over the web and there are a lot of similar questions, but none of them is understandable how to use. What i need is to get a list of users with admin permissions in my html template and show it in the panel. I have just started with django a week ago and I seriously struggle to understand what goes where.. Following best answer from a Similar problem i do understand that: class Group(models.Model): myuser = models.ForeignKey(User, related_name='groups') goes to my models.py, but i cant really get where would i have to put form.fields['myuser'].queryset = User.objects.filter( groups__name='foo') form.fields['myuser'].queryset = User.objects.filter( groups__name__in=['foo']) code to... :/ I also have tried another solution (from the same source as above) qs = User.objects.filter(groups__name__in=['foo']) to put it in my model.py, such as: class Group(models.Model): qs = User.objects.filter(groups__name__in=['Administrators']) but when i do "makemigrations" i get a lot of errors. Thank you in advance for understanding -
Pass multiple objects to templates with render
I'm beginner on Django. I have a project with the following models: My Articles models: class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=160) content = models.TextField() image = models.ImageField(upload_to=upload_location) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) categorie = models.CharField(max_length=200) categorie = models.ForeignKey('categorie.Categorie') publier = models.BooleanField() My Portfolio categories models which is linked with my Article Model: class Categorieport(models.Model): title = models.CharField(max_length=200) article = models.OneToOneField('posts.Post') And finally, my portfolio models with all the photos: class Portfolio(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to=upload_location) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) categorieportfolio = models.ForeignKey('Categorieport') In one view and one template, i'd like to display information concerning the article and the portfolio related to the article. I wrote the following view: def portfolio(request, article=None): portfolio = get_object_or_404(Categorieport, article=article) image_portfolio = portfolio.portfolio_set.all() return render(request, 'portfolio1.html', {'portfolio': portfolio, 'image_portfolio': image_portfolio}) And the following templates: <div class="titre-display"> <h2>{{ portfolio.article.timestamp|date:"d E Y" }} / {{ portfolio.article.categorie}} </h2> <h1>{{ portfolio.article.title}}</h1> </div> <div class="content-display"> <div class="content-display-main"> <div class="content-display-main-portfolio"> <div class="image-portfolio"> <a class="example-image-link" href="{{ image_portfolio.image.url }}" data-lightbox="example-set" data-title="{{image_portfolio.title}}"> </a> I can access to information from my article but i can't access information from my portfolio. I tried it with the shell, and it works. I can't figure out why … -
Django Custom Text Formatting
How can I have add text formatting options in Django-Admin, either by coding it, or does django has addition features for it? For eg: making a text bold, subscript, superscript, etc. -
Test django model with foreign key to another model
I want to test one specific Model without having to worry about the other Model to which it has a Foreign Key (FK) to. Say my model Bundle needs a Foreign Key to my other model Session: models.py: class Bundle(ModelCommon): session = models.ForeignKey(verbose_name=_('Session'), to=Session, default=None, null=False, blank=False) available = models.BooleanField(verbose_name=_('Available'), default=True, null=False, blank=False) As I try to test my Bundle class with a Mock (because I don't need to care about what field values are in the Session object) on test_models.py: def setUp(self): MockSession = mock.create_autospec(Session) self.test_session = MockSession() self.bundle = Bundle(session=self.test_session, name='Mega Bundle', enabled=True, available=True, price=0) def test_event_enabled_is_default_false(self): session = Session() self.assertFalse(session.enabled) I keep getting this message: Error Traceback (most recent call last): File "test_models.py", line 181, in setUp self.bundle = Bundle(session=self.test_session, name='Mega Bundle', enabled=True, available=True, price=0) raise AttributeError("Mock object has no attribute %r" % name) AttributeError: Mock object has no attribute '_state' Here's the question: What is the absolute correct way to using a Test Double in this situation? Because so far I haven't managed to succeed in using one. -
Django: How to make {% extends [file] %} in html file cross platform?
In the login.html there's a line {% extends 'myapp\base.html' %} This does not work on linux but {% extends 'myapp/base.html' %} works How do you make it work cross platform? -
Store Button Click in database Django
I am developing a Django app, I need to track users click for particular button. Suppose I have 10 buttons and if logged in user clicks btn1, btn2, and btn5 then I want to store this to my database that user clicked these buttons -
django app ran on heroku -> AttributeError: 'NoneType' object has no attribute 'endswith'
I think im missing something in my settings.py but i don't know what. The Traceback: formated Traceback: Environment: Request Method: GET Request URL: http://localhost:5000/static/index.css Django Version: 1.10.6 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Manager'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/views/static.py" in serve 54. fullpath = os.path.join(document_root, newpath) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py" in join 70. elif path == '' or path.endswith('/'): Exception Type: AttributeError at /static/index.css Exception Value: 'NoneType' object has no attribute 'endswith' My settings looks like this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'testStatic') STATICFILES_DIRS =[os.path.join(BASE_DIR,'static')] Do i need to add something here ? When i do django run server it runs fine but on heroku i get this error what could it be ? ive asked in django's IRC but no-one there knows what this could be 😔 Thx in advance -
Is it posible to change django form_class dynamically in view class?
In my django app I need to have a different form for the different user role groups; I mean, at least two different forms. Is there any possible way to do so ? Thanks in advance everyone. -
adding a request variable in a django template
I am currently uploading a file to the server in Django as follows (For some unrelated reasons, I cannot use models for this form): <div class="input-group" style="padding-top: 10px"> <div><input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled></div> <div class="input-group-btn"><input type="button" id="get_file" class="btn btn-primary" value="Browse" style="margin-right: 3px;margin-left: 3px"></div> <div class="input-group-btn"><input type="submit" id="upload" class="btn btn-success" value="Upload" style="display: none"></div> <input type="file" id="upload_file" name="upload_file" accept=".zip"> </div> And then I some javascript as: document.getElementById('get_file').onclick = function() { document.getElementById('upload_file').click(); }; $('input[type=file]').change(function (e) { document.getElementById('filename').value = ($(this).val()); document.getElementById('upload').style.display = "inline" }); document.getElementById('upload').onclick = function() { }; This works fine and I can upload the file just fine. However, now along with a file, I also want to send a string identifier. I am not sure how I can insert another request parameter on submit from this template? The django side looks like: def upload(request): """ if request.method == 'POST' and request.FILES['upload_file']: # Do things So I need to add another parameter, so that I can do something like: request.GET.get('identifier') and this identifier key/value is inserted in the template code. -
Data is sent to the form python script, get a code 200, but dont take a letter (result of work view)
I can't send in the form on the website data through the python script. The usual feedback form, which works properly when manually filling, but does not send anything if you send a request script. What to do? The script sending a request to the site: import requests import sys URL = 'http://127.0.0.1:8000/' client = requests.session() client.get(URL) csrftoken = client.cookies['csrftoken'] login_data = dict(lastname='Игин', name='Anton', middlename='Konst', birthday='2017-04-20', telephone='(896) 097-29-02', csrfmiddlewaretoken=csrftoken, next='form_call/') r = client.post(URL, data=login_data, headers=dict(Referer=URL)) views.py def form_call(request): if request.method=='POST': form = Call_Form(request.POST) name = request.POST.get('name', '') lastname = request.POST.get('lastname', '') middlename = request.POST.get('middlename', '') birthday = request.POST.get('birthday', '') telephone = request.POST.get('telephone', '') if form.is_valid(): mail_host = SMTPMail.objects.all()[0] rec_list = RecMail.objects.all() recipients= [] for mail in rec_list: recipients.append(mail.mail) #Список получателей message = ''' На сайте вашей структуры NL International появилась новая заявка на звонок! Вот данные, предоставленные новым консультантом: ФИО:{0} {1} {2} Дата рождения: {3} Телефон: {4}'''.format(name,lastname, middlename, birthday, telephone) subject= 'Заявка на звонок' send_mail(subject, message, mail_host.mail, recipients, fail_silently=False) return redirect('/thanks/') else: return redirect('/error/') -
Importing classes from another app in Django
I am using Django 1.10 for my project. Below is the project structure. project |-accounts | |-forms | | |-__init__.py | | |-user_forms.py |-otherapp | |-views.py I have define UserForm class in user_forms.py file and in __init__.py file I imported user_forms as from .user_forms import * I am trying to use UserForm in otherapp. I was just curious why from accounts.form import UserForm form = UserForm(request.POST) works but import accounts.forms.UserForm form = UserForm(request.POST) or form = accounts.form.UserForm(request.POST) does not work? Isn't 3rd method better than first two as it follows zen of python Explicit is better than implicit. -
Django and Celery tasks
So in our Django project we're using Celery and the Django-Celery module. The person that originally wrote the tasks section wrote it like so: from djcelery import celery @celery.task def do_something(): ... But everywhere in the docs it shows that we should create a separate celery.py file and import the app like so: celery.py from celery import Celery app = Celery('project') if __name__=='__main__': app.run() tasks.py from celery import app // Importing `app` from our celery.py @app.task def do_something(): ... So I'm wondering if there's a problem doing it one way or the other?