Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tablesorter stickyHeaders not aligning with table column
My table header is not aligning with my table column. On the left side of the table, I have a navigation sidebar that the table header somehow failed to recognize after scrolling past the original header (see pics below): I tried wrapping the table in a parent div with the position set to relative, but the table header still doesn't behave correctly (see codes below): {% load static %} <link rel="stylesheet" href="{% static 'css/theme.default.css' %}" type="text/css" /> <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.tablesorter.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.tablesorter.widgets.js' %}"></script> <div id="tableWrap" style="position:relative;"> <table id="myTable" class="tablesorter"> <caption> ... </caption> <thead> <tr> ... </tr> </thead> <tbody> <tr> ... </tr> </tbody> </table> </div> <script> $(document).ready(function(){ $('#myTable').tablesorter({ sortList: [[0,0], [1,0]], widgets: ['zebra', 'filter', 'stickyHeaders'], widgetOptions: { stickyHeaders_attachTo: '#tableWrap' }, }); }); </script> -
how to update two models with a serializer update function
I have teacher and conversation models in my project and a rate function that is a POST API with teacherId and rate as input. Teachers have phone field as an ID. When the rate function called, the teacher's rate and raters fields and the conversation's isRated field must change. how is it possible to update two models in one serializer? here is my Conversation model: class Conversation(models.Model): isRated = models.BooleanField(null=False, default=False) here is my Teacher model: class TeacherUsers(models.Model): phone = models.IntegerField(unique=True, null=False, default=0) rate = models.FloatField(null=True, default=0) raters = models.IntegerField(unique=True, null=False, default=0) and the serializer that updates teacher's rate only: class RateSerializer(serializers.Serializer): teacherId = serializers.IntegerField(required=True) rate = serializers.IntegerField(required=False) def update(self, instance, validated_data): instance.rate = validated_data['rate'] instance.raters = validated_data['raters'] instance.save() return instance -
Changing the ForeignKey based on choices
I'm trying to create a Model that has a field with choices like: MANUFACTURER_CHOICES = ( ('Commscope', 'Commscope'), ('Corning', 'Corning'), ('SOLiD', 'SOLiD'), ('Cisco', 'Cisco'), ('DIGI', 'DIGI') ) manufacturer = models.CharField( max_length=9, choices=MANUFACTURER_CHOICES ) But I want the choice to actually be a ForeignKey, impacting the data and fields that are being referenced. i.e. If Commscope is picked, it attaches the Commscope Model to the Device Model. If Cisco is picked, the Cisco Model and so on and so forth. -
Python send an email passing variable value to html
In my project i have to send an email and pass a value into html code. I try this: l_sender = [] l_sender.append('mario.rossi@test.com') emailsend(l_sender) def emailsend(l_sender): context = { 'news': 'We have good news!' } try: send_html_email(l_sender, 'Get started with Aida', 'email.html', context, sender='wepredict@cathedral.ai') print("Email send") except Exception as e: print(e) in email.html i insert {{ context.news }} but nothing appen. How can i pass my news val value in mail.html? Thanks in advance -
Using list() in my DRF view raises AttributeError
Wanted to convert my dictionary into a list inside of a django rest framework view using the list() built-in, but it raises AttributeError: 'dict_keys' object has no attribute 'META'. Same if I try .values() or .items(). The error persists whether I put the dictionary in the def list method, or overwrite the __init__ and put it there. Identical code outside of django seems to work fine, so what's going on here? Does it have something to do with the DRF method being named 'list'? Here is the simplified version that raises the error: class SomeViewSet(viewsets.ViewSet): some_dict = { 'key1': 'value1', 'key2': 'value2' } def list(self, request, format=None): print(list(self.some_dict.keys())) return Response(some_response()) And this works fine: class SomeViewSet(viewsets.ViewSet): some_dict = { 'key1': 'value1', 'key2': 'value2' } def list(self, request, format=None): print(self.some_dict.keys()) return Response(some_response()) Using [] instead of list() works, but it just puts the view object inside a list instead of converting it into one, so that's no good. Traceback: Traceback (most recent call last): File "C:\Users\FluffyAdmin\.virtualenvs\MapPoolApp-gFHC46op\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\FluffyAdmin\.virtualenvs\MapPoolApp-gFHC46op\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\FluffyAdmin\.virtualenvs\MapPoolApp-gFHC46op\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\FluffyAdmin\.virtualenvs\MapPoolApp-gFHC46op\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\FluffyAdmin\.virtualenvs\MapPoolApp-gFHC46op\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors … -
DRF return token at user registration
I've made a LoginViewSet which returns the token if authentication goes fine but I want to return the token at Registration time also: class TodoUserViewSet(ModelViewSet): http_method_names = ['POST','PUT'] serializer_class = TodoUserSerializer queryset = TodoUser.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (UpdateOwnProfile,) class LoginViewSet(ViewSet): serializer_class = AuthTokenSerializer def create(self, request): return ObtainAuthToken().post(request) -
no such table: main.auth_user__old
I ran this commnad and there was no problem python manage.py makemigrations python manage.py migrate then I ran and did as username, email and password: python manage.py createsuperuser but when I went to admin panel and try new content and I got this error: OperationalError at /admin/..../..../add/ no such table: main.auth_user__old Django version 2.1.4 Python version 3.7 -
Django doesn't find allauth
Hello Ladies and Gents I have a venv for a project called manager. I installed allauth on venv but I get this error: ImportError: No module named 'allauth' pip freeze: (manager) user@host:~/manager$ pip freeze certifi==2018.11.29 chardet==3.0.4 defusedxml==0.5.0 Django==2.1.4 django-allauth==0.38.0 django-crispy-forms==1.7.2 idna==2.8 oauthlib==2.1.0 python3-openid==3.1.0 pytz==2018.7 requests==2.21.0 requests-oauthlib==1.0.0 urllib3==1.24.1 (manager) reiser@assets:~/manager$ pip freeze certifi==2018.11.29 chardet==3.0.4 defusedxml==0.5.0 Django==2.1.4 django-allauth==0.38.0 django-crispy-forms==1.7.2 idna==2.8 oauthlib==2.1.0 python3-openid==3.1.0 pytz==2018.7 requests==2.21.0 requests-oauthlib==1.0.0 urllib3==1.24.1 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'invoices', 'feedback', 'crispy_forms', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] django runserver error: user@host:~/manager/src$ python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7ff29b7c8d08> Traceback (most recent call last): File "/home/reiser/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/reiser/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/reiser/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/reiser/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/reiser/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/reiser/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/reiser/.local/lib/python3.5/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/reiser/.local/lib/python3.5/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No … -
Error: navigator.getUserMedia error:NotReadableError: Could not start video source
I am trying to record a video in the web browser with an Android smartphone. I managed to get the code to work on the web browser in the local server but I am unsure why it isn't working when I access it from a smartphone. When accessing the page from my Android phone, I get the following error: navigator.getUserMedia error:NotReadableError: Could not start video source Following is my code: base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="{% block metadescription %}{% endblock %}"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="container-fullwidth"> <div class="select"> <label for="audioSource">Audio source: </label><select id="audioSource"></select> </div> <div class="select"> <label for="videoSource">Video source: </label><select id="videoSource"></select> </div> <video id="gum" playsinline autoplay muted></video> <video id="recorded" playsinline loop></video> <div> <button id="start">Start camera</button> <button id="record" disabled>Start Recording</button> <button id="play" disabled>Play</button> <button id="download" disabled>Download</button> </div> <div> <h4>Media Stream Constraints options</h4> <p>Echo cancellation: <input type="checkbox" id="echoCancellation"></p> </div> <div> <span id="errorMsg"></span> </div> </div> <script> 'use strict'; /* globals MediaRecorder */ var audioSelect = document.querySelector('select#audioSource'); var videoSelect = document.querySelector('select#videoSource'); audioSelect.onchange = getStream; videoSelect.onchange = getStream; function gotDevices(deviceInfos) { for (var i = 0; i !== deviceInfos.length; ++i) { var deviceInfo … -
Showing img in django admin
i was trying to show image in django admin. i try this code admin.py @admin.register(SampleImages) class CategoryAdmin(admin.ModelAdmin): readonly_fields = ['image_tag'] and for models.py class SampleImages(models.Model): image = models.ImageField(upload_to='images/tile_images') def image_tag(self): return mark_safe('<img src="{}" width="150" height="150"/>'.format(self.image)) image_tag.short_description = 'Image' but image is not showing, i inspect html and that fine. <img src="images/tile_images/150x150.gif" width="150" height="150"> in django admin when i click image url it say Sample images with ID "1/change/images/tile_images/150x150.gif" doesn't exist. Perhaps it was deleted? And image is present in my images/tile_images folder. Anyone can help please?. -
Django: Direct assignment to the reverse side of a related set is prohibited. Use username.set() instead
I have some troubles with migrating my database in django Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "E:\Env\Python\Python37-32\lib\site-packages\django\contrib\auth\checks.py", line 74, in check_user_model if isinstance(cls().is_anonymous, MethodType): File "E:\Env\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 470, in __init__ _setattr(self, field.attname, val) File "E:\Env\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 537, in __set__ % self._get_set_deprecation_msg_params(), TypeError: Direct assignment to the reverse side of a related set is prohibited. Use username.set() instead. Here is my models.py: class PostComments(models.Model): post = models.ForeignKey(InfoPost, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="username") text = models.TextField() created_date = models.DateTimeField(default=timezone.now) #approved_comment = models.BooleanField(default=False) reply_to = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, related_name='replies') #def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) I am trying to make comments system for post in my website, but there is some error occured. I don't know whats wrong with my model, but if i try to make migrations without my new PostComments model, its migrating pretty fine. -
Django Query: How to find all posts from people you follow
I'm currently building a website with the Django Framework. I want on the homepage of my website to display all posts made by people the user is following. Here are the classes for Profile, Story and Follow: class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) class Follow(models.Model): following = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name="following") follower = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name="follower") follow_time = models.DateTimeField(auto_now=True) class Story(models.Model): author = models.ForeignKey('accounts.Profile', on_delete=models.CASCADE, related_name="author") title = models.CharField(max_length=50) content = models.TextField(max_length=10000) As you can see Follow uses two Foreign Keys to represent the following and the follower. Is there a way to query all stories from people the user is following? I really don't know what to filter. Or is this maybe a job for aggregation? If someone could help me, that would be awesome! following_feed = Story.object.filter(???).order_by('-creation_date') -
Django REST shows non-allowed methods under Allow in the Browser
Goal Is to disable OPTIONS method globally. Background According to the official Django REST docs (https://www.django-rest-framework.org/api-guide/metadata/), the proper way to do it is to set DEFAULT_METADATA_CLASS to None. This resolves the problem. After trying to send the OPTIONS curl request, the server responds with the 405. Problem However the API Browser would still show methods under Allow that are actually not allowed: Question How to hide not-supported methods under Allow in Django API Browser? -
move a django model to another app which is parent model for another model
I have to django models in two diffrent apps like app1 and app2, in app1 I got Model1 and in app2 I got BaseModel and the Model1 is like this class Model1(BaseModel): ... Model1 and BaseModel where in one app but I moved Model1 to app2 and now I want to move BaseModel to app2 too. My problem is when I try to move BaseModel to app2 I get this error: Cannot resolve bases for [<ModelState: 'app1.model1'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/2.1/topics/migrations/#dependencies for more What I do is simple: I write migration for renaming table of BaseModel to app2_basemodel then I write migration for creating model in app2 I create migration for altering field basemodel_ptr which is used for inheritance i move the BaseModel code to app2 and delete BaseModel with a migration from app1 This method worked for moving Model1 but when I try to move this base Model I get this error. I appreciate any helps including any other way to reach this refactor idea of moving BaseModel to app1 -
django-mysql connection error inside docker
errors: govtcareer | govtcareer | Traceback (most recent call last): govtcareer | File "manage.py", line 15, in <module> govtcareer | execute_from_command_line(sys.argv) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line govtcareer | utility.execute() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute govtcareer | self.fetch_command(subcommand).run_from_argv(self.argv) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv govtcareer | self.execute(*args, **cmd_options) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute govtcareer | self.check() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check govtcareer | include_deployment_checks=include_deployment_checks, govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks govtcareer | issues = run_checks(tags=[Tags.database]) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks govtcareer | new_errors = check(app_configs=app_configs) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends govtcareer | issues.extend(conn.validation.check(**kwargs)) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check govtcareer | issues.extend(self._check_sql_mode(**kwargs)) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode govtcareer | with self.connection.cursor() as cursor: govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor govtcareer | return self._cursor() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor govtcareer | self.ensure_connection() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection govtcareer | self.connect() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ govtcareer | raise dj_exc_value.with_traceback(traceback) from exc_value govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection govtcareer | self.connect() govtcareer | … -
How Parent object will create in Django Restframework nested serializers
How Parent object will create in Django Restframework nested serializers? I want to show all children associated to the parent but the problem is that when I try to create Parent it asks children list and as per the rule first parent will born models class Parent(models.Model) name = models.CharField(max_length=30) class Child(models.Model) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=30) Serializers class ChildSerializer(ModelSerializer): class Meta: model = Child fields = ('name') class ParentSerializer(ModelSerializer): children = ChildSerializer(many=True) class Meta: model = Parent fields = ('name','children') -
Date display in template for Google structured data
I'm working on SEO for my blog and I'm building structured data for Google. I think I have to get this date format : 2018-12-13T10:50:00+00:00 Currently, my date is like this because I don't know how to do better : <script type="application/ld+json">{ "@context":"http:\/\/schema.org", "@type":"NewsArticle", "dateCreated":"{{post.date|date:"Y-m-d H:i:s"}}", Anyone knows how to transform post.date to return something like 2018-12-13T10:50:00+00:00 ? -
Simulating a HTTP request from a standalone Python script and from command line
I've been tasked to develop a script which can be run from command line, and uses a url as an argument (so simulating a browser request). In the app the corresponding cache mechanism has been successfully built. In order to get this up and running, I'm using RequestFactory to mimic the requests. My script is: class FetchCacheTest(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='thatsme', email='thatsme@hotmail.com', password='secret') def cache_details(self, url): request = self.factory.get(url) print("get_request: {0}".format(request)) request.user = self.user print("request.user: {0}".format(request.user)) request.user = AnonymousUser() response = MyView.as_view()(request) response.render() self.assertEqual(response.status_code, 200) if __name__ == '__main__': ####### #import django #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') #django.setup() ########################## script = sys.argv[0] url = sys.argv[1] print ("Script: {0}\nURL: {1}".format(script, url)) fct = FetchCacheTest t = fct.cache_details(url) In one tab in Terminal I do python manage.py runserver In another tab python fetch_myapp.py https://report/failed The traceback I receive: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've tried out the commented out code just under the if __name__ == '__main__' but to no avail. Any ideas how to circumvent this message? Any further tips on collecting cache stas in general is much appreciated. -
Show specific user details in Django application instead of all details
I am creating my first Django project . I have taken 30,000 values as input and want to show particular values according to primary key . Code: class employeesList(APIView): def get(self,request): employees1 = employees.objects.all() with open('C:\\Users\\Dimple\\Desktop\\Python\\ClickPost\\tracking_ids.csv') as f: reader = csv.reader(f) for row in reader: _, created = employees.objects.get_or_create( AWB=row[0], Pickup_Pincode=row[1], Drop_Pincode=row[2], ) serializer = employeesSerializer(employees1 , many=True) return Response(serializer.data) def post(self,request): # employees1 = employees.objects.get(id=request.employees.AWB) employees1 = employees.objects.all() serializer = employeesSerializer(employees1 , many=True) return Response(serializer.data) If I enter http://127.0.0.1:8000/employees/ in URL , I get all the values . I want the URL to be like http://127.0.0.1:8000/employees/P01001168074 and show values of P01001168074 where P01001168074 is primary ID . Can it be done and if it can , then how ? -
updating field in user model whenever it used
I have extended user model in my project and need to update its field (last online) whenever user has authenticated. I use DRF and IsAuthenticated in permission classes, what is the best way to trigger update event? -
django wrong in the migration
wath is the Wrong!?? C:\holamundo>python manage.py makemigrations App Migrations for 'App': App\migrations\0002_auto_20181216_0745.py - Alter field nombre on tabla resultado: C:\holamundo>python manage.py migrate Operations to perform: Apply all migrations: App, admin, auth, contenttypes, sessions Running migrations: Applying App.0001_initial...Traceback (most recent call last): File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\backends\sqlite3\base.py", line 294, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: duplicate column name: ID The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\migrations\operations\models.py", line 91, in database_forwards schema_editor.create_model(model) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\backends\base\schema.py", line 312, in create_model self.execute(sql, params or None) File "C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\django-2.1.3-py3.7.egg\django\db\backends\base\schema.py", line 133, … -
Django Query: How to order posts by amount of upvotes?
I'm currently working on a website (with Django), where people can write a story, which can be upvoted by themselves or by other people. Here are the classes for Profile, Story and Upvote: class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) birth_date = models.DateField(null=True) gender = models.CharField(max_length=30, null=True) country = models.ForeignKey('home.Country', on_delete=models.PROTECT, related_name="country_of_profile", null=True) biography = models.TextField(max_length=300, blank=True) visited_countries = models.IntegerField(default=1) class Story(models.Model): author = models.ForeignKey('accounts.Profile', on_delete=models.CASCADE, related_name="author") country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="country_of_story") title = models.CharField(max_length=50) content = models.TextField(max_length=10000) longitude = models.DecimalField(max_digits=25, decimal_places=20) latitude = models.DecimalField(max_digits=25, decimal_places=20) creation_date = models.DateTimeField(auto_now=True) class Upvote(models.Model): profile = models.ForeignKey('accounts.Profile', on_delete=models.CASCADE, related_name="upvoter") story = models.ForeignKey('Story', on_delete=models.CASCADE, related_name="upvoted_story") upvote_time = models.DateTimeField(auto_now=True) As you can see, Upvote uses two foreign keys to store the upvoter and the related story. Now I want to make a query which gives me all the stories, sorted by the amount of upvotes they have. I've tried my best to come up with some queries myself, but it's not exactly what I'm searching for. This one doesn't work at all, since it just gives me all the stories in the order they were created, for some reason. Also it contains duplicates, although I want them to … -
Cannot serialize list of objects as JSON in Django
I'm trying to pass some data about a user as JSON, and because the User object has many-to-many relationships, serializing a user as JSON seems to only include the primary key of the m-n object. (e.g. each user has hobbies, but in the JSON it will only have the PK of the hobbies) Anyway, I tried constructing a schema to solve this as such: [[{user}, [hobbies]], [{user}, [hobbies]],...] But whenever I try to serialize this (in Python it's basically an array with an object and another array in it), I get the error: 'list' object has no attribute '_meta' Why is this happening and how can I fix it? -
Django: When delete db.sql3 file / new database, cannot create user : save() got an unexpected keyword argument 'force_insert'
My aim: I want to re-create the django development database from scratch / starting over. I am using Django 2.1.4 My method: I delete the development database file ( db.sql3 ) after this, I attempt to re-build the database, by running python manage.py migrate python manage.py makemigrations python manage.py migrate python manage.py createsuperuser (I have tried several permutations on above, including: the order of commands, makemigrations on a specific app, create a normal user, deleted all migrations files). The result: The last step (create user) produces an error which means I cannot create a user for the database, or else work with the database file: File "/..../venv/lib/python3.6/site-packages/django/db/models/query.py", line 413, in create obj.save(force_insert=True, using=self.db) TypeError: save() got an unexpected keyword argument 'force_insert' My attempts: most posts online related to this is outdated, referencing functionality not current any longer in Django version (2.1.4), such as syncdb. I have spent long time trying find "best practice" around resetting your database / drop tables / start over your database, but those posts useful mostly are 5 years old and reference again functionality not present in Django 2 or referencing production database. I have re-built my project from scratch 3 times to overcome the problem … -
Django form not submitting or providing error messages
When I submit my form, it doesn't post the form data and just reloads the form. It was working beforehand but I'm not sure what I've changed that doesn't make it work anymore. Posting the data through the admin still works fine. The only 'error' message I can see is in the terminal: which can be seen here My code is below: Here is my views.py def create(request): if request.method == 'POST': form = EventCreateForm(request.POST, request.FILES) if form.is_valid():. instance = form.save(commit=False) instance.author = request.user instance.save() instance.save_m2m() return redirect('event:home') else: form = EventCreateForm() return render(request, 'event/create.html', {'form': form}) create.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} {{ form.media }} <div class="container-fluid"> <div class="col-md-4"> <div class="page-header"> <p> Create an event!</p> </div> <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy}} <button type="submit">Submit</button> <br> <br> </form> </div> </div> {% endblock %} Base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'event/css/custom.css' %}"> <title>Django Project</title> </br> <div class="container-fluid" style='font-family:arial'> <center> <h2> Welcome to the django website!</h2> </center> </div> …