Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Latest Chrome caching ajax response despite no cache headers
I have a simple form in a modal that gets populated by a ajax request (to a server running Django) If I add choices to a choice field, those choices are not displaying for a few minutes on the modal. This issues only appeared after updating to the latest version of chrome (80.3987.149). I am including no-cache headers in the ajax response like this: response['Cache-Control'] = 'no-cache, no-store, must-revalidate' response['Pragma'] = 'no-cache' response['Expires'] = '0' But it doesn't seem to matter. My ajax call method looks like this: openAlertModalOnclick(e) { e.preventDefault(); let self = this; $.get($(e.target).attr("href"), resp => { $("#alertModal").html(resp.html).foundation("open").foundation(); }) }).fail(() => { this.showErrorToast("Error occurred while loading alerts.") }) } I am 90% sure this is an issue with just the latest version of chrome, as I could not reproduce it until I updated chrome. Is there anything else I can do to get chrome to stop caching the form? -
Why I have this import error: cannot import name 'View' from 'homepage.views'
Why I have this import error: cannot import name 'View' from 'homepage.views' URLS: from homepage.views import View urlpatterns = [ path('admin/', admin.site.urls), path('homepage/', View), ] VIEWS: from django.http import HttpResponse def View(request): return HttpResponse('hello world') I have added 'homepage' into settings under apps. Thank you! -
passing html tags arguments in django template to javascript function
I want to pass HTML string as argument in javascript, in django template. Here it is: I have bunch of links, which they are in my database. I can access these links via {% for link in links %} {{ link }} {% endfor %} in my django template. for example, I can access a certain link name with using {{ link.name }}, but I also have content specified to every links; like {{ link.content }}. the problem is; in my template I have a sidebar nav which contains several link's urls, and I want to display the content of clicked link in that page. for that, I wrote a javascript function named display: <script> function display(str){ document.getElementById('cont').innerHTML = str: } </script> which will access: <div id="cont"> </div> here it is: <a class="nav-link active" href="{{ link.link }}" onclick="display('{{ link.content }}')">{{ link.name }}</a> in the code above, the display function doesn't work. I mean, when I click the link in sidebar, it doesn't show any content, literally nothing. but for test, when I changed the display argument {{ link.content }} to something else like '<h1>hello<h1>', it worked. p.s: my link's content is an inline html tags like: '<h1><strong>&nbsp; &nbsp; &nbsp; &nbsp; … -
multiple query model in same view django
I've been doing some django these past weeks and I'm having a problem. I have a page where Articles are shown. No problem while reovering all articles from db. But now I'd like to get all categories (an Article has a category) that I have in my database. So I can display like this in my page: List of categories -cat1 -cat2 -cat3 List of articles -art1 -art2 -art3 But I don't know how to do with both queries. Here's what I've tried. class IndexView(generic.ListView): template_name = 'eduardoApp/index.html' context_object_name = 'article_list' def get_queryset(self): return Article.objects.order_by('article_name') def get_categories(request): category_list=Category.objects.all() context = {'category_list':category_list} return render(request,'eduardoApp/index.html',context) And in my view: <h2>List of categories</h2> {% if category_list %} {% for category in category_list %} <p>{{ category.name }}</p> {% endfor %} {% else %} <p>no categorys</p> {% endif %} <h2>List of articles</h2> {% if article_list %} <div class="flex-container"> {% for article in article_list %} <div><a href="{% url 'eduardoApp:detail' article.id %}">{{ article.article_name }}</a></div> {% endfor %} </div> {% else %} <p>No articles...</p> {% endif %} {% endblock %} In my view I keep seeing no categorys displayed (since category_list does not exist but don't know why and how to fix) -
Django: display choice value instead of key
Model: class Model1(models.Model): STATUS_CHOICES = [ ('A', 'active'), ('D', 'deactivated') ] status = models.CharField(max_length=1, choices=STATUS_CHOICES,default='D') Serializers: class Model1Serializers(serializers.ModelSerializer): class Meta: model = Model1 fields = '__all__' View: class View(viewsets.ModelViewSet): queryset = Model1.objects.all() serializer_class = Model1Serializers I came across get_<field_name>_display(). But I am not using any template of mine. I am using Django-REST Framework UI. -
How to fix IntegrityError during the process of saving cropped photo records
Having the model : class Photo(models.Model): file = models.ImageField(upload_to='cropped_photos/',null=True,blank=True) description = models.CharField(max_length=255, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) customer = models.ForeignKey(Woo_Customer,verbose_name="Customer",on_delete = models.CASCADE) I find difficulty in the process of saving a photo record for specific customer after the procedure of uploading and cropping an image with cropper plugin. I do not know how to pass the id of my FK(customer) to the Photo record at the phase of creating the Photo record. Here is my form: class PhotoForm(ModelForm): x = FloatField(widget=HiddenInput()) y = FloatField(widget=HiddenInput()) width = FloatField(widget=HiddenInput()) height = FloatField(widget=HiddenInput()) class Meta: model = Photo fields = ('file', 'x', 'y', 'width', 'height') def save(self): photo = super(PhotoForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.file) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(photo.file.path) return photo Here is my view: def customer_photo_gallery(request,pk): photos = Photo.objects.filter(customer_id = pk) customer = Woo_Customer.objects.get(id = pk) if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('photo_list') else: form = PhotoForm() return render(request, 'woo_customer/woo_customer_photo_gallery.html', {'form': form, 'photos': photos , 'customer': customer}) Here is the template using the cropper plugin (https://fengyuanchen.github.io/cropper/) {% block content %} <script> $(function () { /* SCRIPT TO OPEN … -
django.db.utils.InterfaceError: (0, '') when using django model
I have django.db.utils.InterfaceError: (0, '') error on django. I googled around and found this error is related with mysql connection. I added the CONN_MAX_AGE None in db settings but in vain. I don't even open connection by myself only just using django models. Does anyone knows this error? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', .... 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT'), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'CONN_MAX_AGE' : None ## add here } } These are the stacktrace Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 412, in _query rowcount = self._do_query(q) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 375, in _do_query db.query(q) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) _mysql_exceptions.InterfaceError: (0, '') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
OneToOneField no 'username' member in django python3 or fstring or self attribute problems
Here is my code below. why am I getting an error from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Why is my f-string messing up? It says instance on OneToOneField has no 'username' member? Could this just be pylint and not a real error? how do i tell? -
In Django, how do I render JSON given an OrderedDict?
I'm using Django and Python 3.7. I'm having trouble returning JSON from one of my views. I have this view code ... def get_hints(request): article_id = request.GET.get('article_id', None) article = Article.objects.get(pk=article_id) s = ArticlesService() objects = s.get_hints(article) data = ArticleSerializer(objects, many=True).data print("data: ", data) return HttpResponse(data, content_type="application/json") The service method referenced returns the following data ... def get_hints(self, article): ... sorted_articles_map = OrderedDict(sorted(rank_map.items(), key=operator.itemgetter(1), reverse=True)) return list(sorted_articles_map.keys()) The data returned from the serializer looks like this, definitely not json ... [OrderedDict([('id', 10777935), ('created_on_ms', 1577985486000.0), ('label', 'World'), ('title', "Outrage and Disgust After 'Serial Killer' ..., How do I render proper JSON? -
Django Model Filter: need to return the name not the id of a foreign key
I am trying to filter some data in a Model called WorkPacket work_packets_01012017_25032020 = WorkPacket.objects.all() work_packets_01012017_25032020 = work_packets_01012017_25032020.filter(start_date__gte=datetime.date(2017, 1, 1), start_date__lte=datetime.date(2020, 03, 25)).values('id', 'number', 'name', 'description', 'value', 'type', 'status', 'daily_rate', 'creator', 'creation_date', 'closer', 'closure_date', 'start_date', 'estimated_closure_date', 'estimated_days_overrun', 'invoice_coding', 'issued_pos', 'purchase_order', 'number_of_days', 'number_of_billed_days','number_of_remaining_days', 'number_of_over_run_days', 'effective_daily_rate', 'ahead_behind', 'earnings', 'remaining_earnings', 'reported', 'projects', 'purchase_order__customer', 'purchase_order__owner') This table has a foreign key "purchase_order" related to another model. At the end of the values returned I am trying to attach the 'purchase_order__customer', 'purchase_order__owner'. This works but is returning the ids of the customer and the owner, not the name. How can I return the names, instead? Thank you -
Django: Booleanfield with default value triggers NotNullViolation on 'get_or_create'
I'm working on a Django web application (with a Postgres database) that contains a model with the following field: Loan(models.Model): (...) active = models.BooleanField(default=True) print_code = models.CharField( max_length=100, blank=True, null=True, unique=True, ) (...) However, our application is currently triggering Sentry errors on the following piece of code: loan, created = Loan.objects.get_or_create( print_code=data['print_code'] ) Its raising the following error: null value in column "active" violates not-null constraint DETAIL: Failing row contains (null, null, null, null, print1722, f, null) The traceback also contains the Loan.DoesNotExist error, so I know Django is trying to create a new Loan instance - without providing a value for the active field, but as can be seen in the code above it has a default value. The problem is that so far I've been unable to replicate the problem locally and we don't have shell access to the code that is running live. All unittests also pass without problems, even when I explicitly created some tests to create Loan objects without the active field being set. In all my attempts the code behaved as expected and filled the field with the default True value. Yet the error keeps occurring, so I must be missing something. Does anyone … -
Why django inspectdb skips some ids?
I was running inspectdb on my schema. At first, the defitions are very correct like these: class Diagnosis(models.Model): id = models.BigIntegerField(primary_key=True) code = models.CharField(max_length=255) starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis' class DiagnosisTranslation(models.Model): id = models.IntegerField(primary_key=True) language = models.CharField(max_length=10) title = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis_translation' Then, I added sequences and default values (postgresql) for Ids: CREATE SEQUENCE diagnosis_id_seq START WITH 100000 INCREMENT BY 1; ALTER TABLE diagnosis ALTER COLUMN id SET default nextval('diagnosis_id_seq'); CREATE SEQUENCE diagnosis_translation_id_seq START WITH 100000 INCREMENT BY 1; ALTER TABLE diagnosis_translation ALTER COLUMN id SET default nextval('diagnosis_translation_id_seq'); I reran again python manage.py inspect, and the outcome changes correctly for diagnosis, but not for the other table, it lacks the id attribute now: class Diagnosis(models.Model): id = models.BigAutoField(primary_key=True) code = models.CharField(max_length=255) starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis' class DiagnosisTranslation(models.Model): # Where's the ID ?? language = models.CharField(max_length=10) title = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis_translation' Why does Django omits the … -
Is there a method to populate a Django form field based on another field without using JavaScript?
I am trying to implement a booking system that simply consists of three drop menus. The first one is to choose the location, and the second one is to choose the date. The previous two fields are independent. However, the third one is the time, which is basically the time slots with fixed hours. I mean by fixed hours: 7:00 - 8:00, 8:00 - 9:00, ...etc. The problem is I want to populate the third one based on the first two fields. So for each location I want to check all of the slots for the given date. If it is empty, I will show the time slot. I read a lot of Stack Overflow questions and a lot of tutorials. However, all of them are based on JavaScript which I am trying to avoid. Is it impossible to do it without JavaScript? I am sorry for not providing a code sample because I have no idea about how to do it without JavaScript. -
HTTPS certificates, named servers, CORS
I am not a web dev by profession or education, so I apologize in advance if I am asking this question in a naive / ill-posed way. I have a Django server hosted on "Mom and Pop's Hosting Service TM". This server hosts a web API. It has some random IP address and it's not attached to a domain name. I also have a Vue.js frontend that talks to this API and sends data back and forth to/from it including user auth. (I am using the native Django auth). This Vue.js frontend is hosted in an S3 static hosting bucket and is bound to some domain name: http://www.mystaticfrontend.com (this is just an example, not my actual site). I realize that I need to setup HTTPS certificates in order to encrypt the user authentication that is embedded in all the API requests sent to the Django server as well as all the JSON responses that get sent back and forth. What is the path of least resistance to get this setup? I have been considering migrating my Django server to AWS EC2 because I have read that AWS will generate and manage HTTPS certificates for you. (Maybe there's a simpler way … -
How can I implement a verified field in django?
In Django I'd like to add a field "verified" of type BooleanField to my models which shall indicate if the current model instance has been reviewed by a staff user member or not. Whenever a model instance field other than the "verified" field changed the verified field value shall be reset to False. Whenever only the "verified" field has been changed it's value shall be taken as is (most of the time True but potentially False as well). Using signals to implement something like that seems to be considered an anti-pattern. Instead one should override the save() method. How can I implement something like this most easily. I'd prefer a solution using a third-party package w.o. custom hacks or a solution without any dependencies to other packages. However using django-model-utils monitorfield for a custom implementation or something equivalent would be ok as well. -
Why Django tries to use MySQL instead of sqlite3
My problem is this: When I try to do the migrations, it gives me the following error: python3 manage.py makemigrations Traceback (most recent call last): File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/jenifer/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/jenifer/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/jenifer/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jenifer/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/jenifer/.local/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/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 "/home/jenifer/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/jenifer/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/models/base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/models/options.py", line 208, in … -
DRF import serializer during AppConfig gives incorrect result
i'm not sure how to start this but i try it like this.. Given the following situation: We have an Env-variable PROFILES_SERIALIZER in the form of myapp.serializers.SomeModelSerializer. This serializer should be, due to Env-variable, dynamically changable. (This is relevant for some reason unimportant to the problem). Now I want to have this serializer "imported/available" after the initialization of a certain app called "content" which is done via: class ContentConfig(AppConfig): name = "content" profiles_serializer = None def ready(self): module_ser_class = settings.PROFILES_SERIALIZER.rsplit(".", 1) if any(module_ser_class): self.profiles_serializer = getattr( import_module(module_ser_class[0]), module_ser_class[1] )(many=True) With that i can include this serializer dynamically in a different one for the purpose of nested serialization as follows class TreeNodeSerializer(serializers.ModelSerializer): profiles = django_apps.get_app_config("content").profiles_serializer ... # so one an so forth The resulting views are fine upon the point where we might have nested-serilization within SomeSerializer, for instance class SomeModelSerializer(serializers.ModelSerializer): model1 = ModelOneSerializer() model2 = ModelTwoSerializer() class Meta: model = SomeModel fields = "__all__" If this is the case, any View with serializerclass=TreeNodeSerializer will not show the entries for model1or model2. However if we assume that PROFILES_SERIALIZER = environ.Env("PROFILES_SERIALIZER").rsplit(".",1) This results in the expected behavior: class TreeNodeSerializer(serializers.ModelSerializer): profiles = getattr(import_module(settings.PROFILES_SERIALIZER[0]),settings.PROFILES_SERIALIZER[1])(many=True) ... # so one an so forth My Question is … -
Django-models aren't loaded yet after adding foreignkey
I have looked similar questions in stackoverflow everywhere but nothing helped. My code worked great until I added a foreignkey to one of my models. This is the newly added line: page = models.ForeignKey(Page, on_delete=models.CASCADE, default=Page.objects.get(pk=7).pk) My full models.py looks like this: class Page(Group): pagenumber = models.IntegerField() pagename = models.CharField() class Photo(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE, default=Page.objects.get(pk=7)) file = models.FileField(upload_to='photos') After that, when I hit python manage.py makemigrations, The error comes up. Here is a full traceback(note, my code in this question is simplified version of the original one) : Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site- packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site- packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site- packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in … -
OperationalError could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Trying to deploy my Django app to Heroku and keep getting the following error. I'm not really sure where to start here... I tried killing all processes on port 5432 and restarting Postgres but I'm not too familiar with how to configure the database on Heroku. Thanks for any help. I'm not quite sure where to start. I've been using the Heroku dev guide and googling the error. Most solutions seem to say to restart Postgres but not working for me. 2020-03-25T05:12:41.000000+00:00 app[api]: Build started by user leary.keegan@gmail.com 2020-03-25T05:13:20.394227+00:00 heroku[web.1]: Restarting 2020-03-25T05:13:20.397813+00:00 heroku[web.1]: State changed from up to starting 2020-03-25T05:13:20.175463+00:00 app[api]: Deploy a13facac by user leary.keegan@gmail.com 2020-03-25T05:13:20.175463+00:00 app[api]: Release v18 created by user leary.keegan@gmail.com 2020-03-25T05:13:21.365822+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2020-03-25T05:13:21.584742+00:00 heroku[web.1]: Process exited with status 0 2020-03-25T05:13:21.376200+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [9] [INFO] Worker exiting (pid: 9) 2020-03-25T05:13:21.377965+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [4] [INFO] Handling signal: term 2020-03-25T05:13:21.377967+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-03-25T05:13:21.477875+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [4] [INFO] Shutting down: Master 2020-03-25T05:13:24.895930+00:00 heroku[web.1]: Starting process with command `gunicorn life_cal.wsgi --log-file -` 2020-03-25T05:13:28.209650+00:00 app[web.1]: [2020-03-25 05:13:28 +0000] … -
How to keep tweepy stream running from Django even after apache server restart?
I'm building a django-based twitter app that uses Tweepy streaming and I'm curious how to keep the stream running even after the server reboot? The server is Apache. Thank you. -
Creating a web server that uses postresql and python for securing some information
I am working on a project but at some point I had to make a webserver-ish thing. I use that -ish because I am not sure that's the correct way to describe it. Let me explain what I am trying to do: I want to create a library program that normal user installs, register to the system from it and adds a books which he/she owns. The program will do these with getting required information with variables and sending them to the server. Only sending to the server and no more. When server got this data; registers the user and adds the books to the user's inventory with postgresql. After that the user can display the books which she/he owns but user can not display the registered user list. And while user displaying the inventory he/she will be doing it via read-only psycopg2 commands those use same postgreqsl database. The method I thought to do this: Create postgresql database and tables in it. Write a program which can reach these tables with psycopg2. And set different permissions for each operation in user's program. After that I thought another method: Create postgresql database and tables in it. Create a website with … -
django ORM - Exclude on M2M with F-function not working
I have the following models: class Activity(models.Model): user = models.ForeignKey(User, related_name='activities') project = models.ForeignKey(Project, related_name='activities') class Project(models.Model): assignees = models.ManyToManyField(User, related_name='projects') Now I want to query for all the activities which belog to a user which is NOT in the projects assignees. My query: Activity.objects.exclude(project__assignees=F('user')) Problem is, I always get this error: django.db.utils.OperationalError: (1054, "Unknown column 'U2.id' in 'on clause'") Im working on django 2.2.11 and MySQL. I found a couple of old django bugs but they are supposed to be fixed since ages. Any ideas how I can solve my problem? My activity table is huge and I need an efficient way. And I'd be happy to not use raw queries. Thanks! -
How to make popup 'add' window in Django 3?
In django admin, when there is a ForeignKey or ManyToManyField, there is [+] button to add it like this : How can I make that [+] button with popup window using forms in templates ? -
django-revison: how to get Version objects created using RevisionMiddleware in a request
I'm using django-revision, it's a package for versioning the objects state. I'm using it's midddleware (RevisionMiddleware) that wraps all requests and upon catching any changes to a model makes Version objects that store the changes, and I want to catch all Version objects that will be created during the processing of a request. I want to add the id's of the created objects to the request object but after looking at the middleware code I can see that the function that is responsible for creating the Version object doesn't return anything after the creation. Is there an elegant way to do it? -
No module named 'settings_general' when module exists
When I run manage.py in my terminal, I am getting the error ModuleNotFoundError: No module named 'settings_general'. But, this module does exist in the project in a subfolder. I've ran this manage.py many times, but on mac. And now that the pandemic is occurring I am working from home and am working on a PC with Windows 10. I am using cmder for my terminal and conda for my virtual environment. Any suggestions on how to solve this issue would be greatly appreciated. Note: This is worked on with a team and there should not be changes made to the file hierarchy or the contents of the file. Here's my traceback for running "python manage.py migrate": C:\Users\user\work\urec (master -> origin) (urec) λ python manage.py migrate Traceback (most recent call last): File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\commands\migrate.py", line 63, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\database.py", line 9, in check_database_backends for conn in connections.all(): File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 222, in all return [self[alias] for alias in self] File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 219, in __iter__ …