Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'product_list_by_category' with arguments '('',)' not found. 1 pattern(s) tried: ['en/(?P<category_slug>[-\\w]+)/$']
Reverse for 'product_list_by_category' with arguments '('',)' not found. 1 pattern(s) tried: ['en/(?P<category_slug>[-\\w]+)/$'] 1 {% load i18n %} 2 {% load static %} 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="utf-8" /> 7 <title>{% block title %}{% trans "My shop" %}{% endblock %}</title> 8 <link href="{% static "css/base.css" %}" rel="stylesheet"> 9 </head> 10 <body> This is the error I am getting, I saw some answers to the questions similar to my problem and they suggested to correct the url but my url is already according to the answers. This is my first course django and I am at lost. Please help Here is my model: class Category(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True, unique=True) ) class Meta: #ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Product(TranslatableModel): category = models.ForeignKey(Category, related_name='products') translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True), description = models.TextField(blank=True) ) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) #index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, … -
Django orm: Build many-to-many query for django-cities
I am using django-cities and I want to get all cities within Germany starting with the letter A. Here is the complete source code of the model: https://github.com/coderholic/django-cities/blob/master/cities/models.py And here a simplified version: class City(): name_std = models.CharField(max_length=200, db_index=True, verbose_name="standard name") name = models.CharField(max_length=200, db_index=True, verbose_name="ascii name") alt_names = models.ManyToManyField('AlternativeName') country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='cities', on_delete=SET_NULL_OR_CASCADE) class AlternativeName(SlugModel): name = models.CharField(max_length=255) language_code = models.CharField(max_length=100) is_preferred = models.BooleanField(default=False) is_short = models.BooleanField(default=False) is_colloquial = models.BooleanField(default=False) is_historic = models.BooleanField(default=False) So to get all Cities within German I use the following query: country = Country.objects.filter(code=settings.COUNTRY_CODE).first() City.objects.filter(country=country, name__istartswith="A") This is fine, but I want the German name (Which is stored in AlternativeName, so I do something like: country = Country.objects.filter(code=settings.COUNTRY_CODE).first() City.objects.filter(country=country, alt_names__name__istartswith="A", alt_names__language_code='de') This is working in some cases. But sometime there are more alternative names for for one language. Can I order somehow the alternative names ( .order_by(is_prefered, is_historic, -is_colloquial) ...) and pick only the first result? -
Check python/django library dependencies
I have discovered that I have an installed library in my django app(as a dependecy for another one i think) and I want to know which package/library has introduced. How can I do that the installed library is: pathspec my requirements.txt file is: Babel==2.4.0 boto3==1.4.8 coreapi==2.3.3 coreschema==0.0.4 django-admin-list-filter-dropdown==1.0.1 django-admin-sortable2==0.6.19 django-background-tasks==1.1.12 django-categories==1.5.4 django-ckeditor==5.3.1 django-cors-headers==2.1.0 django-filter==1.0.4 django-import-export==1.0.0 django-markdownx==2.0.22 django-object-actions==0.10.0 django-rest-auth[with_social]==0.9.2 django-simple-metatags==0.9.1 django-static-sitemaps==4.4.0 django-storages==1.5.2 django-taggit==0.22.2 django-taggit-helpers==0.1.4 Django==1.11.10 djangorestframework~=3.6.4 djangorestframework-jwt==1.11.0 factory-boy==2.8.1 itsdangerous==0.24 jellyfish==0.5.6 mailjet-rest==1.3.0 mdx-video==0.1.8 Pillow==4.1.1 psycopg2==2.7.3.2 pyembed-markdown==1.1.0 python-dotenv==0.7.1 raven==6.1.0 requests==2.14.2 six==1.11.0 snapshottest==0.5.0 uritemplate==3.0.0 python-memcached==1.59 -
Django Password Validation string
Is there Any Possible change to change Django Validation string kinda like this : Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. I want different validation rule where can i find this ?? or is it possible to change i am using django auth system -
Test case failing when I simulate Image uploading
I have implemented a test case that has an object that requires has an image field to be uploaded(below you will find the model details). When I run it the test is failing. I did further debugging to print out the response.data in the test file I get a None value which clearly indicates that nothing has been uploaded. I believe the problem might be in my views below you will find how I have implemented the post method. How do i fix this ? test.py def test_can_create_employee_document(self): url = reverse('hr:employee_documents') # Create Dummy Image """uploaded""" filename = 'img' file = File(open('media/documents/keyboard-layer1.png', 'rb')) document = SimpleUploadedFile(filename, file.read(), content_type='multipart/form-data') data = { "employee":1, "document":document, "details": "certifications", "organizations":2 } # client = APIClient() self.client.credentials( HTTP_AUTHORIZATION=token_retrieve(self)) response = self.client.post(url,data, format='multipart') print(response.data) self.assertEqual(response.status_code, 201) I have created a testcase for the following model: models.py class EmployeeDocument(models.Model): """ Model, Which holds Employee documents uploaded. :type employee : integer :param integer: the employee ID :type document: string :param document: the employee's document :type detail: string :param detail: the details about employee's document :type upload_date: string :param upload_date: the date uploaded :type organization: integer :param organization: organization ID """ employee = models.ForeignKey( Employee, related_name="employee_docs", null=True, blank=True) document … -
Django not loading static files
I created added a dashboard to my project it is using bootstrap files which I am trying to load but aren't loading. I am trying to load static file using {% static '' %} and it's now picking up the files. You can ask for further code. Here is the code of the template <link href=" {%static '../static/Dashboard/assets/css/bootstrap.min.css'%}" rel="stylesheet" /> <link href="{%static '../static/Dashboard/assets/css/bootstrap.min.css '%}" rel="stylesheet"/> <link href="{% static '../static/Dashboard/assets/css/paper-dashboard.css' %}" rel="stylesheet"/> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet"> <link href='https://fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'> <link href=" {%static '../static/Dashboard/assets/css/themify-icons.css' %}" rel="stylesheet"> Setting in setting.py STATICFILES_DIR=[ os.path.join(BASE_DIR, "static"), 'final_project/static', ] STATIC_URL = '/static/' -
django-channels: differentiate between different `AnonymousUser`s
Unfortunately I'm using django-channels channels 1.1.8, as I missed all the updates to channels 2.0. Upgrading now is unrealistic as we've just launched this will take some time to figure out correctly. Here's my problem: I'm using the *message.user.id *to differentiate between authenticated users that I need to send messages to. However, there are cases where I'll need to send messages to un-authenticated users as well - and that message depends on an external API call. I have done this in ws_connect(): @channel_session_user_from_http def ws_connect(message): # create group for user if str(message.user) == "AnonymousUser": user_group = "AnonymousUser" + str(uuid.uuid4()) else: user_group = str(message.user.id) print(f"user group is {user_group}") Group(user_group).add(message.reply_channel) Group(user_group).send({"accept": True}) message.channel_session['get_user'] = user_group This is only the first part of the issue, basically I'm appending a random string to each AnonymousUser instance. But I can't find a way to access this string from the request object in a view, in order to determine who I am sending the message to. Is this even achievable? Right now I'm not able to access anything set in the ws_connect in my view. -
Using a model's sub-classes as choice options for that model raises ImportError
We are trying to upgrade a legacy code's django version from 1.8 to 1.9. We have one model that is defined like this: def _get_descendant_question_classes(): stack = [Question] while stack: cls = stack.pop() stack.extend(cls.__subclasses__()) yield cls def _get_question_choices(): question_classes = _get_descendant_question_classes() for cls in question_classes: yield (cls.slug, cls._meta.verbose_name) class Question(models.Model): type = models.CharField(max_length=10, choices=_get_question_choices(), default=slug) class TextQuestion(Question): pass class SelectQuestion(Question): pass ... Basically the model wants to use its sub-classes as choice options for one of its fields. It does this with traversing the model in a DFS manner and yielding all the sub-classes. This code works in django 1.8 but in django 1.9 it gives this error: Traceback (most recent call last): File "./manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 324, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/saeed/saeed/survey/models.py", line 85, in <module> class Question(models.Model): File "/home/saeed/saeed/survey/models.py", line 99, in Question type = models.CharField(max_length=10, choices=_get_question_choices(), default=slug) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 161, in __init__ choices = … -
Django : How to get longitude and latitude from google maps user selected adress and save to database
I am new to Django and Python. I want to make a view in which user can open the google maps ( or anything similar), choose a location (put a thumbtack) on map and get the longitude and latitude from this location to save to database. I searched the internet but i am confused about how to do it Can you please , guide me where to look or what to use? Many thanks for spending your time to help me Kostas -
Are proxies possible while django test client?
I am using pytest to test my code using django test client to hit my APIs. This allows me to use mocking and makes my test faster as well. A requirement has come up where I now have to hit a security tool which is behind a proxy which would validate the various parameters of the test so that these tests do not compromise on the security of the application. So, just want to know if it is possible to hit a proxy while using Django's test client something like what requests does? If this does not work, I would have to start hitting my application using requests or urllib which make me forego my mocking capabilities which I don't want to do. Thanks in advance for the help! -
Get And Post in Django
I am new to Django rest framework, I am used to develop APIs in .net I want to to create 2 APIs one get which gets the Article and Image related to it by pk id, and one post which adds article and photo, I have tried different methods but couldn't get what I want, if anyone can help or share some site where I can learn such thing, that would be great, Thanks in advance PS: select_related is only giving me id of article model. These are my 2 models: from django.db import models class Article(models.Model): Heading = models.CharField(max_length=200, null=True) Article = models.TextField(null=True) CreatedBy = models.IntegerField(null=True) CreatedDate = models.DateTimeField(null=True) IsDeleted = models.BooleanField(default=False) class ArticleImage(models.Model): Image = models.ImageField(upload_to='photos/', null=True) ImageArticle = models.ForeignKey(Article, on_delete=models.CASCADE) and these are my serializers: from rest_framework import serializers from .models import Article, ArticleImage class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'Heading', 'Article') class ArticleImageSerializer(serializers.ModelSerializer): class Meta: model = ArticleImage fields = ('id', 'Image', 'ImageArticle') and these are my views: from django.shortcuts import render from django.views import View from rest_framework import views from rest_framework import viewsets from .models import Article, ArticleImage from .serializers import ArticleSerializer, ArticleImageSerializer from itertools import chain from rest_framework.views import APIView … -
Dynamic hrefs(URLs) in Django
I tried a lot but can't reach to a solution from two days. First lets dive into the code: This is my urls.py from django.conf.urls import include, url from django.contrib import admin from dashboardhome.views import DashboardHomeViewClass from dashboardhome.views import login_view from django.contrib.auth.views import login from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', login ,{'template_name': 'login_template.html'}), url(r'^dashboard/(?P<slug>\w+)/$', login_required(DashboardHomeViewClass.as_view()),name = "dashboard"), ] This is the view class in views.py: from django.shortcuts import render,redirect from django.views import View from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login from django.views.generic import TemplateView, ListView from dashboardhome.models import device_parameter_data from dashboardhome.models import device_user_data class DashboardHomeViewClass(View): def get(self, request, *args, **kwargs): device_user_objects = device_user_data.objects.filter(User_Name = request.user.username) device_parameter_objects = device_parameter_data.objects.all() device_alias_list = [] device_id_list = [] queryset = [] light_list = [] for device in device_user_objects: device_alias_list.append(device.Device_Alias_Data) device_id_list.append(device.Device_Id_Data) # print(device_id_list) slug = self.kwargs.get("slug") for device_id in device_id_list: if slug == device_id: queryset = device_parameter_objects.filter(Device_Id = slug) for data_object in queryset: light_list.append(data_object.Light) context_logged = {'device_user_objects': device_user_objects, 'light_list': light_list} return render(request, "dashboardhometemplate.html", context_logged) Here is my database models: from django.db import models from django.utils import timezone class device_parameter_data(models.Model): Device_Id = models.CharField(max_length=10) Light = models.IntegerField(null = True) updated_time = models.DateTimeField(auto_now=True, null = False) def __str__(self): return self.Device_Id class device_user_data(models.Model): User_Name … -
Start SQS celery worker on Elastic Beanstalk
I am trying to start a celery worker on EB but get an error which doesn't explain much. Command in config file in .ebextensions dir: 03_celery_worker: command: "celery worker --app=config --loglevel=info -E --workdir=/opt/python/current/app/my_project/" The listed command works fine on my local machine (just change workdir parameter). Errors from the EB: Activity execution failed, because: /opt/python/run/venv/local/lib/python3.6/site-packages/celery/platforms.py:796: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! and Starting new HTTPS connection (1): eu-west-1.queue.amazonaws.com (ElasticBeanstalk::ExternalInvocationError) I have updated celery worker command with parameter --uid=2 and privileges error disappeared but command execution is still failed due to ExternalInvocationError Any suggestions what I do wrong? -
Missing object in ManyToManyField when retrieved within Celery task
Let's say that I have a Django model called Pizza. It has a field toppings wich is a ManyToManyField. I put some objects in there (which are of PolymorphicModel class). Next, there's a Celery task which finds that particular Pizza object and lists those toppings. Turns out, one of those toppings is missing. I see it in the Django admin, it's also present when I retrieve the Pizza object with manage.py shell, but never in Celery. What's so different about Celery, that the outcome of toppings.all() is not the same as in other circumstances? I'm using celery==4.1.1, django==2.0.2 and django-polymorphic==2.0.2. -
why the team names are not displaying in django html?
migrations.CreateModel( name='BasketballScore', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('match_played', models.IntegerField(default='0')), ('lose', models.IntegerField(default='0')), ('win', models.IntegerField(default='0')), ('points', models.IntegerField(default='0')), ('team', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teams_basketball', to='Schedule.Team')), ], ), This is the portion from my migration folder, i think this is confirming that my BasketballScore model is migarted fine. class BasketballScore(models.Model): team = models.ForeignKey(Team, related_name='teams_basketball', on_delete=models.CASCADE) match_played = models.IntegerField(default='0') lose = models.IntegerField(default='0') win = models.IntegerField(default='0') points = models.IntegerField(default='0') This is the actual model of BasketballScore. class BasketballScoreView(generic.ListView): context_object_name = 'matches' template_name = 'Schedule/basketball_score.html' queryset = BasketballScore.objects.all() def get_queryset(self): return BasketballScore.objects.all().order_by('-points') This is the corresponding class BasketballScoreView in views.py. {% extends 'Schedule/base.html' %} {% block content %} <div class="container"> <p><button onclick="window.location='{% url 'index' %}'" class="btn btn-default">Go Back</button></p> <div class="table-responsive"> <table class="table table-bordered table-hover"> <tr> <th>Teams</th> <th>Match</th> <th>Win</th> <th>Lose</th> <th>Points</th> </tr> {% for match in matches %} <tr> <td> <div style="width='100';height='20'"><img src="{{ match.team.image.url }}"></div> {{match.team}} </td> <td><div class="text-center">{{match.match_played}}</div></td> <td><div class="text-center">{{match.win}}</div></td> <td><div class="text-center">{{match.lose}}</div></td> <td><div class="text-center">{{match.points}}</div></td> </tr> {% endfor %} </table> </div> </div> {% endblock %} Now this is the basketball_score.html page. <!DOCTYPE html> <html lang="en"> <head> <style> .horizontal { display: inline; background-color: lightgray; } </style> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Schedule</title> {% load static %} <!-- <link rel="stylesheet" href="{% static 'Schedule/css/bootstrap.css' %}" /> <link rel="stylesheet" href="{% … -
Django: query in multiprocessing occurs django.db.utils.OperationalError: SSL error?
I used Django 1.11.1 and PostgreSQL as a database. Here is the code: models.py class Symbol(StockDataBaseModel): code = models.CharField(max_length=20) name = models.CharField(max_length=30) class DailyPrice(StockDataBaseModel): symbol = models.ForeignKey(Symbol) date_time = models.DateTimeField() open = models.DecimalField(max_digits=15, decimal_places=2) high = models.DecimalField(max_digits=15, decimal_places=2) low = models.DecimalField(max_digits=15, decimal_places=2) close = models.DecimalField(max_digits=15, decimal_places=2) Getting data part def _get_price_df(ticker, start_date, end_date): from data_manager.models import DailyPrice, Symbol symbol_set = Symbol.objects.prefetch_related('dailyprice_set').filter(name__iexact=ticker) if symbol_set.exists(): symbol = symbol_set[0] if start_date and end_date: price_set = symbol.dailyprice_set.filter(Q(date_time__gte=start_date) & Q(date_time__lte=end_date)) elif start_date: price_set = symbol.dailyprice_set.filter(Q(date_time__gte=start_date)) elif end_date: price_set = symbol.dailyprice_set.filter(Q(date_time__lte=end_date)) else: price_set = symbol.dailyprice_set.all() else: raise ValueError("No such ticker exists : {}".format(ticker)) class StockDailyDataManager(object): def get_price_data_df(self, tickers, start_date=None, end_date=None): pool = Pool(12) df_list = pool.starmap( _get_price_df, [(ticker, start_date, end_date) for ticker in tickers] ) What I tried: tickers = ['MSFT', 'AAPL', 'samsung'...] pool = Pool(12) df_list = pool.starmap( _get_price_df, [(ticker, start_date, end_date) for ticker in tickers] ) It occurred Error: django.db.utils.OperationalError: SSL error: decryption failed or bad record mac How can I solve this? -
Music stops when page changes Django
I have a music app and I am using JPlayer to stream the music on the page. When I go to another page music stops, I need a way out to make the steam seamless around all the pages. I am using Djnago 1.11 and Django Rest Framework. -
HTML <audio> is showing "live broadcast" on mobile
I'm using Django to point to the mp3 files in the media folder like this: <audio controls autoplay preload=auto controlsList="nodownload" id="audioPlayer"> <source src="../media/{{ article.sound }}" type="audio/mpeg"> Your browser does not support the audio element. </audio> I have no issue in the web browser, but when I use Safari on my iPhone it shows "live broadcast" instead of the standard interface with timeline. The same question was asked 8 years ago, but I don't understand how I should solve the problem. Also, 8 years is a long time in this context. HTML5 <audio> Safari live broadcast vs not -
Django Website If Search
I'm confuse with Python if I make four imput text for search filter. In Debug, I tried "x is not None" or " x != None " But it can't work. [Working fine Result while request have parameters] [Working bad while request does not have any parameters]1 def search(request): good = request.GET.get("q2") buyer = request.GET.get("q3") StartTime = request.GET.get("SD") EndTime = request.GET.get("ED") context = {} if good is not '' or buyer is not '': if good != '' and buyer != '': context = Dlyndx.objects.filter( Q(date__gt=StartTime),Q(date__lte=EndTime), Q(dlysale__btype__exact=buyer)&Q(dlysale__ptype__exact=good) | Q(dlybuy__btype__exact=buyer)&Q(dlybuy__ptype__exact=good)) return render_to_response('search.html',{'context':context}) elif good != '' and buyer == '': context = Dlyndx.objects.filter( Q(date__gt=StartTime),Q(date__lte=EndTime), Q(dlysale__ptype__exact=good) | Q(dlybuy__ptype__exact=good)) return render_to_response('search.html',{'context':context}) else: context = Dlyndx.objects.filter( Q(date__gt=StartTime),Q(date__lte=EndTime), Q(dlysale__btype__exact=buyer) | Q(dlybuy__btype__exact=buyer)).distinct() return render_to_response('search.html',{'context':context}) else: return render(request,"search.html") -
start working with the next JSON block if the current one does not exist
I'll start from what I get, it's a test query where every block exists in the json structure, and everything is close: def main(request): req = requests.get('https://d3.ru/api/posts').json() arr = [] for data in req['posts']: urls = data['main_image_url'] if urls != None: arr.append(urls) return render(request, 'main.html', {'arr': arr}) Next, I begin to delve into the structure of json: def main(request): req = requests.get('https://d3.ru/api/posts').json() arr = [] for data in req['posts']: urls = data['data']['media']['thumbnails']['original']['url'] if urls is not None: arr.append(urls) return render(request, 'main.html', {'arr': arr}) But it gives an error 'NoneType' object is not subscriptable, as far as I understand, this block does not exist for all elements, or the problem is in something else? If everything is the same as I think, then how to start processing the next block if this one does not exist? Unfortunately, I can not put json here, it's too long. -
Django: Haystack and Elasticsearch with Mongoengine
I am trying to integrate Haystack Elasticsearch with my django REST application that uses MongoDB as database. Here is my source code: models.py class Books(Document): ISBN = fields.StringField(null=False, required=True) book_name = fields.StringField(null=False, required=True) genre = fields.StringField(null=False, required=True) author = fields.StringField(null=False, required=True) publisher = fields.StringField(null=False,required=True) price = fields.IntField(required=True) stock = fields.IntField(required=True) search_indexes.py class BookIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) book = indexes.CharField(model_attr="book_name") price = indexes.CharField(model_attr="price") def get_model(self): return Books def index_queryset(self, using=None): return self.get_model().objects.filter( created__lte=timezone.now() ) serializer.py class BookIndexSerilizer(HaystackSerializer): class Meta: index_classes = [BookIndex] fields = [ 'text', 'book', 'price' ] views.py class BookSearchView(HaystackViewSet): index_models = [Books] serializer_class = BookIndexSerilizer urls.py router = routers.DefaultRouter() router.register('search/', BookSearchView, 'Books') settings.py HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://localhost:9200/', 'INDEX_NAME': 'haystack', }, } When i hit the search URL i get following exception: AttributeError('The model being added to the query must derive from Model.'). What is going wrong? -
Javascript Websocket closed unexpectedly when script is loaded externally
While building a chat application in Django, I used embedded javascript and it worked. But, if I write the same code in external javascript then the WebSocket gets closed. I have checked all the links and static file path. The script is loaded completely but the WebSockets gets closed after they open. Here's the tutorial from Official Django Channels website, and that javascript is working in embedded form only not in an external script. And, here's my Github repo where I've implemented Websockets. How can I write JS code in external script instead of embedded? I've Googled but found no help and even this question hasn't been answered yet. Here's the code I'm talking about and the websockets won't work if defined externally: <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br/> <input id="chat-message-input" type="text" size="100"/><br/> <input id="chat-message-submit" type="button" value="Send"/> </body> <script> var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = … -
how to add alt tag automatically for images in django?
I have an admin panel in my site that my admins add articles on it. I want when they upload content to the site with image - the title of the content will be also the image title. Can anyone help me to change my script? Right now this is my script: I would be very grateful for any help. Thanks <article class="post"> <div> <img alt="" class="img-responsive" src="{{ article.card_image_thumbnail.url }}" style="margin-bottom:18px;"> </div> <h1 class=" fa-font-justify-fix " <a href="/article/{{ article.slug }}/">{{ article.title }} </a></h1> <div> <p class=" fa-font-justify-fix "> {{ article.description|striptags|truncatewords:30 }} </p></div> <hr> <div class="post-meta"> <span><i class="fa fa-calendar"></i> {{ article.publish_date|date:"M d" }}</span> <span><i class="fa fa-eye"></i> {{ article.hitcounter_set.first.hitcount }}</span> <a href="/article/{{ article.slug }}/" class="read-more pull-right"> More detail <i class="fa fa-angle-left"></i></a> </div> </article> -
Obtaining ID of form in a formset
I need a way to set the id of the div that contains each form in a formset to a value that contains a number that is representative of the index of that form. eg. I want the 2nd form to have a parent div that looks like this <div id="1"> #id could even be "id_form-1-id". form </div> I've found that {{form.id}} produces the following: <input type="hidden" name="form-3-id" id="id_form-3-id"> Is there a way that I can extract just the id value (i.e. id_form-3-id) from this string using a template tag? For reasons that I won't get into, a forloop.counter counter won't reliably return an index as some forms within the formset can be created outside of the typical formset for loop. Thanks! -
How to check the details of foreignkey before creating object in the form?
In the Django project I'm working on there is model called Course and it contains many Assignment objects. This is a part of models.py: class Assignment(models.Model): course = models.ForeignKey(Course, related_name='get_assignments') name = models.CharField(max_length=200) ipaddress = models.CharField(null=True, max_length=500) publish_type = models.CharField(max_length=50, default="Scheduled") type_of_lab = models.CharField(max_length=50, default="Lab") timeduration = models.DurationField(default=timedelta(seconds=0), null=True) late_duration = models.DurationField(default=timedelta(seconds=0), null=True) exam_group_id = models.CharField(max_length=50, null=True) serial_number = models.IntegerField() program_language = models.CharField(max_length=32) duration = models.DurationField(default=timedelta(seconds=0), null=True) freezing_duration = models.DurationField(default=timedelta(seconds=0), null=True) deadline = models.DateTimeField(null=True) freezing_deadline = models.DateTimeField(null=True) publish_on = models.DateTimeField(null='true') bulk_add = models.FileField(max_length = 800,upload_to=assignment_bulk_upload_path, null=True) When creating an assignment through form, the form is validated using some functions. This is part of forms.py: class AssignmentForm(forms.Form): assignment_type = forms.BooleanField(required=False, widget=forms.HiddenInput()) name = forms.CharField(label="Assignment Name", widget=forms.TextInput(attrs={'placeholder':'Assignment Name (200 Characters or fewer)','maxlength':200})) Typeof = (('Lab', 'Lab'), ('Exam', 'Exam')) publishtype = (('Scheduled', 'Scheduled'), ('On Demand', 'On Demand')) publish_type = forms.ChoiceField( choices=publishtype, label="Choose type of Publish (Default : Scheduled)" ) duration = forms.DurationField( label="Assignment Duration", required=False, help_text="Assignment Duration, input format is HH:MM:SS " ) freezing_duration = forms.DurationField( label="Freezing extra time", required=False, help_text="Extra time for students to freeze submission, input format is HH:MM:SS " ) bulk_add = forms.FileField( error_messages={'invalid': 'File was not a valid tar file.'}, required=False, label="Add sections and/or test cases in bulk", ) …