Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
localStorage.getItem return string, how to get an array and loop through it, also how to compare against existing data if the data id still there?
I have a page lists ads. each ad has a favorite icon. user can click on icon for every single ad to add it to the favorite list. The favorite list is stored on local storage(using cookies). I have made everything. the code works fine ( store selected data). I wrote a code to pull stored favorite ads once the page is loaded. I want to populate the favorite icons with previously favorited ads(data obtained from local storage). The icons has class (fa-star-o) while favorite icons should have class(fa-star). Hence, I need the following Two tasks: 1- I want to find the ads IDs stored on the local storage. Then loop through them and change the icons class based on them. 2- I want to compare existing IDs with current IDs come from the data base because every ads expires after 45 days and will be removed from the data base. How can I do that? The existing problem is the data came from local storage return as string. I did made the following code to make it an array: var stored_fav = JSON.parse("["+localStorage.getItem('SL_favourites')+"]"); The result is an array. However,when I loop through this array, I expect to have all … -
Django Infinite scroll using Django Paginate repeating the queryset
Intro: I am using the the below link to add infinite scroll to my project https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html below is the github code for that link https://github.com/sibtc/simple-infinite-scroll The link shows how to add infinite scroll to both function based views and class based views. I have added this to my function based view and it works perfect. The problem: I have 8 posts in my post-list which is a class-based view. After I add paginate_by = 3 I can only see 3 posts of the 8 posts. Everytime I scroll down these 3 posts keep repeating in an infinite loop My Views: class Postlist(SelectRelatedMixin, ListView): model = Post select_related = ('user', 'group') paginate_by = 3 context_object_name = 'post_list' template_name = 'posts/post_list.html' My Base.html: (I have the below files in JS folder they worked for my FBV) <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> {% block javascript %}{% endblock %} My post_list.html: <div class="col-md-8"> <div class="infinite-container"> {% for post in post_list %} <div class="infinite-item"> {% include "posts/_post.html" %} <!---This code is good----> </div> {% empty %} some code {% endfor %} </div> <div class="loading" style="display: none;"> Loading... </div> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ … -
Cannot access python shell from virtualenv and Django
I'm on Windows 10. I tried to install channels to use websockets with Django but it doesn't work. I got the following error : Failed building wheel for Twisted I have still not succeeded to install channels. But now I have a new problem, I can no anymore access Python shell from my virtual environment that I use for Django. (myproject) D:\Django\mysite>py manage.py shell Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\kevin\Envs\myproject\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'channels' I have no idea to solve my problem ... Someone could bring me help ? -
Python- Google NLP Api returns ssl.SSLEOFError: EOF occurred in violation of protocol
I'm working on a project using Python(3.6) in which I need to process too many files from a directory by using Google cloud natural language processing API, but after processing ~100 files it returns an error as: ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:852) [29/Dec/2018 13:27:33] "POST / HTTP/1.1" 500 17751 Here's from views.py: def nlp_text_manager(text_path, name): text = text_path # encoding = predict_encoding(text_path) # print('encoding is: {}'.format(encoding)) txt = Path(text_path).read_text(encoding='utf8') service = discovery.build('language', 'v1beta2', credentials=credentials) service_request = service.documents().analyzeSentiment( body={ 'document': { 'type': 'PLAIN_TEXT', 'content': txt } } ) response = service_request.execute() return response -
is there any elegant way to get data from 3 options?
I need to get title from data or instance or None actually there may not be any instance then None something like this title = data.get('title', None) but also try to get from instance if possible title = data.get('title', instance.title, None) -
Extract value from cookie
With _ga = request.COOKIES.get('_ga') I e.g. GA1.1.1432317817.1125843050. I now have to define everything behind GA1.1.in a new variable. However, GA1.1. could also be GA1.2. etc. The dots are consistent. How would you extract it? -
Does Django's csrf_exempt decorator remove all POST data?
I have a Django view which returns a list of objects, or allows you to create one if you POST... @csrf_exempt def quantities(request): if request.method == "POST": kwargs = {**request.POST} print(request.POST) quantity = Quantity.objects.create(**kwargs) return JsonResponse({"quantity": f"/quantities/{quantity.id}/"}) return JsonResponse([], safe=False) If it gets a GET request it returns a list of quantities (code not shown), which works fine, and if it gets a POST request it uses POST data to create a new quantity. (I'm aware DRF does all this for you, but for my first API I wanted to try doing it manually - you just understand it better that way.) Anyway in my test, I use requests to check this works... response = requests.post( self.live_server_url + f"/quantities/", data={ "name": "Height", "units": "m", "description": "Human Height" } ) This doesn't work - it doesn't pass any data. That print statement in the view above just prints <QueryDict: {}>. For some reason the POST data that I put in the request has gone from the request by the time it passes through all the middleware and gets to the view. The only thing I can think of is that the @csrf_exempt decorator is removing POST data, though I can't imagine … -
Error while using ckeditor with django version 2.x
Before marking this question duplicate or anything please be informed I researched stack overflow and ckeditor documentation and configured accordingly. first i install ckeditor using pip install django-ckeditor then i configured my settings.py as below # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Static files (CSS, JavaScript, Images) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor" # CKEditor settings CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' # This ensures you have all toolbar icons CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } Then i configured my urls.py (project's url) as below url(r'^ckeditor/', include('ckeditor_uploader.urls')) Then I ran command collect static ckeditor statics are collected in right location defined in settings which is /static/ckeditor/ckeditor After that I imported and used ckeditor richtextfield in my model from django.db import models from ckeditor.fields import RichTextField class Post(models.Model): post = models.RichTextField() While makemigrations i am getting the following error AttributeError: module 'django.db.models' has no attribute 'RichTextField' -
Could not connect to postgres server in a docker from a dockerized app
I would like to run a dockerized Django app with a dockerized postgres. I run the dockerized Django app by using: docker run --rm --env-file /path/to/variables -d -p 8000:8000 django_app:test I run a dockerized postgres by using: docker run --rm -d --env-file /path/to/secrets/variables -p 5432:5432 \ -v "$PWD/my-postgres.conf":/etc/postgresql/postgresql.conf \ --mount src=/path/to/db/data,dst=/var/lib/postgresql/data,type=bind \ postgres:alpine -c 'config_file=/etc/postgresql/postgresql.conf' my postgres config is the default config that is suggested in the postgres docker container documentation. It is essentially a config file that contains listen_addresses = '*' I use the same environment variables for both containers: DJANGO_SETTINGS_MODULE=settings.module PROJECT_KEY=xxyyzzabcdefg DB_ENGINE=django.db.backends.postgresql POSTGRES_DB=db_name POSTGRES_USER=db_user POSTGRES_PASSWORD=verydifficultpassword POSTGRES_HOST=localhost # I've also tried to use 0.0.0.0 POSTGRES_PORT=5432 My Django settings module for the database is: DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE'), 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('POSTGRES_HOST'), 'PORT': os.environ.get('POSTGRES_PORT') } } However, I keep on getting: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? The Dockerfiles for my django app looks like: FROM python:alpine3.7 COPY --from=installer /app /app # required for postgres COPY --from=installer /usr/lib /usr/lib COPY --from=installer /usr/local/bin /usr/local/bin COPY --from=installer /usr/local/lib /usr/local/lib ARG SETTINGS_MODULE WORKDIR /app ENTRYPOINT python manage.py migrate &&\ python … -
Example of how to Subclass Column() in Django-tables2
Can anyone point me to an example of how to subclass the base Column() in django-tables2 please. By default the django-tables2 base Column() attrs supports 'th', 'td', 'cell' and 'a' as detailed in the documentation, which also states that this can be extended by subclasses to allow arbitrary HTML attributes to be added to the output. What I want to try and do, which may be either ambitious or flat out stupid and wrong, is to add a 'ul' attribute (and subsequently 'li' attributes) so that I can render a dropdown menu in a cell. My thinking is to have an options button on each row of my table that provides the user with the various options of 'delete', 'copy', 'archive' etc via a css or js dropdown menu. -
Django max_upload_size get's ignored
i have this code but for some reasone the file size gets ignored, even if i set this directly to ('max_upload_size', 5242880) at formatChecker.py the vaule seems to get ignored after the upload has happend. formatChecker.py from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_lazy as _ class ContentTypeRestrictedFileField(FileField): def __init__(self, *args, **kwargs): self.content_types = kwargs.pop('content_types', []) self.max_upload_size = kwargs.pop('max_upload_size', []) super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs) file = data.file try: content_type = file.content_type if content_type in self.content_types: if file._size > self.max_upload_size: raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % ( filesizeformat(self.max_upload_size), filesizeformat(file._size))) else: raise forms.ValidationError(_('Filetype not supported.')) except AttributeError: pass return data models.py ... class Post(models.Model): postattachment = ContentTypeRestrictedFileField( blank=True, null=True, upload_to=get_file_path_user_uploads, max_upload_size=5242880, content_types=['application/pdf', 'application/zip', 'application/x-rar-compressed', 'application/x-tar', 'image/gif', 'image/jpeg', 'image/png', 'image/svg+xml', ] ) ... Any idea why that problem occurs? Did i forgot something here? Thanks in advance -
Why do we have to include staff and admin fields in custom user django model?
Let's say I am building a social networking website that has nothing do with admin and superuser. But I still have to include these fields while making custom user model. This is going to be a simple model that has user's profile information not that user is admin or superuser. Can anyone explain why do we always need these fields to be there. Can we get rid of them and still create a Custom user model or do we always need them. -
Don't upload and load and show Picture profile in Django
Hellow i use Django freamwork Python. in model i user AbstractBaseUser. i use python3 in my website user can choice picture for that profile. but don't load and upload picture in my model: Model: class CustomUser(AbstractBaseUser , PermissionsMixin): username = models.CharField(max_length = 200 , unique = True) email = models.EmailField() age = models.IntegerField(null=True , blank=True) number = models.IntegerField(default=1) country = models.CharField(max_length = 200) city = models.CharField(max_length = 200) image = models.ImageField(upload_to = 'ImageProfile' , default='ImageProfile/none.jpg') privilege = models.IntegerField(default= 0) is_staff = models.BooleanField(default = False) REQUIRED_FIELDS = ['email'] USERNAME_FIELD = 'username' objects = CustomUserManager() def get_short_name(self): return self.username def natural_key(self): return self.username def __str__(self): return self.username Form: from django import forms from django.contrib.auth import get_user_model class Register(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: User = get_user_model() model = User fields = ('username', 'number' , 'country' , 'city' , 'email' , 'age' , 'image') def clean_username(self): User = get_user_model() username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("username is taken") return username def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save … -
How to add link to npm package to a django template using the script tag when path is always converted to a url
I am trying to add a link to a folder in the npm_modules folder located in the root of my Django project to one of my templates. However, when attempting to do so, the path typed in is simply appended to the current url and is treated as a link. Since my folder is not there, it is not loaded and my javascript crashes. Since it is best practice to keep the npm_modules folder in root, how do I go about referencing folders within it inside my templates? <script src="\node_modules\angular-file-upload\dist\angular-file- upload.min.js" type="text/javascript"></script> -
How to save extra fields on registration using custom user model in DRF + django-rest-auth
Using Django REST Framework (DRF), with django-rest-auth, I created a custom user model with one extra field. My aim is to use the django-rest-auth registration endpoint to register a new user in one request, and thus sending all the data to create a new user, including the data for the extra field. I am using AbstractUser, since it seems recommended for beginners, where more advanced developers could use AbstractBaseUser. This is also why the following SO answers looks too complicated for what I want to achieve: link here. I know this question has been asked multiple times, but the answers are not exactly what I am looking for. For a beginner like me this is complicated stuff. So, my question is, can anyone explain how to achieve what I want? I am using: Django 2.1.4 django-allauth 0.38.0 django-rest-auth 0.9.3 djangorestframework 3.9.0 Here's the code that I have up until this point: Used this tutorial to get to this code settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!gxred^*penrx*qlb=@p)p(vb!&6t78z4n!poz=zj+a0_9#sw1' … -
Django dict key,value in for loop does not work
I'm getting a little stuck on a Django problem where I can't access the values of a dict in a for loop. It works outside the for loop, just not inside. Am I missing the obvious here? Python: err{} err['else'] = {'class': 'Low', 'txt': 'zero'} err['if'] = {'class': 'High', 'txt': 'one'} data = { 'errors': err } return render(request, 'index/error.html', data) HTML template: <p>{{ errors }}</p> <p>{{ errors.if }}</p> <p>{{ errors.if.class }}</p> {% for error in errors %} <div class="{{ error.class }}"><p>{{ error.txt }}</p></div> {% endfor %} The upper 3 lines are for code debugging and work just fine. The for loop doesn't produce any code. Best regards, LVX -
Face Recognition For Web application
I am currently working on a project- facial recognition + Web application for banks. I am done with the front-end part, but the problem is that I don't know how to implement the facial recognition part. Any help please?? -
AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user'
I can't get this to work. I've researched what this error means and have really only received a response close to "change MIDDLEWARE to MIDDLEWARE_CLASSES". This did not work. I've tried rearranging Middleware Classes, however, this too did not work. Is there anything in my code i should be concerned with that is causing this error? Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python37\lib\site-packages\django\contrib\admin\sites.py", line 241, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Python37\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Python37\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Python37\lib\site-packages\django\contrib\admin\sites.py", line 212, in inner if not self.has_permission(request): File "C:\Python37\lib\site-packages\django\contrib\admin\sites.py", line 186, in has_permission return request.user.is_active and request.user.is_staff AttributeError: 'WSGIRequest' object has no attribute 'user' settings.py """ Django settings for trydjango19 project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start … -
Multiple left join and left join against the same model raw query convert to Django ORM
Using Django 1.11 I have the following models: class Product(Model): class Pricebook(Model): class Quote(Model): class SKU(Model): product = models.ForeignKey(Product) pricebook = models.ForeignKey(Pricebook) class SKUPrice(Model): sku = models.ForeignKey(SKU, related_name="prices") class LineItem(Model): quote = models.ForeignKey(Quote, related_name="quote_line_items") sku = models.ForeignKey(SKU) This is the raw query that works for me. SELECT qli.quantity, sku_source.product_id, sku_dest.id as sku_dest_id, sku_dest_price.id as sku_dest_price_id FROM lineitem qli INNER JOIN sku sku_source ON qli.sku_id = sku_source.id LEFT JOIN sku sku_dest ON sku_dest.pricebook_id = sku_source.pricebook_id AND sku_dest.product_id = sku_source.product_id LEFT JOIN skuprice sku_dest_price ON sku_dest_price.status = 'default' AND sku_dest_price.sku_id = sku_dest.id WHERE qli.quotation_id = 40 AND qli.quantity > 0 AND sku_dest.vendor_id = 38; What I have tried is: the_quote_with_id_as_40.quotation_line_items.filter(quantity__gt=0).select_related('sku__product').values('sku__product__id', 'quantity'); This produces this query SELECT "sku"."product_id", "lineitem"."quantity" FROM "lineitem" INNER JOIN "sku" ON ("lineitem"."sku_id" = "sku"."id") WHERE ("lineitem"."quotation_id" = 40 AND "lineitem"."quantity" > 0) which is not exactly what I want. I can of course use raw query. But I would like to know if possible to use ORM. At the very least, of expanding my knowledge. Thank you. -
Reverse for 'product_list' with arguments '('cars',)' not found
I get the following error when i try http://192.168.1.107:8000/shop/. However I do not get any errors when my shop_urls.py looks like this urlpatterns = [ path('shop/', views.product_list, name='product_list'), re_path(r'shop/(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list'), ] why can't I use a different name like product_list_by_category? Also, 'cars' is a category slug name and I do not understand why it isbeing called. Error Reverse for 'product_list' with arguments '('cars',)' not found. 1 pattern(s) tried: ['shop\\/$'] Request Method: GET Request URL: http://192.168.1.107:8000/shop/ Django Version: 2.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_list' with arguments '('cars',)' not found. 1 pattern(s) tried: ['shop\\/$'] Exception Location: /home/gravityns/PycharmProjects/prodgdscorehome/venv/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 622 Python Executable: /home/gravityns/PycharmProjects/prodgdscorehome/venv/bin/python Python Version: 3.6.7 Python Path: main.urls urlpatterns = [ path('admin/', admin.site.urls), path('', include(('gdsauth.urls','gdsauth'), 'gdsauth')), path('', include(('gdsshop.urls','gdsshop'), 'gdsshop')), ] shop_urls.py path('shop/', views.product_list, name='product_list'), re_path(r'shop/(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_category'), re_path(r'shop/(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'), View in question def product_list(request, category_slug=None): context = {} category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) context['title'] = 'Shop' context['category'] = category context['categories'] = categories context['products'] = products return render(request, 'gdsshop/products/list.html',context) models class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') def get_absolute_url(self): return reverse('gdsshop:product_detail', args=[self.id, self.slug]) class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, … -
How to create the manytomany "Through" object automatically?
My django project contains three models: Article, Section and ArticleSection ArticleSection is the manytomany model of relation between Article and Section. The detail view of Article has "Add Section" and the section form works for adding a new section. And right now I have to go to another form of ArticleSection to create a new ArticleSection object to link the article and section explicitly. class Article(models.Model): owner =models.ForeignKey(User, null=False) name =models.CharField(max_length=120, null=False, blank=False) description =models.CharField(max_length=120, null=True, blank=True) class Section(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) articles = models.ManyToManyField('articles.Article', through='articlesections.ArticleSection', related_name='sections') name = models.CharField(max_length = 120) class ArticleSection(models.Model): section = models.ForeignKey("sections.Section", related_name='articlesection', on_delete=models.SET_NULL, null=True, blank=True) article = models.ForeignKey("articles.Article", related_name='articlesection', on_delete=models.SET_NULL, null=True) description= models.CharField(max_length = 120) I would expect the "Add Section" in article detail view would create the section and automatically create the ArticleSection object to link the source article and the newly created section object. Thanks BY -
Don't use `get_queryset()` while creating
Let's say you are modifying get_queryset in you manager something like this class VoteManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class Vote(models.Model): objects = VoteManager() This works as expected but the problem when you use something like get_or_create on Vote model it creates an instance even if it is present in the database because we modified the get_queryset() method. Can we not shadow the soft-deleted instance while creating?? -
FieldError: Cannot resolve keyword 'published_date' into field.
i am creating a new blog django apllication but when run it i got error here is my code #model.py class Post(models.Model): author=models.ForeignKey('auth.user',on_delete=models.CASCADE) title=models.CharField(max_length=200) text=models.TextField() create_date=models.DateTimeField(default=timezone.now()) pubished_date=models.DateTimeField(blank=True,null=True) def publish(self): self.pubished_date=timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comments=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post=models.ForeignKey('blog.Post',related_name='comments') author=models.CharField(max_length=200) test=models.TextField() create_date=models.DateTimeField(default=timezone.now()) approved_comment=models.BooleanField(default=False) def approve(self): self.approved_comment=True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text whenerver i run server i got this field error message. i m new to django -
Is there any way to get 'views.py' of pre-installed apps in django especially 'auth' app?
I got 403 Forbidden while loading my web page, and it says to ensure that 'The view function passes a request to the template's render method.' also i tried all other solutions. if there's any alternate solution please suggest. PS: IT WORKS FINE IN FIREFOX, NO FORBIDDEN ERROR. BUT NOT IN CHROME(i've ensured that it accepts cookies). -
html alert window mode
I have one django project. In the html template, I want to show one alert window after clicking the button. I use the following java function to show the window, but I don't how to adjust the position & text size of such window and also how to hide the default sentence " website says:". Can any one help? Thx! <script LANGUAGE="javascript"> function word() { alert("Start") } </script> <button type='submit' class="btn btn-primary" style="font-size:15px;" onclick="word()"> Start </button>