Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Travis Error doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am trying to build my app in Travis but I keep getting the following error which I am unable to debug. Can anybody see anything obvious that I may be doing wrong? RuntimeError: Model class Code-Institute-Milestone-Project-05.babysitters.models.Babysitter doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. INSTALLED_APPS = [ 'about', 'accounts', 'blog', 'bookings', 'babysitters', 'contact', 'checkout', 'storages', 'django.contrib.admin', 'django.contrib.humanize', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'django_gravatar', 'home', -
Django input login for an admin
How can i add attribute autocomplete="off" to the input login template form for an admin ? I'm find this in the login.html template but can`t find where is the form template <div class="form-row"> {{ form.username.errors }} {{ form.username.label_tag }} {{ form.username }} </div> -
Unable to create custom user model with Django 2.1 and Python 3.5
I'm trying to create a custom user model (as I've done several times before) in an attempt to remove the "username" field and replace it with the "email" field. I created a brand new project and installed the latest version of all packages in a venv: Django==2.1.4 django-filter==2.0.0 djangorestframework==3.9.0 Markdown==3.0.1 pkg-resources==0.0.0 pytz==2018.7 I then created a project with the following layout: . ├── api │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py └── penguin_backend ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py I then added the following code to the api/models.py file which replaces the default user model and user manager class: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.core.mail import send_mail from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) … -
Ajax making two GET requests when it should when it should only be one.
Ajax call is making two GET requests, only for zip codes beginning and ending with 0. It uses jQuery to get the value of the zip field checks the value to see if it equals 5, then makes the get request to a Django view in the second block of code. A success in the Ajax calls iterates through the list and displays it on the webpage. The problem is that it should only be one GET request, but again sometimes it makes two... $( "#zip" ).keyup(function() { if ($(this).val().length===5){ var zip = $(this).val() $.ajax({ type: 'GET', url: '/zipcode', data: { number: $(this).val(), }, dataType: "json", success: function(data) { $(".zip_response").remove(); var zipList = JSON.parse(data); var container = $('<div />'); for(var j=0; j< zipList.length; j++){ container.append($('<li href="#" />').addClass("zip_response").text(zipList[j]["city"]+','+zipList[j]["state"])); } $('.zip_menu').append(container); $('.zip_menu').show(); }, error: function (errorThrown) { }, }); } }); This takes the zip code makes a database call and either returns the row(s) if it exists or returns "None" for city and state info. def zipcode(request): if request.is_ajax(): number = int(request.GET['number']) zip_list = Zip.objects.raw('SELECT * FROM users_zip WHERE zip_code = %s', [number]) data=[] for item in zip_list: data.append({'city': item.city, 'state': item.state}) json_data = json.dumps(data) if not data: json_data = json.dumps([{'city': … -
Django not finding users in pyad
I am trying to display all users in a table. when I run the following in a shell, it returns exactly what I want, But when i do it in django, nothing is displaying. This is the command that works in a shell: import pyad import pyad.adquery q = pyad.adquery.ADQuery() q.execute_query( attributes = ["displayName", 'manager', "description", "telephoneNumber", "otherTelephone","mail", "title", "department", "info", "userAccountControl"], where_clause = "objectClass = '*'", base_dn = "OU=Hidden, DC=for, DC=security" ) for row in q.get_results(): name = row["displayName"] desc = row["description"] phone = row["telephoneNumber"] phone2 = row["otherTelephone"] mail = row["mail"] title = row["title"] department = row["department"] extension = row["info"] status = row["userAccountControl"] man = row["manager"] if man is not None: print(name + ' | ' + title + ' | ' + phone + ' | ' + extension + ' | ' + mail) This is the url call: from adsi import views as dir urlpatterns = [ url(r'^managers/$', dir.ADView.as_view(), name='managers'), This is my view: from .models import Store, Table @method_decorator(login_required, name='dispatch') class ADView(ListView): model = Table context_object_name = 'table' template_name = 'managers.html' This is my template: {% extends 'base.html' %} {% block breadcrumb %} <li class="breadcrumb-item active">Managers</li> {% endblock %} {% block content %} <table class="table … -
django template filter by user using category dropdown button
Greetings. I'm doing a real estate page, and my idea is that through a dropdown list the user can filter between houses, lots or apartments. This is what I have but when going to the option url I get an error in the template. I appreciate the collaboration of whoever takes me out of this doubt. Models.py the category model is a ForeignKey for SaleProperty class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=40, unique=True) is_active = models.BooleanField(default=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name def get_absolute_url(self): return "categoria/%s/" % self.name class SaleProperty(models.Model): VENDER = 'VENDER' RENTAR = 'RENTAR' SI = 'SI' NO = 'NO' CHOICES = ( (VENDER, 'Venta'), (RENTAR, 'Alquilar') ) PARKING_OPTIONS = ( (SI, 'Si'), (NO, 'No') ) ROOMS = [(i, i) for i in range(11)] user = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ForeignKey('Category', on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() parking_option = models.CharField(max_length=2, choices=PARKING_OPTIONS, default=NO) rent_or_sale = models.CharField(max_length=10, choices=CHOICES, default=VENDER) rooms = models.IntegerField(choices=ROOMS) bathrooms = models.IntegerField(choices=ROOMS) price = models.DecimalField(max_digits=10, decimal_places=1) area = models.FloatField(max_length=7) pub_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title # Shows admin the name of entry blog def summary(self): return self.description[:100] # This makes short description def publish(self): self.pub_date = timezone.now() self.save() def pub_date_pretty(self): return … -
Celery group of chains becomes non responsive
I am trying to create a group of chains and when the group gets executed it just stops and hangs, looks very much like deadlock. I checked rabbitmq and resultbackend and they are running just fine. here are my dummy tasks to reproduce: from pprint import pprint from time import sleep @app.task def a(i): result = 'A %s' % i sleep((i%3)/ 10.0) pprint(result) return result @app.task def b(self,i): result = 'B %s' % i sleep((i%3)/ 10.0) pprint(result) return result @app.task def c(self,i): result = 'C %s' % i sleep((i%3)/ 10.0) pprint(result) return result and I call them like this: chains = [chain(a.s(i), b.s(i), c.s(i)) for i in range(100)] g = group(*chains) result = g.apply_async() also my settings are as follows: # Sensible settings for celery CELERY_ALWAYS_EAGER = False CELERY_ACKS_LATE = True CELERY_TASK_PUBLISH_RETRY = True CELERY_DISABLE_RATE_LIMITS = F CELERY_IGNORE_RESULT = False CELERY_SEND_TASK_ERROR_EMAILS = False CELERY_TASK_RESULT_EXPIRES = 600 CELERY_REDIS_MAX_CONNECTIONS = 2048 CELERY_TASK_SERIALIZER = "pickle" CELERY_RESULT_SERIALIZER = "pickle" CELERY_ACCEPT_CONTENT = ["pickle"] # CELERY_TASK_SERIALIZER = "json" # CELERY_ACCEPT_CONTENT = ['application/json'] CELERYD_HIJACK_ROOT_LOGGER = False CELERYD_PREFETCH_MULTIPLIER = 1 CELERYD_MAX_TASKS_PER_CHILD = 1000 I think some deadlock is occuring somewhere because what happens has its symptoms and no error is thrown at all. The version of celery is … -
Why am I getting invalid error in my PyMongo Query
I am writing a pymongo query and it works when I write it in my MongoDB GUI but keep getting an SyntaxError: invalid syntax error. What am I doing wrong? def get_codes(request): get_code = newsCode.aggregate([{ '$match': { 'site': { '$exists': true }, 'segment': { '$exists': true } }, { '$group': { '_id': { 'site': "$site", 'seg_code': { '$substr': ["$segment", 0, 4] }, 'segment': "$segment" } } }, { '$project': { 'site': "$_id.site", 'seg_code': "$_id.seg_code", 'segment': "$_id.segment" } }, { '$sort': { '_id': 1 } } }]) My error is showing at the , near }, { '$project Why am I getting this error? Like i said it is working when I do this in my GUI. Is there something wrong with my syntax? Is the PyMongo code supposed to be different from the MongoDB code? Please help! -
Django: CSRF Cookie not set in iframe -- workaround without csrf exempt
My project is deploying iframes on several 3rd party sites, that are all known and registered within the django application. In these iframes, users can trigger some ajax-form events. Opening the site directly, everything works fine. If I open the 3rd party site, containing the iframe, django is throwing an error after firing the ajax event (403), saying that CSRF failed. In the form I used {% csrf_token %} which is set in the html. However it does not set the corresponding cookie, when calling the site through the iframe (found out both using inspection mode in browser). I do know that I could use a decorator @csrf_exempt, but that will disable csrf-protection all in one, which I don´t want to do. So my questions are: Why does django not set the CSRF Cookie, when the whole page is loaded through an iframe? Is it possible to get django to set the cookie OR is it possible to only exempt the known urls from csrf? Is there a way I dont see? Thanks a lot for your time! :) -
Adding forgot-password feature to Django 2.1 admin site
I read the documentation but whatever don't understand how to add the forgot-password feature to Django 2.1 admin site, help, please. -
Django nullbooleanfield is defaulting to 'False' when left empty on form, shouldn't be Null?
models.py my_field = models.NullBooleanField(null=True) forms.py my_field = forms.BooleanField( label='my_field', required=False, widget=forms.RadioSelect(choices=[(True,'yes'),(False,'no')])) When the form is submitted without the radio buttons selected, the form saves and defaults to false. Shouldn't it default to Null? -
Django Custom Manager (get Boss' subordinates)
I have two models. Boss: class Boss(models.Model): name = models.CharField(max_length=200, blank=False) company = models.CharField(max_length=200, blank=False) and Employee: class Employee(models.Model): boss = models.ForeignKey(Boss, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False) company = models.CharField(max_length=200, blank=False) I want to create a custom manager that will get Boss' employees, it might be working like this: b1 = Boss.objects.first() b1.subordinates.all() I do not know how to implement this actually. I understand I can do something like this: class SubordinatesManager(Manager): def get_queryset: return super().get_queryset().filter(boss=b1) but this will work only for Employee class. -
Property of a model works in the Python shell but works badly in the Django project
As the title of my question says, I have a Django project in which I have declared some classes in the file "models.py". In it, I have a class, the class "Function", which has declared properties. (Screenshot) Without going into much detail as to what or why I need these properties, it happens to me that when the Django project uses these properties, I get an error. (Screenshot) To my surprise, the project in question has been duplicated. There is a copy that I have locally on my computer, where I started to develop the system, where everything works perfectly. And there is another copy, in the servers of the place where I am working, which is the one that causes me the error that I detail. Both copies have the same project, the same code, the same information, they are identical copies. Finally, I accessed the python shell from the project that generates the error in my workplace server and when I simulate the operation of that module of the system that is failing, I get the results I need: To the same object that uses the Django project that causes that error message, from the shell I call … -
How to access the id of the Primary class in the foreign class in django?
I have 2 model classes(Album and Songs) where Song is d foreign class. I want to access the id of the Album class in the Song class. How can i do that?? -
targeting a column value in a Multicolumns class in a django cms for responsive design
I am working on making the columns created by the user to be responsive. The cms can generate multicolumn from 1 to 10 and every column value can be created with a set width that ranges from 10%, 25%, 33%, 50%, 66%, 75%, 100%. the below image is an example of the user interface I am making a responsive image grid that needs to target all possible column size the one user can make and flex it to a % based on the width size of the column (width:10% than flex:10%): Sample of how the column is generated in code So here is an example of how I have targeted the multicolumn class: .row.cms-extra-style div[class^= "multicolumn"]/*.multicolumn10*/{ display: flex; flex-wrap: wrap; padding: 0 4px; align-items: center; } .multicolumn10>.column{ flex: 10%; max-width: 10%; margin-top: 8px; padding: 0 4px; } However, that says all .multicolumn10 will be 10% which is not the case. The user can make multicolumn10 @ 10%, 25%, 33%, 50%, 66%, 75%, 100%. but the CMS makes it by adding an embedded "style width: %"; so is there a way I can say if this column has a width of % flex: same% in CSS? -
Django Check for user in list
I'm creating a django blog app where users can add comments to articles. I want to remove the post button when the user has already commented. I have a model named article and another one named comment (with ForeignKey to article) I tried {% if any request.user in article.comment_set.all} but that doesn't work. I tried to loop over article.comment_set.all but that didn't work either. Is there a method to do this in the template? -
Seed django with fixtures MultiPolygonField
Got this problem, I have my fixtures ready but many of my models have multiPolygonField that work with GeoDjango. { "model": "country_cities.Country", "pk": 1, "fields": { "name": "Bolivia", "iso_a2": "BO", "iso_a3": "BOL", "numeric": "068", "area_poly": "" } } So, I tried to dump data with the admin generated data. The field is not different from my seeder script that search the country, treat the fields and put them like the MULTILINE format. { "model": "country_cities.Country", "pk": 1, "fields": { "name": "Bolivia", "iso_a2": "BO", "iso_a3": "BOL", "numeric": "068", "area_poly": "MULTIPOLYGON(((MANY POINTS)))" } } In theory django loaddata knows how to treat the data, but I got this error: django.contrib.gis.geos.error.GEOSException: Problem installing fixture JSON_PATH: Error encountered checking Geometry returned from GEOS C function "GEOSWKTReader_read_r". Where JSON_PATH is the file.json. There's something I'm missing about this? -
Saving a model to the database in Django
I am new to django and have been working on a project for a few weeks now. I am making a django application that I host on heroku. I want to schedule a task. The end goal is to make a series of API calls that save the results to a model. I currently have in my app a file scheduler.py from django.core.management.base import BaseCommand, CommandError from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() from fans.models import TotalPageLikes @sched.scheduled_job('interval',minutes=1) def timed_job(): print('This job runs every minute') @sched.scheduled_job('interval',minutes=1) def fan_call(): twr = TotalPageLikes() twr.fans = 50 twr.save() print('should have saved TWR') class Command(BaseCommand): def handle(self, *args, **options): sched.start() In my Procfile I call this web: gunicorn site1.wsgi scheduler: python manage.py scheduler And here is the model class TotalPageLikes(models.Model): fans = models.BigIntegerField() Finally here is my admin from django.contrib import admin # Register your models here. from .models import Fan, Input, TotalPageLikes admin.site.register(Fan) admin.site.register(Input) admin.site.register(TotalPageLikes) Everything deploys and runs successfully, and I can see the results with heroku logs --tail . I see the print statements, but when I open the app in heroku, and navigate to /admin, I see that the model holds nothing. It is not showing an error for the … -
why my django admin causing perfomance issue?
I really need help to understand why django admin causing performance issue? the visvists table has around 1lkh rows and I have to join with around 8 different model classes (with foreign key) to get complete visit data set. I have searched/read a lot about Django admin optimization and I also get the some idea but I couldn't able to implement it on the existing project. below is the snap shot for my admin.py and models.py file. admin.py class VisVisitsAdmin(admin.ModelAdmin): list_display = ('visit_id','program_name','state_name','district_name','block_name','school_name') fieldsets = [ ['General information', { 'fields': ['school_program','visit_id','user'] }], ['Optional Field', { 'classes': ['collapse'], 'fields': [('visit_no', 'is_valid','ac_year')], }], ] def block_name(self, obj): if obj.school_program: # return obj.village.cluster.block.block_name return obj.school_program.school.cluster.block.block_name block_name.short_description = 'block name' def district_name(self, obj): if obj.school_program: # return obj.village.cluster.block.district.district_name return obj.school_program.school.cluster.block.district.district_name district_name.short_description = 'district name' def state_name(self, obj): if obj.school_program: # return obj.village.cluster.block.district.state.name_of_state return obj.school_program.school.cluster.block.district.state.name_of_state state_name.short_description = 'state name' def program_name(self,obj): if obj.school_program: return obj.school_program.program.program_name def school_name(self,obj): if obj.school_program: return obj.school_program.school.school_name admin.site.register(VisVisits,VisVisitsAdmin) model.py class VisVisits(models.Model): visit_id = models.IntegerField(primary_key=True) visit_no = models.IntegerField(blank=True, null=True) school_program = models.ForeignKey(SchProgramForSchools, models.DO_NOTHING, blank=True, null=True) user = models.ForeignKey(UsrUsers, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'vis_visits' def __str__(self): return str(self.visit_id) class SchPrograms(models.Model): program_id = models.IntegerField(primary_key=True) program_name = models.CharField(max_length=200, blank=True, … -
NoReverseMatch at / Reverse for 'news' not found. 'news' is not a valid view function or pattern name
NoReverseMatch at / Reverse for 'news' not found. 'news' is not a valid view function or pattern name. I am making a news website for that i want to get the news for detail by by its slug or id but i didn't get success and i get an error NoReverseMatch at / Reverse for 'news' not found. 'news' is not a valid view function or pattern name. views.py from django.http import Http404 from django.shortcuts import render from django.views.generic import ListView,DetailView from .models import Main class MainListView(ListView): queryset = Main.objects.all() # temp = List.objects.all() template_name = "news/main_list.html" def get_context_data(self, *args, **kwargs): context = super(MainListView, self).get_context_data(*args, **kwargs) context['queryset'] = Main.objects.all() return context class MainDetailSlugView(DetailView): queryset = Main.objects.all() template_name = "news/detail.html" class HeadDetailView(DetailView): #queryset = Product.objects.all() template_name = "head/detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) def get_object(self, *args, **kwargs): request = self.request pk = self.kwargs.get('pk') instance = Head.objects.get_by_id(pk) if instance is None: raise Http404("Product doesn't exist") return instance models.py import random import os from django.core.urlresolvers import reverse from django.db import models from django.urls import reverse from django.db.models.signals import pre_save, post_save def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name,ext def upload_image_path(instence, filename): new_filename = random.randint(1,396548799) name, ext … -
Django CreateView- ModelForm with many-to-many InlineFormset ValueError
I'm struggling with such a problem: I have models: class ForecastType(models.Model): client = models.ForeignKey(Client, related_name="weatherforecast_client") created_by = models.ForeignKey(Forecaster, related_name="weatherforecast_created_by") modified_by = models.ForeignKey(Forecaster, related_name="weatherforecast_modified_by", blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) weather_forecasts = models.ManyToManyField('WeatherForecast') STATUS_CHOICES = ( ("D", "Draft"), ("A", "Active"), ("H", "History"), ) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default="D") class OneDayForecast(ForecastType): def __str__(self): return f"Prognoza pogody dla: {self.client}, wykonana dnia: {self.creation_date}" class WeatherForecast(models.Model): begin_date = models.DateTimeField(blank=True, null=True) finish_date = models.DateTimeField(blank=True, null=True) forecast_type = models.ForeignKey('ForecastType', null=True, blank=True) description = models.TextField(max_length=300, blank=True, null=True) I also have ModelForm and InlineFormset: class OneDayForecastForm(ModelForm): class Meta: model = OneDayForecast exclude = ('weather_forecasts',) WeatherForecastFormset = inlineformset_factory(OneDayForecast, WeatherForecast, exclude=('forecast_type',), extra=2) and finally an CreateView: class OneDayForecast(ForecasterRequiredMixin, CreateView): template_name = "forecaster/one_day.html" success_url = reverse_lazy("forecaster:dashboard") model = OneDayForecast form_class = OneDayForecastForm def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) weather_forecast_form = WeatherForecastFormset() return self.render_to_response( self.get_context_data(form=form, weather_forecast_form=weather_forecast_form) ) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) weather_forecast_form = WeatherForecastFormset(self.request.POST) if form.is_valid() and weather_forecast_form.is_valid(): return self.form_valid(form, weather_forecast_form) else: return self.form_invalid(form, weather_forecast_form) def form_valid(self, form, weather_forecast_form): self.object = form.save(commit=False) for weather_form in weather_forecast_form: weather_object = weather_form.save() self.object.weatherforecast_set.add(weather_object) self.object.save() form.save_m2m() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, weather_forecast_form): return self.render_to_response( self.get_context_data(form=form, weather_forecast_form=weather_forecast_form) ) … -
django project derived from python-socketio django example unable to serve any other URLs
After playing with python-socketios django_example, and seeing that it worked great, I created a new django project, configured it just like the example, copied over the example app to the project (complete with it's overriding of the runserver management command). Everything worked fine, and I was able to make my a few changes so that you can set a nick, some redis stuff to lookup up the sid for a nick, and was able to support sending private messages to a nick. Everything was still working great. I figured the next logical step was to, rather than having to manually set a nick, require the user to login, expose their username as a var in a script block in the template (I moved scripts/index.html to templates/index.html), and automatically have the javascript emit my custom 'set_nick' event with the username automatically upon connect. I defined LOGIN_URL = '/accounts/login' in settings.py, included 'django.contrib.auth.urls' in my urls.py and wrapped the index view with @login_required. It was only then that I noticed that no matter what URL you request, you always get the chat apps index view - no login page redirect, '/admin/' is ignored, etc. Currently, I'm simply using the django development server. … -
Django role based permissions
I'm developing a huge application in django and I need a permission system and I assume that the native user/group permission within django is not sufficient. Here my needs: The application will be available through multiple departments. In each department there will be nearly the same actions. But maybe an user will be allowed to add a new team member in department A and in department B he is only allowed to view the team list and in the other departments he has no access at all. I though using a RBAC system would be most appropriate. Roles must also be inheritable, stored in a model an managable through an interface. Any good ideas or suggestions? Regards -
Django server is not working on Virtual Server
I have a server that is using Ubuntu. I have upload my Django project to the server. And ran the command: python manage.py runserver 0.0.0.0:80 But when I try to go the website in browser I get The requested URL could not be retrieved error. What can be the reason of that? -
Adding conditions to <script src=..> in html using django
html: <body> <script> var participants =[]; </script> {% for player in playerList %} ........... {% empty %} <div style="text-align: center; color: Black; margin-bottom: 90%"> <h2>empty</h2> </div> {% endfor %} <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}"></script> </body> I want want to stop the execution of <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}"> part when participants =[] is empty. How to do that?.