Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to integrate google map into user's profile in django
Any advice would be deeply appreciated am kinda stock here. Am trying to build a app that takes in user's location and display it in form of a map on their profile page. -
Running migrations works locally but not on Travis CI
I have a project in Django 1.8 and I'm starting to use Travis CI, but I have a problem that I cannot solve. When I perform test locally, by python manage.py test, it works fine and there is no problem at running migrations. However, when the same command is executed by Travis, it applies well all migrations except one. The error trace is the following: Traceback (most recent call last): File "EntHub/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle failures = test_runner.run_tests(test_labels) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/test/runner.py", line 210, in run_tests old_config = self.setup_databases() File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases **kwargs File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True), File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db test_flush=True, File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command return command.execute(*args, **defaults) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, … -
InconsistentMigrationHistory with django user_auth
I'm working on my first django project and I'm trying to add user_authentication now. I know i probably should've done this at the very start but I'm trying to do it now. I have a few other apps created and its running fine. However when I added an accounts app i get the following error when i run migrations in accounts/models.py django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. -
Can not Login after enabling template cache
I'm trying to make my Django 1.8 faster by enabling template render cache. So I added this to my setting TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ], }, }] In my test, it gave about 30% page load speed up, however, after enabling it, users can not login ot server. I use redis as cache: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' I tried to somehow replace filesystem.Loader with redis one but failed. How can I solve this? -
Complex inner joins in Django
I have been trying to get this query to work for a couple of hours now and I would love some help since I'm still new to Django. I have these models (simplified) class Job(models.Model): country = models.ForeignKey(Country) active = models.BooleanField() class Country(models.Model): name = models.CharField(max_length=100) class State(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country) class City(models.Model): name = models.CharField(max_length=100) state = models.ForeignKey(State) class Worker(models.Model): name = models.CharField(max_length=100) addresses = models.ManyToManyField(Address) class Address(models.Model): address_field = models.CharField(max_length=100) city = models.ForeignKey(City) I want to select all the distinct and active Jobs on all the Countries which my Worker has an Address on. My view has this code: def get(self, request): worker = Worker.objects.get(pk=request.user.id) full_query = Q(active=True) # my problem is here, since it is a ManyToMany Relationship full_query &= Q(country__id__in=worker.addresses ??????) jobs = Job.objects.filter(full_query) I got this to work getting all the worker's addresses in a for loop and saving the country id in a list and doing country_ids = [] for address in worker.addresses: country_ids.append(address.city.state.country.id) Q(country__id__in=[country_ids] But I think Django has a more elegant way of doing this. Thanks in advance! -
Using CreateView for two ModelForms with uploadfiles
I have some issues with a CreateView with two forms that relate to each via a foreignkey. Oddly I am not even getting any errors in the front end or the back end. All that happens is the page refreshes back with an empty form. If I deliberately put in incorrect data the form will display it. My guess is the error is in the view somewhere. The html will take both forms in correctly and display them properly, but when I click upload, nothing happens, only page is returned with empty forms. The application doesn't get as far as the 'print ('hello') so the error must happen somewhere else. models.py for the Photo model class ImageModel(models.Model): image = models.ImageField(_('image'), max_length=IMAGE_FIELD_MAX_LENGTH, upload_to=get_storage_path) date_taken = models.DateTimeField(_('date taken'), null=True, blank=True, editable=False) view_count = models.PositiveIntegerField(_('view count'), default=0, editable=False) crop_from = models.CharField(_('crop from'), blank=True, max_length=10, default='center', choices=CROP_ANCHOR_CHOICES) effect = models.ForeignKey('PhotoEffect', null=True, blank=True, related_name="%(class)s_related", verbose_name=_('effect')) class Photo(ImageModel): title = models.CharField(_('title'), max_length=60, unique=True) slug = models.SlugField(_('slug'), unique=True, help_text=_('A "slug" is a unique URL-friendly title for an object.')) caption = models.TextField(_('caption'), blank=True) date_added = models.DateTimeField(_('date added'), default=now) is_public = models.BooleanField(_('is public'), default=True, help_text=_('Public photographs will be displayed in the default views.')) sites = models.ManyToManyField(Site, verbose_name=_(u'sites'), blank=True) views.py … -
How to configure baseHref in CkEditor?
I'm using CKEditor for Django, latest version and have it configured for image uploads. The image uploads successfully, but when I send it across to another website via their API, the image URL is local and does not load. I tried to use baseHref, but it seems to have no effect. I'm stuck with this one, can someone help, please? The final image has a URL of something like: https://differentsite.com/media/ckeuploads/2017/03/02/picture1 How do I make it so it comes across like this? https://example.com/media/ckeuploads/2017/03/02/picture1 This is my settings.py for CkEditor: MEDIA_ROOT = '/home/django_uploads/' MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = "ckeuploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'baseHref': 'https://example.com/', 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']}, {'name': 'forms', 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, … -
Elements of CreateView and UpdateView in one form
I've got a fairly simple Django project with 2 models; Action and Comments. An action has any number of comments related to it. These are the models: class Action(models.Model): STATUSES = ( ('R', 'Red'), ('A', 'Amber'), ('G', 'Green') ) name = models.CharField(max_length=255) body = models.TextField() status = models.CharField(max_length = 1, choices=STATUSES) owner = models.ForeignKey(User) class Comment(models.Model): body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) action = models.ForeignKey(Action, related_name="comments") I'm trying to make a CreateView class to add a new comment that includes the 'Status' dropdown from the Action model, in the same form, so users can update the status of the related action as they comment. So far, I've been able to add the comments as an inline formset in an UpdateView for Actions, but this is got messy quickly as the number of comments mounted up and I couldn't figure out a way to show just the extra field of a formset. I've also been able to hardcode in a <select> list in a comment CreateView, then grab elements in the form_valid function. This approach works but it feels very... "bodged". Is anyone aware of a better way? -
Get a historical version of a model
I have two models like these: class Model1: name = models.CharField() class Model2: model1 = models.ForeignKey(Model1, default=get_default_model1) The get_default_model1 function must get a specific instance of Model1 (with a specific name, for example) or create it if it doesn't exist. The problem is that this function is supposed to import Model1 and that is a problem if such model then changes, as an old migration trying to run this function will break. When doing a RunPython operation in a migration you have access to historical versions of a model via the apps argument, but this is not the case. I have written the following code to manually create the historical version of my model: from django.db import models, connection from django.db.migrations.loader import MigrationLoader def get_default_model1(): loader = MigrationLoader(connection) apps = loader.project_state(list(loader.applied_migrations)).apps Model1 = apps.get_model('app', 'Model1') return Model1.objects.get_or_create( name=settings.DEFAULT_NAME, defaults={'name': settings.DEFAULT_NAME} )[0].pk But in some migrations it fails with django.db.migrations.exceptions.NodeNotFoundError: Node ('default', '0004_auto_20160423_0400') not a valid node. It seems to be related to replaced migrations of a third-party dependency. Is there a better way of getting a historical version of my model or accomplishing what I'm trying to do here? -
Django 1.10 SSLv2_method import error when send_mail behind an Apache2.4
I'm trying to install a nearly empty django 1.10 project behind an Apache2 mod_wsgi. In the project settings, I use EMAIL_USE_TLS = True, EMAIL_PORT='587' to send an email via gmail from a web form. I can send the email just fine when I do manage.py runserver standalone at console. But when the django project sits behind Apache2, I'm always getting this error: /home/wr200m/anaconda2/lib/python2.7/lib-dynload/_ssl.so: undefined symbol: SSLv2_method Django 1.10 runs on a Ubuntu 16.04 with python2.7 in a conda virtual environment. The Apache2 serves a few https sites just fine. I understand SSLv2 has largely been deprecated by modern systems and the mod_ssl.conf has the default config (enable all except SSLv3 disabled, and SSLv2 not supported anyways). Why would this SSLv2_method be depended upon anyways? Following is the traceback from Django: Environment: Request Method: POST Request URL: https://wr2opt/contact/ Django Version: 1.10.5 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'contact', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms'] 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 "/home/wr200m/anaconda2/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/wr200m/anaconda2/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/wr200m/anaconda2/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wr200m/workspace/wr200m/optionswww/src/contact/views.py" in contact 20. … -
Apache/Django: ImportError: No module named 'my_project'
Trying to get my django project hosted using apache2 and mod_wsgi. I've tried various configurations, but keep getting import errors when hitting the site in a browser such as: Traceback (most recent call last): File "/home/pi/projects/my_projectMain/my_project/my_project/wsgi.py", line 19, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.4/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.4/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2212, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked ImportError: No module named 'my_project' Here's my directory structure(/home/user/projects/my_projectMain/): -- my_projectEnv\ (virtualenv w/ python 3.5.2, django 1.10, django-bootstrap3, django-static-jquery==2.1.4) -- my_project\ |-- app\ |-- manage.py |-- static\ |-- my_project\ |-- | -- __init__.py |-- | -- __pycache__ |-- | -- settings.py |-- | -- wsgi.py `-- | -- urls.py wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") … -
How to deploy Django app not using Localhost
We have created an app for a production facility that is very simple using django and python. But throughout prototyping we used Runserver command and localhost. The problem is this: We want to deploy the app without using localhost and the command line every time. The people using it wont be able to do this. It will be on implemented on one computer so it shouldnt be that challenging. The app pulls data from one database and stores data in another. It would be nice to have our own URL. Do we need to do it through wsgi? Apache? I know the problem is simple but there seem to be so many ways to deploy and many of them are overcomplicated for our needs. Follow up question: I read that it just using Localhost isnt the best for this type of thing. Is this true? Any help would be great -
ProgrammingError: column "product" is of type product[] but expression is of type text[] enum postgres
I would like to save array of enums. I have the following: CREATE TABLE public.campaign ( id integer NOT NULL, product product[] ) product is an enum. In Django I defined it like this: PRODUCT = ( ('car', 'car'), ('truck', 'truck') ) class Campaign(models.Model): product = ArrayField(models.CharField(null=True, choices=PRODUCT)) However, when I write the following: campaign = Campaign(id=5, product=["car", "truck"]) campaign.save() I get the following error: ProgrammingError: column "product" is of type product[] but expression is of type text[] LINE 1: ..."product" = ARRAY['car... Note I saw this answer, but I don't use sqlalchemy and would rather not use it if not needed. -
How to pass a sorted list (list of dictionaries) to a Django 1.6 template
I have a method that needs to display some data that I create from a model in a sorted manner. I am trying to pass an ordered set to the template. Here's the method: def club_team_results(request, team_id): """Display detailed information for a specific team, including a list of results by event.""" team = Team.objects.get(pk=team_id) team_events_list = EventDivisionTeam.objects.filter(team=team.id).order_by('division__start_date') results={} # Each match result is listed once, this team can be either of team or opposing_team for r in Result.objects.filter(team=team): results[r.id] = {'opponent': r.opposing_team.name, 'outcome': r.outcome, 'scores': r.scores, 'phase': r.phase, 'match': r.match, 'event_division_id': r.division.id, } for r in Result.objects.filter(opposing_team=team): results[r.id] = {'opponent': r.team.name, 'outcome': r.outcome, 'scores': r.scores, 'phase': r.phase, 'match': r.match, 'event_division_id': r.division.id, } context = {'team_events_list': team_events_list, 'team_results': results, 'team': team, } return render(request, 'rank/club_team_results.html', context) I want to pass the results object sorted by the primary key (r.id). I have tried replacing: 'team_results': results with 'team_results': sorted(results.items()) in the context assignment, but no data is passed to the template when I try to sort it. Note that I can't upgrade the Django version at this time (I'll do that this summer), so I'm stuck with 1.6 (currently using Python 3.3 and Django 1.6). Any assistance would be appreciated! -
Annotate using a filtered, index'd model
I am trying to find a way to annotate using a filtered, index'd list. For example, say I have a list of hikes, and I want to take the list of the 5 longest hikes, add them together, and annotate them onto the user. The ultimate goal is to create a sorted list of the Users based on the total distance of their longest 5 hikes. Some code: class Hike(model.Modelform): length = models.IntegerField ... class HikeLog(model.Modelform): user = models.ForeignKey(User, on_delete=models.CASCADE) hike = models.ForeignKey(Hike, on_delete=models.CASCADE) Something like this?? qs = User.objects.all() qs = qs.annotate(totaldistance=Sum(hikelog.order_by('-length')[:5]).order_by('-totaldistance') Which could output a list such as: {% for qs in qs %} {{ qs.user.name }} {{ qs.user.totaldistance }} {% endfor %} User: Total Distance: 3 100mi 1 85mi 2 60mi And so on. Is this possible? I've been trying to figure out a way to do this using Case(), but not having much luck. -
Django filter on attribute with two values, preferring the result of one
This is kind of a weird question, so sorry in advance. I have a model in Django Rest that looks like this: class BaseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True class Foo(BaseModel): barId = models.ForeignKey(Bar, unique=False) fizzId = models.ForeignKey(Fizz, unique=False) buzzId = models.IntegerField(unique=False) value = models.TextField() And I have a ViewSet that needs to return a list of all the Foos that have a given {request_barId, request_buzzId, lastUpdateDate}. This is fairly straightforward, foobar = Foo.objects.filter( buzzId=request_buzzId, modified_date__gt=request_lastUpdateDate, barId=request_barId) Here's the rub. There's a default value for buzzId that is the base list that the specified buzzId needs to overlay, replacing the instances on the base list. That's where I'm getting a little lost. I have a solution, but I feel like it's not particularly elegant and that there's go to be a way to do this cleaner. Here's my code to do the overlay: base_foobar = Foo.objects.filter( buzzId=base_buzzId, modified_date__gt=request_lastUpdateDate, barId=request_barId).exclude( fizzId__in=[o.fizzId for o in foobar]) result = foobar | base_foobar And this just seems really janky. Is there a way to clean this up? -
django datetime to unix timestamp
my model create = models.DateTimeField(auto_now_add=True) how to get unix time from this field? datetime.datetime.timestamp() but I need int -
Javascript in custom Django template tag?
I know it is possible to use a Django variable in Javascript, but is it possible to use a Javascript string as an argument in a custom template tag? e.g. var source = {{ censuses|to_JSON:$('#id_census-0-survey').val()|safe }} where to_JSON is a registered template tag Django 1.10 / Jquery 2.1.3 -
Django and python 2.7 issue with unicode in form error
I'm start new project in TDD idea so first I wrote tests. But I have a problem with utf (I think) I have simple login form from django.utils.translation import ugettext_lazy as _ ERRORS_MESSAGES = { 'not_active': _(u"Użytkownik nie jest aktywny"), 'user_not_exist': _(u"Użytkownik o podanym loginie już istnieje") } class LoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(max_length=50, widget=forms.PasswordInput) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if not user: raise forms.ValidationError(ERRORS_MESSAGES['user_not_exist']) if not user.is_active: raise forms.ValidationError(ERRORS_MESSAGES['not_active']) return self.cleaned_data And in test: user = User.objects.create( username='asd', password='asd', email='asd@ad.asd' ) form = LoginForm(data={'username': 'asd', 'password': 'asd'}) self.assertEqual(form.is_valid(), False) print "ERRORS:", form.errors['__all__'] self.assertIn(ERRORS_MESSAGES['not_active'], form.errors) And console output: # here, char 'ż' looks fine, ERRORS: <ul class="errorlist nonfield"><li>Użytkownik o podanym loginie już istnieje</li></ul> # but next: self.assertIn(ERRORS_MESSAGES['not_active'], form.errors) AssertionError: not found in {'all': [u'U\u017cytkownik o podanym loginie ju\u017c istnieje']} -
django Form validation not working, why?
This is my first project in django and i cant find a problem, Problem: submit button alow even when form is not valid In another form .is_valid() working very good, Maybe not working because one POST sending 2 diferent model, can be true? idea from: http://www.joshuakehn.com/2013/7/18/multiple-django-forms-in-one-form.html Any idea to resolve problem? views.py [...] def reservation_view(request, pk): bus = get_object_or_404(Bus, pk=pk) form_client = ClientForm(prefix='cl') form_var = ReservationForm(prefix='res') if request.method == "POST": form_client = ClientForm(request.POST,prefix='cl') form_var = ReservationForm(request.POST,prefix='res') if form_var.is_valid() and form_client.is_valid(): newreservation = form_var.save(commit=False) newreservation.reBusID = bus newreservation.reClientID = form_client.save() #can be changed i future if the same client newreservation.reDate = timezone.now() #not in use right now newreservation.save() buses = Bus.objects.filter(available_for_cutomers=True) #to dispaly next site if form is valid return render(request, 'busreserv/client.html', {'buses' : buses}) else: form_var = ReservationForm() form_client = ClientForm() return render(request, 'busreserv/newreservation.html', {'formReservation' : form_var, 'bus':bus , 'form_client':form_client}) models.py class Bus(models.Model): # Base model of Bus description = models.CharField(max_length=200) brand = models.CharField(max_length=150) plate_nr = models.CharField(max_length=10) people_capacity = models.IntegerField() price_per_km = models.DecimalField(max_digits=5, decimal_places=2) available_for_cutomers = models.BooleanField(default=True) def __str__(self): return self.plate_nr class Client(models.Model): firstName = models.CharField(max_length=15) lastName = models.CharField(max_length=15) clientEmail = models.CharField(max_length=15) clientPhone = models.CharField(max_length=15) def __str__(self): return self.lastName class Reservation(models.Model): reBusID = models.ForeignKey( 'Bus',blank=True, null=True) reClientID = models.ForeignKey( 'Client',blank=True, … -
Django - How do I use the URL template tag in a format_html safe string?
I'm trying to include the URL template tag in a string that I have created using the format_html method: message = format_html( '''<div> <p>{0} wants to join {1}!</p> {% url 'accounts:detail' pk={2} as profile_url %} <p> View their <a href="{{ profile_url }}">profile</a> </p> <div>Approve</div> <div>Deny</div> </div> ''', self.request_user.username, self.lab.name, self.request_user.pk) The html that is outputted to the browser looks like this: <a href="{ url 'accounts:detail' pk=4}">profile</a> Basically my url tag without the %'s. I have tried escaping the % by typing: {%% url 'accounts:detail' pk={2} as profile_url %%} But I receive the same output. Any ideas? -
Lists are not currently supported in HTML input
I am using Django REST generic views for my API endpoint. One of the field in my serializer has ManyToMany relationship. I want to show that field into my API endpoint, But getting this error Lists are not currently supported in HTML input. What can I do ? class AlertCreateView(ListCreateAPIView): permission_classes = (IsAuthenticated,) pagination_class = None serializer_class = AlertSerializer def get_queryset(self): queues = Queue.objects.all() for queue in queues: queryset = Alert.objects.filter( queue=queue ) return queryset My Serializer is this: class AlertSerializer(serializers.ModelSerializer): queue = QueueSerializer(many=True) class Meta: model = Alert fields = ( 'id', 'name', 'queue','email', 'expected_qos' ) -
Django custom button counter
I want to have 2 buttons at the bottom of my each post like that: I need suggestions how could I achieve that. I tried django-vote library, but it does not work for me. My code: <--template.html--> <div class="post-bottom overflow"> <ul class="nav navbar-nav post-nav"> <li><a href="#"><i class="fa fa-tag"></i>0 Creative</a></li> <li><a href="#"><i class="fa fa-heart"></i>32 Love</a></li> </ul> </div> _ ###**VIEWS.PY**### class IndexView(generic.ListView): template_name = 'web_serv/index.html' context_object_name = 'post_list' paginate_by = 10 def get_queryset(self): queryset = Post.objects.all() if self.request.GET.get('category'): queryset = queryset.filter(category=self.request.GET.get('category', '')) return queryset def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['category_list'] = Category.objects.all() return context _ #models.py# class Post(VoteModel, models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=40) category = models.ForeignKey(Category) picture = ImageWithThumbsField(sizes=((850, 400), (66, 66))) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-created_date'] def __str__(self): return self.title + ' - ' + str(self.created_date.date()) Any suggestions are welcome :) -
Are Django Channels WebSocketConsumers stateless
I'm trying to use Django channels to create an object that stays persistent for everyone connected to the socket/ When I try to create an object that stays persistent between multiple receive() runs, it throws a NoneType exception class MyConsumer(WebsocketConsumer): def __init__(self,path): self.protocol = None WebsocketConsumer.__init__(self, path) def connection_groups(self): return ["test"] # Connected to websocket.connect def connect(self,message): try: self.protocol = "hello" except Exception as exc: print ("Unable to accept incoming connection. Reason: %s" % str(exc)) self.message.reply_channel.send({"accept": True}) # Connected to websocket.receive def receive(self,text=None, bytes=None): text = self.protocol[1] # This throws an error that says protocol is none self.send(text=text, bytes=bytes) # Connected to websocket.disconnect def disconnect(self,message): pass -
Django Data synchronisation between local and online server
I got a local server running a djanago application only for local use in this network.(1) Now I want to have some sort of report site that can be accessed from the Internet. Also as a django app. (2) My question is now what is the best way to get the data from 1 regarding security and usability.