Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using django respassword_reset_confirm error ,
I am using Django 2.1 and getting an error during password reset authentication right at the end my urls from django.conf.urls import url from django.contrib import admin from . import views from django.contrib.auth import views as auth_views from django.urls import reverse, reverse_lazy, resolve app_name = 'partners' urlpatterns = [ url(r'^$', views.home, name='partner_home'), url(r'^(?P<partner_id>[0-9]+)/$', views.detail, name='detail'), url(r'^login/$',auth_views.LoginView.as_view(template_name="partners/registration/login.html"), name="login"), url(r'^logout/$',auth_views.LogoutView.as_view(template_name="partners/registration/logout.html"), name="logout"), url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.view_profile, name='view_profile'), url(r'^profile/edit/$', views.edit_profile, name='edit_profile'), # Password URL's ################################################################################################### url(r'^change-password/$', views.change_password, name='change_password'), url( r'^password_reset/$', auth_views.PasswordResetView.as_view( template_name="partners/registration/password_reset.html", email_template_name="partners/registration/password_reset_email.html", success_url=reverse_lazy("partners:password_reset_done"), # might be required ), name='password_reset' ), url(r'^password_reset_done/', auth_views.PasswordResetDoneView.as_view( template_name="registration/password_reset_done.html", ), name='password_reset_done' ), url(r'^password_reset_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', # r'(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view( template_name="registration/password_reset_confirm.html", ), name='password_reset_confirm', ), url(r'^password_reset_complete/$', auth_views.PasswordResetCompleteView.as_view( template_name="partners/registration/password_reset_complete.html", ), name="password_reset_complete" ), ] I am able to login, then go to the password reset view. An email is sent using the development server and I am able to use the link to create a new password. Once I enter the new password I get an error (but the password in the background is changed). I am not sure why this is the case at the moment . I am not using my custom password_reset_xxx html file instead I am using the builtin views My URLS and structure The Error Message PLEASE HELP it should … -
Celery django : launch worker - ImportError: No module named XXX
I have difficulties to laucnh celery worker. The exemple here works fine and is closed to documentation. My problem is that my real configuration folder construction is like this : djangosite/ |-- package/ | |-- __init__.py | |-- myapp/ | | |-- __init__.py | | |-- migrations/ | | |-- templates/ | | |-- apps.py | | |-- models.py | | +-- views.py |-- mysite/ | |-- __init__.py | |-- settings.py | |-- urls.py | |-- celery.py | +-- wsgi.py |-- manage.py My app is a subfolder of package when the exemple show an app in folder. __init__ of mysite folder: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py contains: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('celery_app') # This reads, e.g., CELERY_ACCEPT_CONTENT = ['json'] from settings.py: app.config_from_object('django.conf:settings') # For autodiscover_tasks to work, you must define your tasks in a file called 'tasks.py'. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) I launch: celery worker -l info -A mysite and celery cannot find laboratory module. How to solve this ? Do I need to put my application the django root folder ? -
django.db.utils.IntegrityError: 1062, Duplicate entry for key
I have a problem with my django migrations. Before making the changes my table contained the following columns: STATUS = ( ('Active', 'Active'), ('Pending', 'Pending'), ('Incomplete', 'Incomplete') ) id = models.CharField(primary_key=True, max_length=50, unique=True, editable=False, default=uuid.uuid4) name = models.CharField(max_length=100, null=False, default='') country = models.CharField(max_length=100, choices=COUNTRY, null=True, blank=True) postcode = models.CharField(max_length=20, null=False, blank=True) address = models.TextField(max_length=200, null=False, blank=True) status = models.CharField(max_length=20, choices=STATUS, default='Pending') created_on = models.DateTimeField(default=timezone.now, editable=False) balance = models.DecimalField(default='0.00', max_digits=16, decimal_places=2, null=True, editable=True) but when I added the new fields: api_key = models.CharField(max_length=50, unique=True, editable=False, default=uuid.uuid4) key_exp = models.DateTimeField(default=one_day_hence, editable=False) I keep getting django.db.utils.IntegrityError: (1062, "Duplicate entry 'fc1d481d-add2-4d9c-92d9-a1b05018730a' for key 'api_key'") when running migrations. First of all, I find it suspicious since django will provide a different value for any default=uuid.uuid4. I tried migrating several times but I get the same error but with a different key. Secondly, I tried to remove unique=True but this didn't change anything, the error is the same. Any idea why and how I can solve this? -
Special symbol with context variable
In my django template I have: <strong>Copyright &copy; </strong> {{ copyright }} Where: copyright = "Company &copy; 2014-2018" Which shows: Copyright © Company &copy; 2014-2018 Why is the first symbol ok, and the second not? -
Django View Return Queryset with extra information
I have a normal Django view that returns the API for a query set. It takes query params from the URL and filters the database based on the parameters. It also outputs a maximum length of 3 "Part" objects. I would like to add something so that it returns information on whether the queryset is clipped by the maximum length of 3. The idea is that since the inputs the query parameters, if the parameters are too vague, then there will be too much data being queried from the database. So it is clipped but then the user needs to know that it was clipped. The current code looks like this class PartList(generics.ListAPIView): serializer_class = PartSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = Part.objects.all() querydict = self.request.query_params for (k, value) in querydict.items(): search_type = 'contains' filter = k + '__' + search_type queryset = queryset.filter(**{filter: value}) query_max_limit = 3 return queryset[:min(len(queryset), query_max_limit)] -
Django: any way to execute consecutive model.save() operations as 1 single DB request?
I have a function that does operations on a Django model instance, and I'm trying to break it up into sub operations that can be used independently. However, this means that I end up calling .save on each change and trigger a DB request. def subop1(instance): instance.a1 = 1 instance.save() def subop1(instance): instance.a2 = 2 instance.save() def subop1(instance): instance.a3 = 3 instance.save() def main_op(instance): subop1(instance) # triggers 1 DB request subop2(instance) # triggers 1 DB request subop3(instance) # triggers 1 DB request Is there any way to avoid having .save triggering a DB request every time while still keeping each function independently functional? Maybe some way of deferring the .save operations until some context manager exits and then saving all at once with 1 DB request. Tried to read through transaction documentation but I didn't find anything that fit. -
How can I get an info about a traffic from many sites if I include my script inside them? (Analog: Google Analitycs, Yandex Metric)
I use django and python. I actually want to know how different services with their metrics listen the traffic from many sites? In django we have the request object which include all information but what if I want to get info from many sources outside my django? -
does django send_mail() support custom 'from'?
my django app is sending emails (via SendGrid API) using django.core.mail's send_mail send_mail( subject='foo', message=message, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[user.email], fail_silently=False, html_message=rendered) the emails send fine but since it's sending from hi@myapp.com the email "From" alias in inboxes just shows up as "hi", and I'd like to make it more verbose so my recipients know who sent them the email ("Hi from AppName"). I don't see any field in send_mail docs (https://docs.djangoproject.com/en/2.1/topics/email/) for customizing how the "From" sender alias string appears (beyond the email itself) other than 'The “From:” header of the email will be the value of the SERVER_EMAIL setting'. does django's send_mail not support this (i.e., I need to rewrite this to using a sendgrid lib? https://github.com/sendgrid/sendgrid-python?) or is there a config setting in SendGrid where I can automatically set 'fromname'? thanks Is that -
How to print data in Django views
In PHP I'm used to being able to do print_r($data) or var_dump($data) in controller for printing any kind of variable or array but in Django how can I print a data (object, list, dictionary) in views.py for knowing which value is inside that. -
How to create form instance using subclass Django Python
class MyModelFormSet(BaseRegistrationEmailMessageForm): def clean(self): super().clean() for form in self.forms: subject = form.cleaned_data['subject'] form.cleaned_data['subject'] = subject form.instance.subject = subject start = form.cleaned_data['subject'].find( '{{ ' ) raise forms.ValidationError({'subject':subject}) return form.cleaned_data -
Error H10 App Crash on Heroku with Django
I'm deploying an app with Django==1.11.15 and Python==2.7.15 on Heroku and the push worked fine and return this comment: remote: -----> Launching... remote: Released v6 remote: https://healthylifeweb.herokuapp.com/ deployed to Heroku But the aplication link show an error and suggest and command to see the log, i wrote the command but i don't know how to solve the error. The log file: $ heroku logs --tail 2018-10-10T10:15:54.204608+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in <module> 2018-10-10T10:15:54.204615+00:00 app[web.1]: sys.exit(run()) 2018-10-10T10:15:54.204639+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 61, in run 2018-10-10T10:15:54.204712+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2018-10-10T10:15:54.204715+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 223, in run 2018-10-10T10:15:54.204769+00:00 app[web.1]: super(Application, self).run() 2018-10-10T10:15:54.204771+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run 2018-10-10T10:15:54.204870+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2018-10-10T10:15:54.204825+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 232, in run 2018-10-10T10:15:54.204823+00:00 app[web.1]: Arbiter(self).run() 2018-10-10T10:15:54.204937+00:00 app[web.1]: self.stop() 2018-10-10T10:15:54.204872+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 345, in halt 2018-10-10T10:15:54.204939+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 393, in stop 2018-10-10T10:15:54.205007+00:00 app[web.1]: time.sleep(0.1) 2018-10-10T10:15:54.205064+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2018-10-10T10:15:54.205009+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 245, in handle_chld 2018-10-10T10:15:54.205062+00:00 app[web.1]: self.reap_workers() 2018-10-10T10:15:54.205146+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2018-10-10T10:15:54.205207+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2018-10-10T10:15:54.287683+00:00 heroku[web.1]: Process exited with status 1 2018-10-10T10:15:54.307196+00:00 heroku[web.1]: State changed from starting to crashed 2018-10-10T10:16:12.438188+00:00 heroku[router]: at=error code=H10 desc="App crashed" … -
How to round up in html.erb file
In a ruby html template file, I need to round a number (i.e. 5.12 to 6). <td>{{offer.amount | currency:$:0}}</td> I tried doing: offer.amount.ceil but it won't work (the entire td column would be blank with no numbers). -
Django REST Swagger hiding ModelViewSet with permission_classes=[IsAuthenticated]
I used Django REST Swagger in my Django project. It is able to show all the URL with views which does not have permission_classes = [IsAuthenticated]. While the view with permission_classes = [IsAuthenticated] is not shown in the list-api. Here is an example: class EquipmentCategoryViewSet(ResponseMixin, viewsets.ModelViewSet): queryset = EquipmentCategory.objects.all() serializer_class = EquipmentCategorySerializer permission_classes = [IsAuthenticated] if i remove permission_classes = [IsAuthenticated], it is shown in the swagger list-api. Please suggest what should be done to show views with isAuthenticated added. -
DJANGO: ValidationError ["'journals__Start_Date' value has an invalid date format. It must be in YYYY-MM-DD format."]
I dont know what I am doing wrong in my code I want to perform this: journal.objects.filter(Q(User=request.user) | Q(Date__range=[('journals__Start_Date'),('journals__End_Date')]) My models.py look like this: class journal(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname') Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) class selectdatefield(models.Model): Journal = models.ForeignKey(journal,on_delete=models.CASCADE,null=True,blank=True,related_name='journals') Start_Date = models.DateField(blank=True, null=True) End_Date = models.DateField(blank=True, null=True) Do anyone have any idea what is wrong in my code? I have used F expressions but it doesnt filter the date range... -
Django Problem with FilesystemStorage.save()
Context : Implement prod Django web project in Centos env. I am trying to solve a function on file storage action that didn't work but i cant see why?... maybe a permission problem... I have a pretty same function that work... The function import os def manager_file_tasks(file, archive_path): print(file, archive_path) # i got this : file.csv /MYHOME/Site_Django/media/archive_file/uploadedFiles tmp_archive_path = os.path.join(BASE_DIR, 'visualisation', 'UploadFiles', 'file') # Test if the folder archive exist if not os.path.exists(tmp_archive_path): os.makedirs(tmp_archive_path) print(tmp_archive_path) # i got this : /MYHOME/Site_Django/visualisation/UploadFiles/file fs = FileSystemStorage(location=tmp_archive_path) print(fs) # i got this : <django.core.files.storage.FileSystemStorage object at 0x7f57f622bda0> print(armdb_file.name, armdb_file) # i got this : file.csv file.csv print(fs.save(armdb_file.name, armdb_file)) # NO RESULT .... :( filename = fs.save(armdb_file.name, armdb_file) print(filename) armdb_file = fs.path(filename) print(armdb_file) # some other stuffs are made after.... Here the rights of the folder: [me@web01]$ ll /MYHOME/Site_Django/visualisation/UploadFiles/ total 0 drw-r--r--. 2 apache apache 6 10 oct. 11:22 file Thanks in advance for the help. -
Django tests: self.client.post is not being executed for the second time
I am trying to create an object using POST request, and then simply edit it using PUT request. The code itself works whenever I am doing all of necessary steps on my own, by hand. Unfortunately, whenever I am trying to test it using TestCase, it goes completely wrong. The POST request is being executed in a proper way, but whenever I am trying to send second request with PUT operation (within the same block of code), it is not being created def test_fully_working_editing_items(self): self.test_operation_type = "POST" self.chosen_date_from = str(datetime.now().month) + "/" + str(datetime.now().day) + "/" + str(datetime.now().year) self.chosen_date_to = str((datetime.now() + timedelta(days=1)).month) + "/" + str((datetime.now() + timedelta(days=1)).day) + "/" + str((datetime.now() + timedelta(days=1)).year) self.placement = self.test_placement_offer.id # THIS ONE WORKS response = self.client.post(reverse('advertisement_user_basket:user_basket_controller'), data={ 'operation': self.test_operation_type, 'chosen_date_to': self.chosen_date_to, 'chosen_date_from': self.chosen_date_from, 'placement': self.placement, 'chosen_impression_number': self.test_impression_number.number } ) self.assertEqual(response.status_code, 200) self.assertEqual( json.loads(response.content.decode('utf-8'))["is_valid"], True ) self.test_obtained_advertisement_item_id = json.loads(response.content.decode('utf-8'))["items"][0]["id"] ''' ============================================================ EDITING ITEMS ============================================================ ''' self.test_operation_type = "PUT" self.chosen_date_from = str(datetime.now().month) + "/" + str(datetime.now().day) + "/" + str(datetime.now().year) self.chosen_date_to_new = str((datetime.now() + timedelta(days=3)).day) + "/" + str((datetime.now() + timedelta(days=3)).month) + "/" + str((datetime.now() + timedelta(days=3)).year) self.placement = self.test_placement_offer.id logger.error('111111111111111111111111') # THIS ONE DOES NOT WORK second_response = self.client.post(reverse('advertisement_user_basket:user_basket_controller'), data = { … -
Django: 403 Missing or insufficient permissions
I am running datastore emulator. When I run "dev_appserver.py app.yaml" command, I get this error 403 Missing or insufficient permissions. This is the warning I get. I know there is a problem with authentication. I have gone through this. But couldn't end up finding a solution. Some details: 1) I am using MySQL databases for some apps. 2) For others, I am want to use datastore. 3) I am running datastore emulator on one tab, google cloud proxy on another, dev_appserver on the third one. 4) I have set the environment variables using the command gcloud beta emulators datastore env-init. My settings.py if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/connectionname', 'NAME': 'db_name', 'USER': 'username', 'PASSWORD': 'password', } } else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: # # $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306 # # See https://cloud.google.com/sql/docs/mysql-connect-proxy DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3307', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'password', } } # [END … -
view function not found in django
When trying to click on a button to redirect to getonboard.html I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'getonboard' not found. 'getonboard' is not a valid view function or pattern name. artdb/urls.py: path('getonboard/',views.getonboard,name='getonboard'), templates/artdb/base.html: <p><a class="btn btn-primary btn-lg" href="{% url 'getonboard' %}" role="button">Get onboard &raquo;</a></p> artdb/views.py: def getonboard(request): return render(request,'artdb/getonboard.html') templates/artdb/getonboard.html: {% extends "artdb/base.html" %} {% block content %} <h2>getonboard template</h2> <p>this is the getonboard text</p> {% endblock content %} any thoughts? -
post_save cause IntegrityError while having onetoone relation in User and Profile model
i am extending django User model by onetoone relation wit Profile model.and i want to create a profile of a user when User instance is created so i use post_save signal.when i create a user(using register view) a profile is also created with blank and null values which is what i want . but when i try to login with that user IntegrityError appears. views.py def register(request): if request.method == 'POST': user_form = CreatUserForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request,'accounts/registration_done.html',{'new_user':new_user}) else: return render(request,'accounts/registration.html', {'user_form':user_form}) else: user_form = CreatUserForm() return render(request,'accounts/registration.html',{'user_form':user_form}) @login_required def edit_profile(request): if request.method == 'POST': user_edit_form = UserEditForm(instance=request.user,data=request.POST) profile_edit_form = ProfileEditForm(instance=request.user.profile,data=request.POST) if user_edit_form.is_valid() and profile_edit_form.is_valid(): user_edit_form.save() profile_edit_form.save() messages.add_message(request,messages.SUCCESS,'profile updated') return redirect('dashboard') else: return render(request,'accounts/edit_profile.html',{'user_edit_form':user_edit_form, 'profile_edit_form':profile_edit_form}) else: user_edit_form = UserEditForm(instance=request.user) profile_edit_form = ProfileEditForm(instance=request.user.profile) return render(request,'accounts/edit_profile.html',{'user_edit_form':user_edit_form, 'profile_edit_form':profile_edit_form}) models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=30,blank=True) last_name = models.CharField(max_length=30,blank=True) DOB = models.DateField(null=True,blank=True) mobile_no = models.IntegerField(null=True,blank=True) address = models.TextField(max_length=250,blank=True) signals.py from accounts.models import Profile def create_user_profile(sender, instance, created, **kwargs): Profile.objects.create(user=instance) apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' def ready(self): from django.db.models.signals import post_save from accounts.signals import create_user_profile from django.contrib.auth.models import User post_save.connect(create_user_profile, sender=User, dispatch_uid='create_user_profile') Error: Environment: Request Method: POST Request URL: http://example:8000/accounts/login/ Django Version: … -
Nested Views in Django - Python
I am new to python, and making a transition from AngularJs. I am struggling to implement login to render specific template without refreshing the whole page. Base.html have two templates and in turn, those two have another two. Now all of them have different URLs, so when I hot one URL, that particular HTML is rendered, killing all the others. My base HTML has all the elements which will always be there (like index.html) <div class="container"> <div class="row"> <div class="col s3 offset-s3"> <div class="card blue-grey darken-1"> <div class="card-content white-text"> <span class="card-title">Dice</span> <p>Throw dice</p> </div> <div class="card-action"> <a href="#dice">Let's Play</a> {% comment %} <a href="#">This is a link</a> {% endcomment %} </div> </div> </div> <div class="col s3"> <div class="card blue-grey darken-1"> <div class="card-content white-text"> <span class="card-title">Hangman</span> <p>You know it</p> </div> <div class="card-action"> <a href="#hangman">Let's Play</a> {% comment %} <a href="#">This is a link</a> {% endcomment %} </div> </div> </div> </div> </div> Thanks :) -
Django: Add variable to template tag
I use {{ order.total_gross|currencynofmt:order.event.currency }} to display 200.00 and {{ order.total_gross|currencyfmt:order.event.currency }} to display $200.00 What's changing is format=True or format=False. I wonder if there is a way to bring that into one template tag as they are very similar. register = template.Library() @register.filter def currencyfmt(amount, currency_iso_code): return smallest_currency_unit_converter( amount, currency_iso_code, reverse=True, format=True ) @register.filter def currencynofmt(amount, currency_iso_code): return smallest_currency_unit_converter( amount, currency_iso_code, reverse=True, format=False ) -
Using _set.filter(id = 4) django field fetch
can I ask a question in django i'm a beginner in django, but I'm very much interested in developing a website on django. Here is my problem I'm trying to fetch the data from from page model which is connected to Subject model with a foreignkey. Is there any way on how to fetch the data quickly? Here is my views.py urls.py I'm trying to fetch the field title form page_set.filter object. Thanks for the help in advance -
Django (TypeError): __init__() got an unexpected keyword argument 'widget'
I have the problem that, when i run my website it comes with two Type Errors. I do not know what it is i need to edit, but i know it is in the models.py file. Error 1: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001D025692400> Traceback (most recent call last): File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\bruger\Dropbox\min-login-web\web_login\users\models.py", line 25, in <module> class Desc(models.Model): File "C:\Users\bruger\Dropbox\min-login-web\web_login\users\models.py", line 26, in Desc description = models.CharField(widget = forms.Textarea, max_length = 250, required=False) File "C:\Users\bruger\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py", line 1037, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got … -
Django admin order field doesn't look right
My django admin panel doesn't seem to be sorting correctly, I have a custom method which will count the comments of each post. class PostAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'comments', 'created') def get_queryset(self, request): qs = super(PostAdmin, self).get_queryset(request) qs = qs.annotate(com=models.Count('comment')) return qs def comments(self, obj): return obj.comment_set.count() comments.admin_order_field = 'com' But sadly, whenever I click the header of the table to sort by comments, I get something like this: 85 100 132 128 36 Yes, I've made sure to sort the column by descending order. What am I doing wrong? -
Django - How to add data from ajax button into html, so it updates everytime button is clicked?
currently I've got an ajax like button set up. The console shows that the like count is toggling when I press the button, but how do I actually retrieve the 'like_count' variable to put into my html. My button code is: <script type="text/javascript"> function toggleLike(){ $.ajax({ url: "{% url 'photo_blog-post_like_api' post.id %}", data: {like_count: 'like_count', 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(data) { console.log(data); } }); }; </script> and the html for the button is: <input type="button" onclick="toggleLike()" value="Like"/> and the code for my view is: class LikePostAPI(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, slug=None, format=None, pk=None): obj = get_object_or_404(Post, id=pk) user = self.request.user updated = False liked = False if user.is_authenticated: if user in obj.likes.all(): liked = False obj.likes.remove(user) like_count = obj.likes.count() else: liked = True obj.likes.add(user) like_count = obj.likes.count() updated = True data = { "updated": updated, "liked": liked, "like_count": like_count } return Response(data) Thanks for the help!