Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What does 'Reverse' means in errors when running Django?
I'm trying to run a blog build with django on the browser. And I got this error: NoReverseMatch at / Reverse for 'blog.views.post_detail' not found. 'blog.views.post_detail' is not a valid view function or pattern name. My url.py of my app looks like: from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.post_list), ] It seems that when I type 127.0.0.1:8000/. The url will direct to views.post_list. And my views.py looks like: from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.objects.filter(published_date__isnull=False) return render(request, 'blog/post_list.html', {'posts': posts} def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) post_list() will render the request with post_list.html. Inside post_list.html, the error comes from the line: <h1><a href="{% url 'blog.views.post_detail' pk=post.pk %}">{{ post.title }}</a></h1> I don't really understand what 'Reverse' means in the error message. 'blog.views.post_detail' does exist in views.py. I think I got everything needed for the code and can't figure out what went wrong. I'm new to django, sorry if the question is basic and thanks for answering! -
Django JSONField: filtering numeric list containing values inside a range
Consider a PostgreSQL JSONField in a Django model with the following structure and data: info= {'label': 'productA' , 'array1':[ 2.01, 3.32, 5.34, 6.03, 8.11, 10.00] } The "info" must be a JSONField. I would like to filter the instances (table rows) of the Django Model where info__array1 has elements between 5 and 8. How can I do it? Thank you, C. -
AttributeError: 'ManagerFromSetDi...' object has no attribute 'normalize_email' afetr upgrading to django 1.11.3
after upgrading to django 1.11 I get the following AttributeError: 'ManagerFromSet....' object has no attribute 'normalize_email'; after googling I found the following from the django official documentation: If you subclass AbstractUser and override clean(), be sure it calls super(). BaseUserManager.normalize_email() is called in a new AbstractUser.clean() method so that normalization is applied in cases like model form validation. ...but I'm not able to understand what it means. Any help will be greatly appreciated. this is the code raising the error: def test_chk_anag_form_email_dupl(self): dati = gen_dizio(the_form=AnagForm, the_model_factory=AnagraficaFactory, data_field_list={'email': 'paperino@xyz.net'}) form_instance = AnagForm(data=dati) # print form_instance self.assertFalse(form_instance.is_valid(), form_instance.errors) this is the form: class AnagForm(ModelForm): class Meta: model = Anagrafica # exclude = ['username', ] # exclude = ['gestore', 'username', ] fields = ('username', 'email', 'first_name', 'last_name', 'cf', 'indirizzo', 'tel', 'cell', 'storico') # 'tel', 'cell', 'cap', 'storico') def __init__(self, *args, **kwargs): from django.forms.widgets import HiddenInput # hide_condition = kwargs.pop('hide_condition',None) super(AnagForm, self).__init__(*args, **kwargs) # if hide_condition: self.fields['username'].widget = HiddenInput() def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') esistono_altri = Anagrafica.objects.filter(email=email).exclude(username=username).count() if email and esistono_altri: raise forms.ValidationError(u'Questo indirizzo email è già registrato') return email and this is the model: class Anagrafica(User): VAL_STORICO = ( (u'S', u'Si'), (u'N', u'No'), ) cf = models.CharField('codice fiscale', max_length=16, blank=True, … -
Calling celery sub tasks from a task
I am working on a web application in which I need to do a lot of background processing. To achieve this I start a celery task(Call it super task) and send the response back immediately. Now, this super task calls more celery tasks(sub tasks) for parallel processing. I am using groups functionality of celery to achieve this. Code Overview @app.task def super_task(): do_heavy_work() @app.task def sub_tasks(): do_something() def do_heavy_work(): collect_ = [] for i in some_range: collect_.add(sub_tasks.s()) group_tasks = celery.group(collect_) group_result = group_tasks.delay() # can we collect result in super task for sub tasks without any #issue for res in group_result: perform_something_on_result(res.result) super_task.delay() Now the above approach works if my sub tasks are low (tested with 4 subtasks) But as I increase the sub tasks, Few sub tasks are always left in pending state for a long time (close to 15 minutes) and then get successfully executed(tested individually they should not take this much time). My question is am I getting stuck in some deadlock state. If yes then is there a way to get out of this deadlock, if not is there a way to achieve above functionality using with or without celery. celery version = 3.1.23 Total workers … -
How do I specify type of index in django? (btree vs hash, etc)
Like the title says, how do I specify the type of index I want on a field in a model in django. class Person: ... age = models.IntegerField(db_index=True) But now what? How do I make sure it is a btree index and not a hash. Or is this all done automatically for us and there is some large table that django uses for choosing the "optimal index type" -
Django 2 language site once again
I've already created my simple blog in python Django. For now I am interested how to maintain two languages on my blog. I'm know about Django internationalization but I do not want to translate button text in my templates. I've created post model with several fields for different languages: description_ru, description_en. At the end of the day I want to show fields based on user language preference. What best practices now (in 2017) to that. Many projects seems to be out of date now ;-( Maybe I should create separate aps for different languages? Thanks in advance. -
error 'NoneType' object has no attribute '__dict__'
I have encoutered this error and its not letting me save the info in the form. The initial data is showing well in the form but saving is challenging me. Hope someone can help, I'm really stuck class UserPostCreatView(CreateView): form_class = PostModelForm template_name = 'posts/post_form.html' success_url = "/profile/{user_slug}/wall" def get_initial(self): # Get the initial dictionary from the superclass method initial = super(UserPostCreatView, self).get_initial() user_slug = self.kwargs.get('user_slug') user_content_type = ContentType.objects.get_for_model(authomodel.User) auth_user = get_object_or_404(authomodel.User, user_slug=user_slug) auth_user_id = auth_user.id # Copy the dictionary so we don't accidentally change a mutable dict initial = initial.copy() initial = { "content_type": user_content_type, "object_id" : auth_user_id, } return initial def form_valid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = { 'initial': self.get_initial(), } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST or None, 'files': self.request.FILES or None}) return kwargs def get_form_class(self): return self.form_class -
Django many to many relationship, use one table for Two or more model
i am having following table hotels Model id name rooms Model id name facilities Model id name facility_properties facility_id linking_id type (hotel or room) in Django i want to create a link. in both, hotel and rooms, i want to use facility_property table as many-to-many linking table. it can be hotel and facility linking or room and facility linking. linking_id can be hotel id or room id -
Django- how to create schemas with independent columns
I am new to Django and I have to create webpages which takes the following inputs: location, technology, and services. The first web page should select a location type, and based on that it goes to the next page which selects the technology according to the location. the third web page selects services based on both the technology and location selected previously(it will be the intersection of both).For that i have to create schemas where each location can have multiple technologies and services, where both are independent of each other, and each technology multiple services. eg: loc1_tech->tech1,tech2 loc2_service->service1,service2,service3 tech1_service->service1,service2 tech_service2->service3,service4,service5 If we select loc1, then the next web page shows tech1 and tech2, and if i select tech2, then the third web page shows service3 only, which is the intersection of services of loc1 and tech2. I am planning to create 3 schemas- loc_tech, loc_services, tech_services in models.py. Is this the efficient way to go about it and create schemas? Also, how will i find the intersection of web services for the third webpage? -
Django - How to extend the swagger with additional functionalities?
I am using Django with Swagger documentation. I wonder if there is any way to extend functionalities. At this moment I use only base schema in settings. I see only URLs. When I click Django Logout it doesn't work. Is there a possibility to add an option to send an example body in methods? For instance I have also optional searching like GET /users/{user_id}/object?sth=123 is it possible to include it in swagger documentation, too? I was looking in the documentation but there isn't much information. My settings at this moment look in this way: schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^', schema_view), ] -
how to zip all pdf files under a static folder? django
I have a folder named pdfs under static folder. I am trying to have a returned zip which contains all the pdf files in the pdfs folder. I have tried a few threads and used their codes, but I tried to workout things but then couldn't solve the last part that I get a message saying no file / directory I know static folders are a bit different than usual folders. can someone please give me a hand and see what I have missed? Thanks in advance from StringIO import StringIO import zipfile pdf_list = os.listdir(pdf_path) print('###pdf list################################') print(pdf_path) # this does show me the whole path up to the pdfs folder print(pdf_list) # returns ['abc.pdf', 'efd.pdf'] zip_subdir = "somefiles" zip_filename = "%s.zip" % zip_subdir # Open StringIO to grab in-memory ZIP contents s = StringIO() # Grab ZIP file from in-memory, make response with correct MIME-type resp = HttpResponse(content_type='application/zip') # ..and correct content-disposition resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename # The zip compressor zf = zipfile.ZipFile(s, "w") for pdf_file in pdf_list: print(pdf_file) zf.write(pdf_file, pdf_path + pdf_file) zf.writestr('file_name.zip', pdf_file.getvalue()) zf.close() return resp here I am getting errors for not able to find file / directory for 'abc.pdf' -
Can't get rid of "nonexistent parent node" in django 1.11
So far I've tried about anything the internet has given me on this problem and I still haven't solved it. Python 3.6.1 - django 1.11.2 - virtualenv I had a django project with two apps account and app2. Recently I decided to split them up into more appropriate apps as the project is growing. Now I have a total of 8 apps where account got split up into user_auth and user, then I deleted account. To tidy it up even more I moved all apps from the root folder to /apps/. So far, only user, user_auth, app2 is in use where app2 has been untouched. The code in each separate file was split up, moved to the designated app and recoded to get imports from the correct paths. To get a fresh start I delete the db.sqlite3 file, removed all *.pyc files, deleted all __pycache__ folders and emptied the migrations folders, making sure to keep all __init__.py files. Running python manage.py migrate through a virtualenv gives me this output: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "H:\Programming\VirProjDir\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "H:\Programming\VirProjDir\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "H:\Programming\VirProjDir\lib\site-packages\django\core\management\base.py", line 283, in … -
"Select All" Checkbox and other features won't work in Django Admin
In my Django admin the checkbox at the top of the column of checkboxes does nothing. Usually it select/deselects all items in the list to allow for quick deletion or other actions, but I think there's something wrong with the javascript that runs that function. It's not just in one model or one app, but across all models and all apps. I've tried "collectstatic" and it gives me 0 static files copied to '/home/alex/newton/staticfiles', 276 unmodified. Here's what the static part of my settings.py file looks like: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) CSS is working, images are working and loading normally. I don't have very much Javascript on my site, so I can't say whether or not the rest of the site is suffering Javascript issues. Any ideas would be much appreciated. -
django.core.exceptions.FieldError: Unknown field(s) (dob) specified for User
I am trying to make a simple signup/login page through django. I have used UserCreationForm and used a model UserProfile to extend the user model. While my UserProfile was working correctly with one field 'department' but is giving errors, when I tried to add another field 'dob'. I am new to django so brief explanation would be appreciated. Thanks in advance forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from mysite.core.models import UserProfile from django.db import models class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') department = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') dob = models.DateField(auto_now=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email','password1', 'password2', 'department','dob',) def save(self, commit=True): # Save the provided password in hashed format user = super(SignUpForm, self).save(commit=False) user_profile = UserProfile(user=user, department=self.cleaned_data['department'],dob=self.cleaned_data['dob']) user.save() user_profile.save() return user, user_profile views.py from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from mysite.core.forms import SignUpForm @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user,user_profile = form.save(commit=False) username = user.cleaned_data.get('username') raw_password = user.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: … -
How to link a Django model field to an instance of the same model
I'm trying to design a Django model for articles with attributes like title, publication date, etc. One of the attributes is other article(s) that the article in question is commenting on. I'm not sure how to code this since there is no foreign key involved - I just want a reference to other instances of the Article model (i.e. one or more other articles). This is what I have so far: class Article(models.Model): title = models.CharField(max_length=400) publication_date = date_published = models.DateField() comment_on = ????????????? Any suggestions would be much appreciated. Thank you! -
how to upload Django app with mysql to heroku?
I'm trying to upload Django app with MySql DB to Heroku. Locally in my computer it runs with MySql DB. In postgresql I used the file: requirements.txt : It containes: dj-database-url==0.4.1 Django==1.10.2 gunicorn==19.6.0 psycopg2==2.6.2 whitenoise==2.0.6 how should I change it in order to upload the app? In my settings.py file I changed only the DATABASE list: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER': 'root', 'PASSWORD': 'my_password', } } what else should I just in order to upload the app? -
Display Django Page in an Iframe refused due to x-frame-options
I have a Django website hosted with nginx that runs fine when accessed directly via the browser. I'm however trying to display it on an iFrame (on Amazon Mechanical Turk). Here my page is refused: console output : Refused to display 'https://my_website' in a frame because it set 'X-Frame-Options' to 'sameorigin'. If i understand it correctly, this happens because my website does not allow itself to be displayed in an iFrame, as per the x-frame-options. How can I change the x-frame-options on my website, allowing it to be shown in a frame? -
Django: send_mail not working [only for production]
I'm having issues with my send_mail function in my production environment in Heroku. My settings.py are identical for local and for production and Gmail is sending the emails correctly when I test in the localhost, but for some reason I'm getting a 500 SERVER ERROR and I'm not even getting the error logs from django in my Admin email (probably for the same reason). I already did this before and it is really strange that this is happening. And the same gmail had already done this for the local development, so I don't think the problem is there. I'm using Python3.6, Django1.11 and Heroku. Here's my code: settings.py EMAIL_HOST = 'smtp.gmail.com' from .passwords import EMAIL_HOST_USER from .passwords import EMAIL_HOST_PASSWORD EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER from .passwords import ADMINS MANAGERS = ADMINS views.py from django.conf import settings from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import LandingPageMapasForm def mapas(request): form = LandingPageMapasForm(request.POST or None) context = { "form": form, } if form.is_valid(): obj = form.save(commit=False) # obj.user = self.request.user obj.save() form_empresa = form.cleaned_data.get('empresa') subject = '%s - Solicitação de Orçamento' %(form_empresa) contact_message = 'message' context = {} from_email … -
DDoS protection for Django Channels
Is there anything specific that can be done to ensure a Django Channels server is not susceptible to DDoS (attack or accident) from websocket clients? Since Channels is not truly asynchronous (still workers behind the scenes), I feel like it would be quite easy to take down a Channels-based website - even with fairly simple hardware. I'm currently building an application on Django Channels and will run some tests later to see how it holds up. Is there some form of throttling built in to Daphne? Should I implement some application-level throttling? This would still be slow since a worker still handles the throttled request, but the request can be much faster. Is there anything else I can do to attempt to thwart these attacks? One thought I had was to always ensure there are workers designated for specific channels - that way, if the websocket channel gets overloaded, HTTP will still respond. -
Django 'ChoiceField' object has no attribute 'use_required_attribute'
Here's my model (in models.py) class Score(models.Model): ROUTINETYPE_CHOICE = ( (0, 'R1'), (1, 'R2'), (2, 'F'), ) routineType = models.IntegerField(choices=ROUTINETYPE_CHOICE) pointA = models.DecimalField(max_digits=3, decimal_places=1) pointB = models.DecimalField(max_digits=3, decimal_places=1) pointC = models.DecimalField(max_digits=5, decimal_places=3) And here's my Form (in forms.py) class ScoreForm(forms.ModelForm): class Meta: ROUTINETYPE_CHOICE = ( (0, 'R1'), (1, 'R2'), (2, 'F'), ) model = Score fields = ('routineType', 'pointA', 'pointB', 'pointC') widgets = { 'routineType': forms.ChoiceField(choices=ROUTINETYPE_CHOICE), 'pointA': forms.TextInput(attrs={'placeholder': 'xx,xx', 'value': '0'}), 'pointB': forms.TextInput(attrs={'placeholder': 'xx,xx', 'value': '0'}), 'pointC': forms.TextInput(attrs={'placeholder': 'xx,xx', 'value': '0'}), } And my view is usual: def score_create(request): if request.method == 'POST': form = ScoreForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/score/') else: form = ScoreForm() context = {'form': form} return render(request, 'score_create.html', context) When I try to display my form, django give me this error: 'ChoiceField' object has no attribute 'use_required_attribute' The use_required_attribute is new in Django 1.10 and I've the possibility to set it to False. But it's on the Form level, it will say that my other fields are loosing the HTML required attribute too. I've only three possibilities (with no "dummy" default option selected (something like "choose…")), so my ChoiceField have always an option selected and then the HTML attribute "required" is fulfilled. Someone know an another … -
Refer to admin site using {% url 'admin' %} in app django
i wanna Move user to admin panel site in Django using {% url 'admin' %} but the problem is my template in rendering in an app and i dont wanna rewrite url("^admin/",admin.site.urls) in project/site/urls.py here it is project / urls.py urlpatterns = [ url(r"^admin/", admin.site.urls, name="admin"), url(r"^", include("core.urls")),] project / site / urls.py urlpatterns = [ url(r"^$",indexView.as_view() ,name="index" ), ] accountspattenrns = { url(r"^accounts/signup/$",signupView.as_view() ,name="signup" ), url(r"^accounts/login/$",loginView.as_view() ,name="login" ), url(r"^accounts/logout/$",logoutView.as_view() ,name="logout" ), url(r"^accounts/profile/$",ProfileView.as_view() ,name="profile" ), } urlpatterns +=accountspattenrns template.html <li><a href="{% url 'admin' %}"><i class="fa fa-black-tie fa-2x"></i> <div>Admin</div></a></li> Error : -
Initialize with data while run the django app for the first time
Suppose I have an app Settings which contains model namely Season. Now I want to intitialize Season model with dummy data while I run python manage.py makemigration Settings command for the first time. I don't even know whether it's possible or not, as I'm very new in Django. So if you know any other way to solve my problem then please let me know also. Thanks in advance. -
Run a python Script in Django Web project that stores data in database
There is a python script written in "sample.py" which stores some data in mySQL database table. I have a Django project created [new to Django]. Now, I want to run "sample.py" in this Django project such that it stores data in the database. How do I do that? -
How to change Angular2 interpolatioin syntax curly brackets to something else?
I want to use Angular2 with Django, but they both use double curly brackets in templates, is there a way to change them to something else in Angular2 or in Django (found only a way for Jinja2 templating engine, but not Django templating engine) if that's not possible in Angular2? A link to the official documentation would be really appreciated (wierd, but I couldn't find anything about it there) -
Media Files not Displaying in Django
I am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for gallery images with a filefield), the image is stored in /media/images correctly. I have my media settings set in settings.py as follows: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") Project urls.py: from django.conf.urls import include, url from django.contrib import admin import gallery.views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('gallery.urls')), ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Gallery urls.py: from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^', views.homepage, name = 'home'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Gallery views.py: def homepage(request): texts = Sitetext.objects.all() gal = Galleryimg.objects.all() gal.order_by('position') return render(request,'index.html', {"text1":texts[0].text,"text2":texts[1].text,"text3":texts[2].text,"text4":texts[3].text,"title1":texts[0].title,"title2":texts[1].title,"title3":texts[2].title,"title4":texts[3].title,"gallery":gal}) And then this is the part of the template code that accesses the image: {% for g in gallery %} <div class="col-md-3 col-sm-4 col-xs-6"><img class="img- responsive" src="g.imgfile.url"/></div> {% endfor %} When I create a gallery image, a broken image pops up, but the image is not accessed correctly.