Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: No module named locallibrary.settings
You could have seen the question so many times. But unluckily I cant solve this error. I am using python 2.7.12 , django 1.8 The tutorial source I learn is Mozilla django development where they teach with latest version of python3 and django 1.10 Somehow I tackled to use with older version. everything was going good until I started to import models to admin. soem class codes started showing that it has no object member, even though it exist and hence I finally got the error as "ImportError: No module named locallibrary.settings" Here what I tried: Updated to python 3(thought that could be the problem) appended correct sys path() with project path. Still same error showing up Anybody help me out for solving the issue. -
Django REST: Redirect has been blocked by CORS policy
I have enabled CORS in Django settings as following: INSTALLED_APPS = ( ... 'corsheaders', ... ) MIDDLEWARE_CLASSES = [ ... 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware' ... ] CORS_ORIGIN_ALLOW_ALL = True When I call (from my Frontend AngularJS web-app) the GET API, I get the following error: XMLHttpRequest cannot load [url1]. Redirect from [url1] to [url2] has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect. Should I add something else to the Django settings? -
Django form submit with ajax
I have new_registration view as follows : def new_registration(request): context = {} if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): language = Language.objects.get(key="EN") country = Country.objects.get(key="BE") user = User() user.username = form.cleaned_data['email'] user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.email = form.cleaned_data['email'] user.set_password(form.cleaned_data['password']) user.save() # Send an email to user subject = "The account is created" plain_message = "Your account has been created successfully but it's not activated. Once your information has been processed, your account will be activated and you will get an email." html_message = render_to_string('master/email_templates/account_created_member.html', {'name': user.first_name}) msg = EmailMultiAlternatives(subject, plain_message, settings.EMAIL_FROM, [user.email]) msg.attach_alternative(html_message, "text/html") msg.send() context['form'] = RegistrationForm() context['success'] = "Your account has been created successfully. Once your information has been processed, your account will be activated." return render(request, 'master/new-registration.html', context) else: form = RegistrationForm() context['form'] = form return render(request, 'master/new-registration.html', context) The template new_registration.html is as follows : {% extends "master/base.html" %} {% block content %} <div id="container" class="cls-container"> <div id="bg-overlay" class="bg-img" style="background-image: url(/static/master/img/48210373_l.jpg)"></div> <div class="cls-content"> <div class="cls-content-lg panel"> <div class="panel-body"> <div> {% if error %} <div class="mar-btm alert alert-danger" style="border-left: none;"> {{ error }}</div> {% endif %} </div> <div> {% if success %} <div class="mar-btm alert alert-primary" style="border-left: none;"> {{ success }}</div> {% endif … -
How to reorder the models on a django-admin-tools dashboard?
I use the django-admin-tools app. On the dashboard I would like to reorder the models related to an app. To achieve this I used the django-modeladmin-reorder package before, but it seems it's not compatible with the django-admin-tools package. Here is an example of what I would like to achieve. Inside my application I have an Animals app with the models Lion, Antelope, Cat, Dog. On the index page I see something like this now: Animals Lions (Add|Change) Cats (Add|Change) Antelopes (Add|Change) Dogs (Add|Change) And I would like to change the order of the models to see this: Animals Cats (Add|Change) Dogs (Add|Change) Lions (Add|Change) Antelopes (Add|Change) So I defined that I want to see the models in the following order: Cats, Dogs, Lions, Antelopes. Any idea on how to do it? Thanks, Andras -
Regroup Items based on Day Django
I want to regroup objects by placing them in date. I used the regroup tag. The result will print out like this, 06.03.17 Smart Town: DC 05.03.17 Man Ranking: DC 05.03.17 Jose Ranking: SW 05.03.17 Faz Man: DC I want it to display like the format below. 06.03.17 Smart Town: DC 05.03.17 Man Ranking: DC Jose Ranking: SW Faz Man: DC Template: {% regroup myup by pub_date as date_list %} {% for md in date_list %} <p>{{ md.grouper|date:"d.m.y" }}</p> {% for xp in md.list %} <p>{{ xp.title }}: {{ xp.category }}</p> {% endfor %} {% endfor %} How do I go about this? -
Django - CSRF verification failed - after successfully loged in
I am getting CSRF verification failed when i return to back go back after login using django method. It returns the sign in page even after i successfully log in. And it posts the error as CSRF verification failed. Could i use to set anything in Django setting? Please tell me some suggestions to fix on it. -
Django: Block access to specific users in one app
I'm building an Django project demonstration that has in its constitution 3 apps (app, blog, frontend) The challenge I'm facing is the following: I want to limit access to the app app to allow only registered users. In other words, restrict access to all the pages in app django app. After doing some research, stumbled accross the following links: Link 1 Link 2 Link 3 The answer in Link 1 seems the easier to implement. Still, I'm having some problems doing it, as I have little experience working with Middleware in Django. Asked there in the comments: 'I want to limit the access of one app, called app, if the user doesn't have login. The middleware RequireLoginMiddleware class should be placed where?' but no reply yet so far and I don't seem to find a way to cross this. Can anyone explain me what I need to do to Restrict access to all the pages in a django app to allow only registered users? -
ImportError: cannot import name signals when importing wsgi file in Django 1.10
I'm getting the following error trying to run Django using apache: mod_wsgi (pid=3294): Target WSGI script '/www/cocurate2_dev/startup.wsgi' cannot be loaded as Python module. mod_wsgi (pid=3294): Exception occurred processing WSGI script '/www/cocurate2_dev/startup.wsgi'. Traceback (most recent call last): File "/www/cocurate2_dev/startup.wsgi", line 3, in <module> from django.core.wsgi import get_wsgi_application File "/www/cocurate2_dev/components/lib/python2.7/site-packages/django/core/wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "/www/cocurate2_dev/components/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 10, in <module> from django import http File "/www/cocurate2_dev/components/lib/python2.7/site-packages/django/http/__init__.py", line 5, in <module> from django.http.response import ( File "/www/cocurate2_dev/components/lib/python2.7/site-packages/django/http/response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "/www/cocurate2_dev/components/lib/python2.7/site-packages/django/core/serializers/__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "/www/cocurate2_dev/components/lib/python2.7/site-packages/django/core/serializers/base.py", line 4, in <module> from django.db import models File "/www/cocurate2_dev/components/lib/python2.7/site-packages/django/db/models/__init__.py", line 4, in <module> from django.db.models import signals # NOQA ImportError: cannot import name signals Everything works find when using manage.py runserver. I've updated the wsgi file to be the same as the default one from django 1.10. I've checked that signals.py exists inside djanog, I've also cleaned .pyc files. -
Foreign key use with user model upload
These are my models and one user can upload multiple videos but one video belongs only to one user. How do I use the foreign key concept over here? When I add a user, does this automatically add a username in the Video model? If not, how do I do that? I'm very new to django over here class User(models.Model): first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) username=models.CharField(max_length=25, primary_key=True) password=models.CharField(max_length=15) email_id=models.CharField(max_length=30, default='NULL') profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',default='') def __str__(self): return self.username class Video(models.Model): username=models.ForeignKey(User,on_delete=models.CASCADE,default="") video=models.FileField(upload_to='videos/%Y/%m/%d/',default='') videotitle=models.CharField(max_length=100) likes=models.PositiveIntegerField(default=0) dislikes=models.PositiveIntegerField(default=0) def __str__(self): return self.video -
Django translations work on dev and heroku, not ec2
I have a django app that is deployed on heroku, but for technical reasons I need to move over to ec2. I have translations that work on my local computer and on heroku, but WILL NOT work on EC2 (Amazon Linux). My .mo files ARE NOT git ignored. Just in case, I recompiled on the new server. My locale path points to the correct dir - I print it out after setting it and it matches. I have checked many many posts, and nothing helps. Any ideas? I'm serving the app with gunicorn & nginx. -
Django Rest Framework KeyError 'request'
i have my serializer like this class PublicacionSerializer(serializers.ModelSerializer): usuario = UserSerializer2() likeado = serializers.SerializerMethodField() class Meta: model = Publicacion fields = ('id','usuario', 'likeado') def get_likeado(self, obj): user = self.context['request'].user try: like = Like.objects.get(publicacion=obj, usuario=user) return like.id except Like.DoesNotExist: return False when i access to the url for know if an user has liked to a post i got a KeyError 'request' in code line user = self.context['request'].user anyone knows how to solve it? -
Saving data to django database
I have three django models (user, member (extended user), subscription) and the are connected with a ForeignKey. And then when the user want to create a new account I save it to the database as follows: language = Language.objects.get(key="EN") country = Country.objects.get(key="BE") user = User() user.username = form.cleaned_data['email'] user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.email = form.cleaned_data['email'] user.set_password(form.cleaned_data['password']) user.save() member = Member() member.number = form.cleaned_data['member_id'] member.name = '{} {}'.format(form.cleaned_data['firstname'], form.cleaned_data['lastname']) member.address = form.cleaned_data['address'] member.postcode = form.cleaned_data['postcode'] member.city = form.cleaned_data['city'] member.country = country member.telephone = form.cleaned_data['telephone'] member.mobile = form.cleaned_data['mobile'] member.user = user member.language = language member.active = False member.save() subscription = Subscription() subscription.started = datetime.date.today() subscription.type = Type.objects.get(default=True) subscription.member = member subscription.save() That works fine. But I want to ask if there is a better way to store it to the database? -
What do these errors mean ? mysql in django
I am trying to run a program I was given to look at as an example, it is like a shopping website, that uses MySQL database instead of the original database provided in Django! I just wanted to see if anyone understands what these errors mean? any info would be appreciated! I would have provided the code of the web page, but there is to much it won't fit ! Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 1266, in check errors.extend(cls._check_fields(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 1337, in _check_fields errors.extend(field.check(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 893, in check errors = super(AutoField, self).check(**kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 208, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 311, in _check_backend_specific_checks return connections[db].validation.check_field(self, **kwargs) File "/Library/Python/2.7/site-packages/django/db/backends/mysql/validation.py", line 41, in check_field field_type = field.db_type(connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 629, in db_type return connection.data_types[self.get_internal_type()] % data File "/Library/Python/2.7/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
DateTimeField displaying a textbox instead of a date picker
The current date is being displayed but it is displayed in a textbox. How do i get a datepicker???? models.py class Comment(models.Model): title = models.CharField(max_length=100) text = models.CharField(max_length=100) notes = models.CharField(max_length=100) date = models.DateTimeField("Date", default=datetime.date.today) def __str__(self): return self.title forms.py class MyCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['title', 'text', 'notes', 'date'] -
InvalidTemplateLibrary exception when working through Wagtail Documentation on Snippets
I'm following the Wagtail documentation on Snippets to make sure I can get that working before creating my own. But have come across a stumbling block. I have added the model for the adverts in the models.py file and am now creating the demo_tags.py file. Currently it reads - from django import template from demo.models import * register = template.Library() ... #don't know if something is supposed to go in here # Advert snippets @register.inclusion_tag('demo/tags/adverts.html', takes_context=True) def adverts(context): return { 'adverts': Advert.objects.all(), 'request': context['request'], } When I run the development server the from demo.models import * line creates a InvalidTemplateLibraryerror. Clearly I'm supposed to change the replace the 'demo' and '*' with something, but what? Additionally, when it comes to creating the template, called adverts.html, which directory should that be going in? the templatetags one, or with the other blog templates? Thanks. -
Generic relation in django, queryset with aggregate
I use django 1.6 and generic relation in models. And I have problem with aggregate function in model: Here is part of my view: class EventListView(PageContextMixin, ListView): model = Activity template_name = 'events/eventlist.html' def get_queryset(self): seasons = Season.objects.all() if not self.request.user.is_superuser: seasons = seasons.filter(is_active=True) active_seasons_ids = list(IsActiveFlag.objects.exclude(is_active=False).values_list('id', flat=True)) seasons = list(Season.objects.filter(isactiveflags__id__in=active_seasons_ids)) minmax = seasons.aggregate(Min('start'), Max('end')) min_date = minmax['start__min'] max_date = minmax['end__max'] active_sale_and_cycles_ids = list(SaleAndCycle.objects.exclude(is_sale_active=False).values_list('id', flat=True)) filters_sale = Q(sale_and_cycles__id__in=active_sale_and_cycles_ids) active_is_cyclic_event_ids = list(SaleAndCycle.objects.exclude(is_cyclic_event_active=False).values_list('id', flat=True)) filters_cycle = Q(sale_and_cycles__id__in=active_is_cyclic_event_ids) sales_events_activities = Activity.objects.filter(Q(filters_sale, online=True) | Q(filters_cycle, online=True)) sales_events_ids = sales_events_activities.values_list('id', flat=True) minmax_sales_events_activities = sales_events_activities.aggregate(Min('start'), Max('end')) max_date_sales_events_activities = minmax_sales_events_activities['end__max'] I get an error in this place: minmax_sales_events_activities = sales_events_activities.aggregate(Min('start'), Max('end')) Error: no such table: events_saleandcycle But there is table in database (I use sqlite) with fields: id, content_type_id, object_id, position, is_sale_active, is_cyclic_event_active, cycle_link class SaleAndCycle(SortableVAExtra): is_sale_active = models.BooleanField(default=False) is_cyclic_event_active = models.BooleanField(default=False) cycle_link = models.CharField(max_length=255, null=True, blank=True) def __unicode__(self): return str(self.is_sale_active) -
django rest framework: object of type 'NoneType' has no len() when calling get method of related tabe
I am building an django rest api for saving/managing customer data for my project. I have two models. Customer for storing basic customer details and CustomerDetails for storing a bunch of customer details. I want to write a single api to create/update data for both the models. Now my code is saving the user data. But I now I can't get the customer data. When I call the get method, the following error occurs. TypeError at /api/v1/customer object of type 'NoneType' has no len() Request Method: GET Request URL: http://127.0.0.1:8000/api/v1/customer Also, Do I need to do anything extra to use this code for updation (PUT) urls.py router.register(r'customer', views.CustomerViewSet, 'customers') models.py class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) address = models.CharField(max_length=50) city = models.CharField(max_length=256) """some more fields to go""" # Create your models here. class CustomerDetails(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE, primary_key=True, ) spouse_name = models.CharField(max_length=256) interests = models.CharField(max_length=256) """many more fields to go""" serializers.py class CustomerDetailsSerializer(serializers.ModelSerializer): class Meta: model = CustomerDetails fields = ('spouse_name',) class CustomerSerializer(serializers.ModelSerializer): customer_details = CustomerDetailsSerializer( required=True) class Meta: model = Customer fields = ('name', 'city', 'customer_details', ) def create(self, validated_data): request = self.context.get('request') user = request.user # create user customer = Customer.objects.create( user = … -
Filter all Users to show only active ones in admin interface
I have a model, let's call it X, which has a ManyToManyField that can list any number of users. In the admin interface (the only place those X objects can be created), I want to filter all the possible users by whether they are active (is_active=True) or not. Old instances of X can have inactive users, that is fine. It is just new instances of X that cannot have inactive users added. How can I do that? -
ReverseOneToOne not evaluated in django signal
I have two models : class Content(models.Model): text = models.TextField(blank=True, null=True) class Article(models.Model): content = models.OneToOneField(Content, related_name="article_content") And a signal (declared in signals module, and connected through AppConfig.ready() : def clear_cache(sender, **kwargs): print(sender.article_content.pk) post_save.connect(clear_cache, sender=Content) When I save a content, AttributeError: 'ReverseOneToOneDescriptor' object has no attribute 'pk' is raised art = Article.objects.get(pk=1) ct = art.content # content exists ct.save() So my questions : Why getting related descriptor returns the linked object instance everywhere but not in my signal How can i access my related object inside the signal (without replacing my OneToOneField by a ForeignKey) I've setup minimal project reproducing this behaviour -
Put django file object into tikka server
In my project I have receiving multiple files using request.FILES.getlist('filedname') and saving it using django forms save method. Again reading the same files using tikka server api of python (read_by_tikka(file_url)). Is there any way to directly put list files getting from request.FILES to tikka server without saving it on hard disk. -
Semantic UI - variable grid on mobile, tablet and computer
I have user images in the grid which should adjust their sizes depending on the width of the grid. Right now I have: <div class="ui ten column grid"> {% for user in event.participants.all %} <div class="center aligned column"> <a href="{% url 'profiles:profile' user.username %}"><img class="ui circular small centered image" src="{{ user.profile.get_avatar_url }}"></a> <p>{{ user.username }}</p> </div> {% endfor %} </div> And everything works fine except that on small devices profile images decrease in size dramatically, because of "ten column grid" which is applied for mobile devices as well as for computers. I know that for columns it is possible to declare: <div class="sixteen wide mobile twelve wide tablet ten wide computer column"> but it won't work if I use it for grid: <div class="ui sixteen wide mobile twelve wide tablet ten wide computer column grid"> How can I create adjustable to the content grid in Semantic which will have different width on mobile, tablet and computer? -
what is the die() equivalent in Django
what is the die() equivalent in Django? i want to stop the script in the middle of HTML template. Right now what i did to debug is simply by using the debugging feature in IDE. -
Sorting Objects Based on Dates Django
I have a model VBRank with the different fields including pub_date. Now, I want to display each VBRank object on the homepage according to the date posted by querying pub_date. I want the homepage to get sorted like 'WorldstarHipHop.com' homepage. If I should do this, VBRank.objects.filter(pub_date=datetime.date.today()) It will bring out all objects posted today, like Today's Rank. I'm confused on how to filter for each day objects dynamically e.g March 5 2017 Rank, March 4 2017 Rank, March 3 2017 Rank and so on. How can I go about this? Another thing is, if I should filter by all Rank posted like this, VBRank.objects.all() Sorting the objects out based on dates is where I'm stucked. -
Django manager first() vs Model.objects.all()[:1]
I would like to know if first() is the same as limiting querysets. Is Model.objects.first() the same as Model.objects.all()[:1] in speed? You've to remember that first() is the same as Model.objects.all()[0], so my thoughts are that they aren't the same, but then I don't understand why we have a handy method as first(). -
Django fail to reference value after return serializered model object for ajax request
I have a ajax request call QueryDB and try to query the data. def QueryDB(request): _exp = request.GET['exp'] _alg = request.GET['alg'] _orderby = request.GET['orderby'] _type = request.GET['type'] _nOutput = request.GET['nOutput'] if(_type == 'fp'): evs = ev_detection.objects.filter(alg=_alg, exp = _exp) order_evs = evs.order_by('score'); #order_evs = order_evs[0:int(_nOutput)] data = serializers.serialize('json', order_evs) return HttpResponse(data, content_type = "application/json") ev_detection model: class ev_detection(models.Model): imageset = models.CharField(max_length=20,default='') exp = models.CharField(max_length=20,default='') alg = models.CharField(max_length=20) nFrame = models.FloatField() xAxis = models.FloatField() yAxis = models.FloatField() width = models.FloatField() height = models.FloatField() score = models.FloatField() match = models.IntegerField() My AJAX function: $(document).ready(function(){ $('#fpquery').on("click", function(){ $.ajax({ type:'GET', url: '/results/QueryDB', data: { 'exp':'Reasonable', 'alg':'FT22-OI', 'type':'fp', 'orderby': 'score', 'nOutput': 5 }, dataType: 'json', success: function (data) { alert(data[0].length); } }); }); }); The alert popup value "undefined" But when I change it to alert(data.length);it return 5 which is the correct number. I just wonder how can I get the correct json return in my case?