Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static precompiler doesn't work in production mode
I installed django-static-precompiler completely according to the documentation to compile my scss-files and it works brilliantly... until I set DEBUG from True to False. From that moment on, the staticfiles cannot be found anymore: File "/usr/local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 422, in stored_name raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'COMPILED/css/porcupine.css' In my html file, I compile and load the .scss as follows: <link rel="stylesheet" href="{% static "css/porcupine.scss"|compile %}"/> This file is indeed being created, but only when Debug=False is not picked up by the file system, or so it seems. Surprisingly, the file is exactly where it is supposed to be and the compiled file can be inspected in the browser at: http://localhost:8000/static/COMPILED/css/porcupine.css So the question is: what's going on? How to make Django find the compiled files in production mode (DEBUG=False)? I happily include more settings upon request, but Django is a bit convoluted in its many settings in different files, and I would like to keep this post simple. -
Can't start worker, No module named 'celery
I try to include tasks in my webapplication but i can't start the celery work. My project structure is the following: website/website --> init.py, settings.py, urls.py, wsgi.py website/index --> init.py, celery_app.py, tasks.py Index is my startpage where i want to run the tasks. index/celery_app.py has the following code: from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('index', broker='amqp://localhost//', backend='amqp://', include=['index.tasks']) # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) if __name__ == '__main__': app.start() index/tasks.py: from __future__ import absolute_import from .celery_app import app @app.task def test_func(): print("Test Background Task") When i want to start the worker with celery -A index worker --loglevel=info I get the following error: ModuleNotFoundError: No module named 'celery'. I run the commandprompt in the index folder. The other solutions in similar questions didn't help me. -
Django How to check if entry exists in database?
I have the following model in my application: class Device(models.Model): class Meta: verbose_name_plural = "devices" imei = models.CharField(max_length=15, unique=True) last_update = models.DateTimeField() rule = models.CharField(max_length=20) @classmethod def create(cls, imei, last_update, rule): device = cls(imei = imei, last_update = last_update, rule = rule) return device def __str__(self): return self.imei Now, after I do an update I want to check if the device is already stored in my database. So I used this code: if Device.objects.filter(imei="123456789").exists(): return True else: return False But for some reason when I run it, it doesn't work and I keep getting 500 error. What am I doing wrong here? -
Migration of Django field with default value 0 to PostgreSQL database
I want to update default column value but it seems like default value on columns is is only on the ORM layer, and is not actually setting a default value in the DB and returns error django.db.utils.OperationalError: cannot ALTER TABLE "bps_registration_application" because it has pending trigger events. Is it possible to update default columnn value to 0 in postgress migrations by updating in django model? This is models.py. class Application(models.Model): registration_date = models.CharField(max_length=15) building_use = models.ForeignKey(to=system_settings.models.BuildingUse) building_category = models.CharField(max_length=30) building_structure_category = models.ForeignKey(to=system_settings.models.BuildingStructureCategory) building_length_ft = models.IntegerField(blank=True, default=0) building_breadth_ft = models.IntegerField(blank=True, default=0) building_height_ft = models.IntegerField(blank=True, default=0) building_length_in = models.IntegerField(blank=True, default=0) building_breadth_in = models.IntegerField(blank=True, default=0) building_height_in = models.IntegerField(blank=True, default=0) building_storey = models.IntegerField(blank=True, default=0) building_area = models.DecimalField(max_digits=6, decimal_places=2) reg = models.ForeignKey(NewRegistration) -
Pytest PropertyMock as return_value for MagicMock does not get invoked
I am trying to mock the return_value for a MagicMock instance as a PropertyMock but it appears to be returning the PropertyMock object without invoking it i.e. does not return the actual value. class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel # ... fields = ( "my_field" ) my_field = serializers.SerializerMethodField() def get_my_field(self, instance): other_models = instance.group.filter() if other_models: # returns <class 'unittest.mock.PropertyMock'> instead of an actual value print(type(other_models.get().my_property)) # throws error since it isn't receiving a string return ujson.loads(other_models.get().my_property) return {} # test case def test_hello(mocker): expected_value = ujson.dumps({'hello': 2}) instance_mock = mocker.MagicMock() other_model_mock = mocker.MagicMock() other_model_mock.get().my_property = mocker.PropertyMock(return_value=expected_value) instance_mock.group.filter.return_value = other_model_mock serializer = MySerializer() observed_value = serializer.get_my_field(instance_mock) assert expected_value == observed_value -
Django only allowing users into their own profile for multiple pages
I have this URL "private/profile/" and I wrote something like this to keep any user except the profile owner out of that page if int(pk) != profile: return HttpResponse("ERROR:...") else: return render(...) The problem is that I have multiple urls like "private/profile//editProfile", and I need to write the code above for every single URL. Is there a better practice for this? -
Using PostgreSQL aggregate expressions in Django
As of PostgreSQL 9.0+, using aggregate expressions is supported. For example, you are able to use ORDER BY to sort rows before calling on to the PostGIS function ST_MakeLine as below: SELECT ST_MakeLine(position ORDER BY timestamp)::bytea AS line FROM recorded_positions WHERE dataset_id = 98 ORDER BY timestamp ASC What I have in my application is the following in an attempt to do this but clearly this is not the use case for order_by(): queryset = queryset.order_by('timestamp') \ .annotate(line=Func('position', function='ST_MakeLine')) \ .values('line') Of course this produces the following wrong SQL for what I want (and invalid due to use of order_by on a non aggregate column): SELECT ST_MakeLine(position)::bytea AS line FROM recorded_positions WHERE dataset_id = 98 ORDER BY timestamp ASC Is this possible at all with Django or will I have to do something else (raw query, subquery, etc) to accomplish the same result? -
Some issues with UUID while migrating from SQLite to Postgresql in Django 2.0
I am trying to migrate my Django 2.0.4 project from SQLite to PostgreSQL 10 following the steps described here, but I am having differents problems. During the project I changed some Integer fields to UUID4 fields. I managed to run python manage.py migrate --run-syncdb manually editing auto_increment migration file making changes of this type (see id field): From class Migration(migrations.Migration): dependencies = [ ('dumps', '0011_auto_20180608_1714'), ] operations = [ migrations.CreateModel( name='Report', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('data', models.DateTimeField(auto_now_add=True, verbose_name='Date')), ], ), ... ... ... To class Migration(migrations.Migration): dependencies = [ ('dumps', '0011_auto_20180608_1714'), ] operations = [ migrations.CreateModel( name='Report', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')), ('data', models.DateTimeField(auto_now_add=True, verbose_name='Date')), ], ), ... ... ... Next, I commented all auto_increment files in which there was an AlterTable on uuid fields, but when I run python manage.py loaddata datadump.json I obtain the following error: django.db.utils.ProgrammingError: Problem installing fixture 'C:\Users\djangoproject\datadump.json': Could not load myApp.Reservation(pk=10d00b08-bf35-469f-b53f-ec28f8b6ecb3): ERROR: column "reservation_id" is integer type but the expression is uuid type LINE 1: UPDATE "myApp_reservation" SET "reservation_id" = '066cff3c-4b... -
How to implement pagination in django?
I found a resource where it has code like this: from django.contrib.auth.models import User from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def index(request): user_list = User.objects.all() page = request.GET.get('page', 1) paginator = Paginator(user_list, 10) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'core/user_list.html', { 'users': users }) I have a code like this: def product_list(request, category_slug=None): category = None categories = Category.objects.all().order_by("-rating") #paginator = Paginator(categories, 10) products = Product.objects.all().order_by("-number") users = User.objects.exclude(id=request.user.id) query = request.GET.get('q') if query=='': return HttpResponseRedirect('/') if query: categories = Category.objects.filter(Q(slug__icontains=query)| Q(url__icontains=query)).order_by("-rating") products = Product.objects.filter(Q(slug__icontains=query) | Q(name__icontains=query) | Q(description__icontains=query)).order_by("number") if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) categories_counter = products.annotate(Count('id')) categories_count = len(categories_counter) #contacts = paginator.get_page(query) context = { 'category': category, 'categories': categories, 'products': products, 'categories_count':categories_count, 'query':query, 'users':users, #'contacts':contacts, } return render(request, 'shop/product/list.html', context) I have retrieved objects from two models, Category, and Product. How do I implement the pagination code in this view? I also don't get the idea of the page= request.GET.get('page',1) because i have query = request.GET.get('q') in my code. Is page built-in function? -
Heroku Django webapp getting error logs say gunicorn command not found but it is there
I am trying to run a django app on heroku with postgresql but i'm getting when i go to my app url i check the heroku logs --tail and see 2018-08-27T10:37:19.086599+00:00 heroku[web.1]: State changed from starting to crashed 2018-08-27T10:37:19.070449+00:00 heroku[web.1]: Process exited with status 127 2018-08-27T10:37:18.986150+00:00 app[web.1]: bash: gunicorn: command not found i have a requirements.txt with gunicorn, the heroku python buildpack installed i try maybe installing gunicorn remotely with heroku run pip install -r requirements.txt but i get › Error: remote requirements.txt not found in git remotes -
Django Rest Framework Custom Authentication + return custom json
I am using django 2.1 and python 3.6....I want to authenticate users using custom authentication and return token along with email and id after validating user. In settinge.py AUTHENTICATION_BACKENDS = ( "users.views.authentication_backend.UserAuthenticationBackend", ) In views.py class UserAuthenticationBackend(object): def authenticate(self, request, email=None, password=None): validate_email(email) valid_email = True kwargs = {'email': email} try: user = get_user_model().objects.get(**kwargs) except get_user_model().DoesNotExist: raise exceptions.AuthenticationFailed('User does not exist.') if valid_email and user.check_password(password) and user.is_valid is True: return user elif valid_email and user.check_password(password) and user.is_valid is False: raise exceptions.AuthenticationFailed('Sorry your account is suspended temporarily,' ) else: raise exceptions.AuthenticationFailed('Sorry, your email and password does not match.') I want to return response as follows: {'token':"", 'user': {'id': 1, 'email': 'admin@abc.com', 'is_active': True}} Thanks in advance... -
u"'' value has an invalid date format. It must be in YYYY-MM-DD format i need it to be MM-DD-YYYY
ValidationError at /uimsapp/employee/19543/ [u"'' value has an invalid date format. It must be in YYYY-MM-DD format."] Request Method: POST Request URL: http://127.0.0.1:8000/uimsapp/employee/19543/ Django Version: 1.8 Exception Type: ValidationError Exception Value: [u"'' value has an invalid date format. It must be in YYYY-MM-DD format."] Exception Location: /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/fields/init.py in to_python, line 1287 Python Executable: /home/fella/djangoApps/pmo/venv/bin/python Python Version: 2.7.15 Python Path: ['/home/fella/djangoApps/pmo/venv/src', '/home/fella/djangoApps/pmo/venv/lib/python2.7', '/home/fella/djangoApps/pmo/venv/lib/python2.7/plat-x86_64-linux-gnu', '/home/fella/djangoApps/pmo/venv/lib/python2.7/lib-tk', '/home/fella/djangoApps/pmo/venv/lib/python2.7/lib-old', '/home/fella/djangoApps/pmo/venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages', '/home/fella/djangoApps/pmo/venv/lib/python2.7/site-packages', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/odf', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/odf', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/odf', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/odf', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/odf', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/odf', '/home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/odf'] Server time: Mon, 27 Aug 2018 13:35:37 +0000 Traceback Switch to copy-and-paste view /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /home/fella/djangoApps/pmo/venv/src/uimsapp/views.py in employee_edit instance.save() ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/base.py in save force_update=force_update, update_fields=update_fields) ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/base.py in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/base.py in _save_table forced_update) ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/base.py in _do_update return filtered._update(values) > 0 ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/query.py in _update return query.get_compiler(self.db).execute_sql(CURSOR) ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py in execute_sql sql, params = self.as_sql() ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py in as_sql val = field.get_db_prep_save(val, connection=self.connection) ... ▶ Local vars /home/fella/djangoApps/pmo/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_db_prep_save prepared=False) ... ▶ … -
django-allauth settings for slack
How can I get avatar_url of slack user? I use django-allauth==0.36.0 I wrote custom provider because in version 0.30.0 I can get the avatar by using method get_avatar_url(), but in version 0.30.0 it doesn't work. Maybe I write wrong fields in settings of something else? SOCIALACCOUNT_PROVIDERS = { 'Custom': { 'SCOPE': ['identity.basic', 'identity.email','identity.avatar'], 'FIELDS': ['user.image_192',], } } This code of my customized slack provider. provider.py from allauth.socialaccount.providers.slack.provider import SlackProvider, SlackAccount class CustomSlackProvider(SlackProvider): id = 'custom' name = 'Custom' account_class = SlackAccount def get_default_scope(self): return ['identity.basic', 'identity.email', 'identity.avatar', 'identity.team'] provider_classes = [CustomSlackProvider] urls.py from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns from .provider import CustomSlackProvider urlpatterns = default_urlpatterns(CustomSlackProvider) views.py from allauth.socialaccount.providers.oauth2.views import ( OAuth2CallbackView, OAuth2LoginView, ) from allauth.socialaccount.providers.slack.views import SlackOAuth2Adapter from .provider import CustomSlackProvider class CustomSlackOAuth2Adapter(SlackOAuth2Adapter): provider_id = CustomSlackProvider.id oauth2_login = OAuth2LoginView.adapter_view(CustomSlackOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(CustomSlackOAuth2Adapter) apps.py from django.apps import AppConfig class CustomSlackProviderConfig(AppConfig): name = 'aht_slack_provider' def ready(self): import aht_slack_provider -
How do I manage a rapidly growing postgres table in Django?
I have a website that is used to show live data from different machines in a crushing facility. Right now the "Sensor Data" obtained from all the machines in one facility is stored in a "sensordata" table and this data is used by the user to make reports for a time period(upto last three months). The site has been running for 3 months now and the sensor data table is already at 113 million rows. My company is planning to add even more facilities( this will multiply then number of machines). What's a good solution to store this large an amount of data?(That's also future safe for say 100's of facilities) -
How can I add a small snippet of code that uses request and runs when someone accesses the django admin page?
How can I add a small snippet of code that runs when someone accesses the admin page. I am trying to get the IP address of users that use the admin and make changes to the database. I can use django signals to see when changes are made, but I need to access django request in order to gain access to a user's IP address. I thought a simple way would be to just add a snippet of code in the the admin views where I would request the IP address and save it in a variable. I looked into overriding the django admin views, but everything I found seemed to be correlated with creating querysets and returning http request in some way, which is not what I want (I don't believe.) -
Django url parameter appended with "/None"
So I've dozens of urls set up like this, but only this one fails: url(r'^artist_page/(?P<am_id>.*)/$', views.artist_profile, name='artist_page'), And the view is defined like this: def artist_profile(request, am_id=None): but for some reason the view is receiving am_id as am_id/None. I've tried removing the None as the initial value from the view, different regex patterns, nothing works. What am I doing wrong? -
Process Data of the database
I have a model with 49 different numbers, I upload these numers on the admin page. My final goal is to give answers based on these numbers. My question is how can I process these numbers from the database and then upload the answer to the database? Thanks for your answers! -
Why does Ajax refresh page on mobile devices after submitting form via POST method?
I am trying form submission on my Django website. Ajax works fine for form submissions on Desktop and doesn't refresh page on submission, whereas when using on mobile devices the POST data is submitted successfully but the page refreshes after the request. How can I prevent refresh after submission? <script> $(document).ready(function(){ $('#email_button_secondary_submit').on('click', function(e){ $('#email_button_secondary_submit > span').removeClass('glyphicon glyphicon-chevron-right'); $('#email_button_secondary_submit > span').addClass('fa fa-spinner fa-spin'); $emailaddress = $('#email').val(); $.ajax({ type: "POST", url : '', cached: false, data: { email: $emailaddress, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function () { $('.Subscribe').hide(); $('.Thanks').show(); }, complete: function () { $('#email_button_secondary_submit > span').removeClass('fa fa-spinner fa-spin'); $('#email_button_secondary_submit > span').addClass('glyphicon glyphicon-ok'); }, error: function () { $('.Subscribe').hide(); $('.Error').show(); $('#email_button_secondary_submit > span').removeClass('glyphicon glyphicon-ok'); $('#email_button_secondary_submit > span').addClass('glyphicon glyphicon-remove'); }, }); e.preventDefault(); }); }); </script> -
Value error shown in Internet Explorer or web view in android but not in chrome
As the question says, in my Django app, the browser or the web app has to send an id of the object to the server. It works perfectly well on chrome 100 % times, but in other browsers or web view in Android, it sometimes throws a value error. What can be the reason? -
Django Display a selection list
I am trying to implement a form where candidates can be selected for approval processing. I want to display a list of candidates, so their data can be viewed during selection. models.py class SubmissionApproval(models.Model): candidate=models.ForeignKey(Candidate,on_delete=models.CASCADE) clientProcess=models.ForeignKey(ClientProcessDetails,verbose_name="Client Process",help_text="Process",on_delete=models.PROTECT) dateSubmitted=models.DateTimeField(auto_now_add=True) comments=models.CharField("Comments",max_length=200,blank=True,null=True) class Meta: verbose_name="First Stage Approval" unique_together=(('candidate','clientProcess'),) def __str__(self): return self.candidate.name views.py def submissionApprovalList(request): object_list=Candidate.objects.all() if request.method=="POST": fm=SubmissionApprovalFormList(request.POST) print("Reached Post") if fm.is_valid(): print("Printing Candidates Start") for item in fm.cleaned_data['candidates']: print(item) print("Printing candidates End") else: fm=SubmissionApprovalFormList() return render(request,'itrecruitment/firstStageSubmissionList.html',{'form':fm,'object_list':object_list }) forms.py class SubmissionApprovalFormList(forms.Form): candidates=forms.ModelMultipleChoiceField(queryset=Candidate.objects.all(),\ widget=forms.CheckboxSelectMultiple) template {% extends "seekgeek/base.html" %} {% block content %} <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Select Candidates for First Stage Submission</h3> <a href="{% url 'candidate:add' %}"><button type="button" class="btn btn-primary pull-right">Add Candidate </button></a> </div> <!-- /. box-header --> <div class="box-body table-responsive"> <!-- form details --> {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} {% bootstrap_messages %} <form method="post" enctype="multipart/form-data" > {% csrf_token %} <table class="table table-bordered table-hover datatable2"> <thead> <tr> <td><b>Select</b></td> <td><b>Candidate No</b></td> <td><b>Candidate Name</b></td> <td><b>Current CTC (LPA)</b></td> <td><b>Expected CTC (LPA)</b></td> <td><b>Experience in Yrs</b></td> <td><b>Recruiter</b></td> <td><b>Latest Status</b></td> <td><b>Languages</b></td> <td><b>Updated</b></td> </tr> </thead> <!-- ./ table head --> <tbody> {% for obj in object_list %} <tr> <!--Select field for Form --> <td> {{ form.candidates.0 }} </td> <!--Select … -
Django form validation - assertFalse()
I am quite new to the Django testing software. Right at the moment I am trying to create a test class for validators connected with given form ( process of cleaning the input data): forms.py: class SignupForm(forms.Form): email = forms.EmailField(max_length=200) first_name = forms.CharField(max_length=200) last_name = forms.CharField(max_length=200) company_name = forms.CharField(max_length=200) password1 = forms.CharField(max_length=200) password2 = forms.CharField(max_length=200) def clean(self): cleaned_data = self.cleaned_data cleaned_username_obtained = cleaned_data.get('username') if(cleaned_username_obtained != None): username_obtained = cleaned_username_obtained.lower() else: raise ValidationError('Username is empty!') cleaned_email_address = cleaned_data.get('email') cleaned_password1 = cleaned_data.get('password1') cleaned_password2 = cleaned_data.get('password2') cleaned_first_name = cleaned_data.get('first_name') cleaned_last_name = cleaned_data.get('last_name') cleaned_company_name = cleaned_data.get('company_name') if username_obtained != None: if((User.objects.filter(username=username_obtained)).count() > 0): self._errors['username'] = [u'Username is already in use'] elif((ModelOfAdvertisementClient.objects.filter(email_address=cleaned_email_address)).count() > 0): self._errors['email'] = [u'Email is already in use'] elif(len(cleaned_password1) == 0): self._errors['password1'] = [u'Password input box is empty'] elif(cleaned_password2 != cleaned_password1): self._errors['password2'] = [u'Inserted passwords are different!'] return cleaned_data test_forms.py: class SignupFormTest(TestCase): @classmethod def test_correct_values(self): form = SignupForm({ 'username': 'testUsername', 'email': 'mark12@gmail.com', 'first_name': 'Karl', 'last_name': 'Smith', 'company_name': 'HiTech Inc.', 'password1': 'test123', 'password2': 'test123' } ) print(str(form.is_valid())) self.assertFalse(form.is_valid()) Unfortunately, each time I am launching written above code, it ends up with following error message: self.assertFalse(form.is_valid()) TypeError: assertFalse() missing 1 required positional argument: 'expr' and due to the fact, that form.is_valid() returns "False", I … -
Django TypeError: render() got an unexpected keyword argument 'renderer'
I've upgraded to Django 2.1, and I'm seeing this error when I load the admin interface: TypeError at /admin/foo/bar/1/change/ render() got an unexpected keyword argument 'renderer' -
i have "Requested setting INSTALLED_APPS" warnings. i dont know how to solve this
my settings view INSTALLED_APPS = [ 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "aksalist", ] when i run this (test_et.py ), this error occurs. (test_py) from django.core.management.base import BaseCommand from aksalist.models import * class Command(BaseCommand): help = 'Get single products from cs-cart' def handle(self, *args, **options): pass bolge = Bolgeler.objects.all() personel = Aksalist.objects.all()[0] gunler = ("2018-08-28", "2018-08-29", "2018-08-30") vardiyalar = ("07:30 - 15:30", "15:30 - 23:30","23:30 - 07:30") for i in gunler: for y in vardiyalar: for z in bolge: obj = VardiyalarRMS.objects.create(gun=i, bolge=z, vardiya_donemi=y ) print(obj) exit() my manage.py !/usr/bin/env python import os import sys if name == 'main': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aksamer.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) -
Like Dislike Toggle using custom template tags
I want the text inside button to toggle between like and dislike .Im trying to accomplish this using custom template tags . The like and dislike is working and model is getting updated. Just want the button to toggle between like and dislike! I have created the template tags folder .Just want help in creating the template tag function inside post_extras.py and how to call the function inside the template post_extras.py from django import template register = template.Library() @register.simple_tag(takes_context=True) def isliked(context,entry): if entry.filter(id=context['request'].post.id).exists(): return "Unlike" else: return "Like" like_section.html {% load post_extras %} {{ entry.total_likes }} Like{{ entry.total_likes | pluralize }} <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} <input type="submit" name="{{ entry.id }}" value="like" class="btn btn-primary like"/> </form> models.py class Post(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) heading = models.CharField(max_length=200, null=False) text = models.TextField(null=False) created_date=models.DateTimeField(default=timezone.now) pic = models.ImageField(upload_to='image', blank='True') def __str__(self): return self.heading def getuser(self): return self.user.username def total_likes(self): return Like.objects.filter(post=self).count() class Like(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) def __str__(self): return self.post.heading ajax code: $(document).on('click','.like',function(e) { e.preventDefault(); var pks=$(this).attr('name'); console.log('primarys : '+ pks); $.ajax({ type:'POST', url:'like/', data:{ 'ids': pks, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success:function (response) { $(e.target).parents('.like-section').html(response); console.log(response) console.log("liked"); }, error: function(rs,e){ console.log(rs, e.responseText); console.log('ERROR'); }, }); }); views.py def like_post(request): … -
Django - 1051 Unknown table error
I accidentally manually dropped a data table. Now when I try to run my project I get an error that says: 1051 Unknown table error. Is there any way I can fix it it or am I screwed?