Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'memoryview' object has no attribute '_committed'
I am writing app for students project and encountered problem when saving modified model object Model: class Appointments(models.Model): id = models.IntegerField(primary_key=True) patient_pesel = models.ForeignKey('Patients', models.DO_NOTHING, db_column='patient_pesel') appointment_date = models.DateTimeField(blank=True, null=True) department = models.ForeignKey('Departments', models.DO_NOTHING, db_column='department') room = models.ForeignKey('Rooms', models.DO_NOTHING, db_column='room', blank=True, null=True) doctor = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='doctor', blank=True, null=True) appointment_type = models.ForeignKey('DAppointmentType', models.DO_NOTHING, db_column='appointment_type') suggested_date = models.DateField() referral = models.FileField(upload_to='referrals', blank=True, null=True) nfz = models.BooleanField() recommendations = models.TextField(blank=True, null=True) accepted_at = models.DateTimeField(blank=True, null=True) accepted_by = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='accepted_by', blank=True, null=True, related_name='accepted_HospitalStaff') updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) updated_by = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='updated_by', blank=True, null=True, related_name='updated_HospitalStaff') class Meta: managed = True db_table = 'appointments' View: def staff_accept_single_appointment_2(request): app_id = request.POST.get("appointment_id") date = request.POST.get("app_date") time = request.POST.get("app_hour") doctor = request.POST.get("doctor") room = request.POST.get("room") date_time_obj = datetime.strptime((str(date)+' '+str(time)).replace('-','/'), '%Y/%m/%d %H:%M') doctor_object = HospitalStaff.objects.get(id=doctor) room_object = Rooms.objects.get(room_name=room) app_object = Appointments.objects.get(id=app_id) app_object.appointment_date=date_time_obj app_object.doctor=doctor_object app_object.room=room_object app_object.save() return HttpResponseRedirect('/staff/registration/accept_appointments/accept_single_appointment') also checked much simpler version of view: def staff_accept_single_appointment_2(request): app_object = Appointments.objects.get(id=1) app_object.save() and i am still encountering 'memoryview' object has no attribute '_committed' error and can not go around it. Tried also using objects.filter().update() . It does not throws an error, but it does not affect database eighter. Tried searching solutions, maybe it is connected with FileField in … -
In Django Tables2, how do you make a column show text from a table referenced by a foreign key?
After reading all the docs and answers I can find, and burning a whole day, I still can't make this work. Using Django Tables2, I want to show a list of instruments; the instruments table includes a foreign key to an instrumentsType table. When I list the instruments and their attributes, I want to use the foreign key to substitute the textual instrument type description from the other table. I have tried every combination of double underscores and other accessor techniques, but so far all I get is the dreaded -- in the column. (Displaying just the record ID works). from .models import Instrument from django_tables2 import A from instrumenttypes.models import InstrumentType class InstrumentTable(tables.Table): id = tables.LinkColumn('instrument_details', args=[A('station_id')]) class Meta: model = Instrument template_name = "django_tables2/bootstrap.html" fields = ("id", "instrument", "nickname", "serialNo", "instrument__instrumenttype_id__instrumenttypes__id_instrumentType" ) The models involved are: Instruments model.py from django.db import models from instrumenttypes.models import InstrumentType from stations.models import Station # Create your models here. class Instrument(models.Model): instrument = models.CharField(max_length=40) instrumenttype = models.ForeignKey(InstrumentType, on_delete=models.CASCADE, null=True) station = models.ForeignKey(Station, on_delete=models.CASCADE, default=1) serialNo = models.CharField(max_length=60, null=True, blank=True) dateAdded = models.DateTimeField("Date Added", null=True, blank=True) dateRemoved = models.DateTimeField("Date Removed", null=True, blank=True) status = models.CharField(max_length=10, null=True, blank=True) nickname = models.CharField(max_length=40, null=True, blank=True) InstrumentTypes … -
Sum of column values inside Json array with group by
I have next Django model. class StocksHistory(models.Model): wh_data = models.JsonField() created_at = models.DateTimeField() I store JSON data in wh_data. [ { "id":4124124, "stocks":[ { "wh":507, "qty":2 }, { "wh":2737, "qty":1 } ], }, { "id":746457457, "stocks":[ { "wh":507, "qty":3 } ] } ] Note: it's data for one row - 2022-06-06. I need to calculate the sum inside stocks by grouping them by wh and by created_at so that the output is something like this [ { "wh":507, "qty":5, "created_at":"2022-06-06" }, { "wh":2737, "qty":1, "created_at":"2022-06-06" }, { "wh":507, "qty":0, "created_at":"2022-06-07" }, { "wh":2737, "qty":2, "created_at":"2022-06-07" } ] I know how to group by date, but I don't understand how to proceed with aggregations inside JsonField. StocksHistory.objects.extra(select={'day': 'date( created_at )'}) .values('day') .annotate( ??? ) A solution is suitable, both through Django ORM and through RAW SQL. -
Django admin - create user without set password
I need to set the admin user creation to let register an user but without request the password. password1 and password2 fields are required in admin forms. does anybody know how to achieve it? thanks! -
Django built in filter truncatewords ,how to get the left words?
I have a string named message equals to "Hello word how are you", In the Django template if I use: <div>{{message|truncatechars:2 }}</div> Then I will have: <div>Hello word</div> My question is except using {{message|slice:'11:'}},is there anyway I can get the rest words in message by using truncatechars or other django buit in template ? the output need be : how are you -
Toggle is_superuser in django admin
How to toggle a boolean field is_superuser in the django admin panel which enables a user to become superuser? I am using AbstractUser for my user model. -
Google Analytics Measurement Id as Environment Variable
I just started using Google Analytics and I have my code in my base html file for a Django web app. <!-- Global site tag (gtag.js) - Google Analytics --> <script nonce="{{ CSP_NONCE }}" async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX"></script> <script nonce="{{ CSP_NONCE }}"> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag("config","G-XXXXXXXXX"); </script> <!-- end GA --> My question is, for the measurement id (G-XXXXXXXXX) is this something that needs to be a secret? I keep all my keys, etc in the env file and though I could do the same with this id but I keep running into errors. I tried {% 'GOOGLE_ID' %} but that didn't work. Is there a good way to implement this? -
How to count the total non-distinct many-to-many relationships across objects of a model?
Assume I have the following models: class Tag(Model): name = CharField() class Book(Model): title = CharField() tags = ManyToManyField(Tag) Now suppose I have 3 books, and each book has 3 tags. Some of the tags might be the same for some of the books, it doesn't matter. Book 1 (Tags = "tag1", "tag2", "tag3") Book 2 (Tags = "tag1", "tag4", "tag5") Book 3 (Tags = "tag4", "tag5", "tag6") How can I count all non-distinct tags in a Django ORM query so that I get 9 as a result? -
How to run a backend script on Django from html page
I'm trying to process apple pay payments on my Django site. While I understand that this is better off in the back end, I currently am running the scripts in a JS static file, which means that that info is public. How can I set up my project to run a back-end python script when the apple pay button is clicked? Please discuss file organization in your answer. (For simplicity, you can just assume I am trying to run a script that loads another website instead of going through the whole apple pay process.) I came across this resource and it looked like it could be along the right track, but I think it might be overcomplicating things. https://github.com/Jason-Oleana/How-to-run-a-python-script-by-clicking-on-an-html-button -
Is there a method to pass react sessionStorage data to django rest framework backend?
I have a variable named hostwhich stores a session id for a user who visits my site. The variable is stored in sessionStorage of my react frontend. Is there a way of passing this variable to my backend without having to fetch for an API view root from the backend? -
Django is not fetching another app static file but fetching the main app static file?
Django is fetching the main app static files but it is not fetching the other app static files how to solve it ?? Error in CC is: Main File : Html Link Of CC : Main html link : Folder structure : -
Django Rest Framework authentication with Custom User Model
I have multiple types of user in my django app: Employee and Patient. They have fields that are specific to each of them. They are implemented using the AbstractBaseUser model as below: from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) USERNAME_FIELD = 'identifier' first_name = models.CharField( max_length=50, null=False, blank=False) last_name = models.CharField( max_length=50, null=False, blank=False) date_of_birth = models.DateField(null=False, blank=False) USER_TYPE_CHOICES = ( (1, 'Patient'), (2, 'Employee'), ) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, default=1, blank=False, null=False) class Role(models.Model): RoleName = models.CharField(max_length=50, null=False, blank=False) class Employee(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) employment_start_date = models.DateField(null=False, blank=True) employment_end_date = models.DateField(null=False, blank=True) role = models.ForeignKey( Role, on_delete=models.CASCADE, related_name='assigned_employees') class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) I have a few questions with how to go forward with this: How does just the choice in the User class limit the fields that a user has access to? If I had a HTML page would I create an Employee then a User would be created, or the other way round? When I'm using Django Rest Framework, how can I implement a sign up and log in with the two different types? I'm struggling to understand how this would work conceptually. Is … -
Integrating chainable animation image gallery code into Django project
I'm building a website using Django and I want to add this image gallery to one of my pages, but I'm having issues integrating the code. The HTML, CSS, and JS code I want to add is here: https://gist.github.com/CodeMyUI/9769b75c7a81d24138ae74bdbadc39e4 I've added the JS (inside a <script> element) and HTML to my django template, and added the CSS to my project's style.css file, but when I try to render, I'm getting a console error: Uncaught TypeError: Cannot read properties of null (reading 'classList') I also don't see anywhere in the code snippets that points to the images that I want to use for the gallery. Help on what I'm missing to successfully integrate this cool image gallery would be appreciated. -
Migrating sqlite to mysql using Django
I’m new to Django and web servers, and have been stuck for a few days. I inherited a Django app, python version 2.7 and Django version 1.9. The app was previously using the default SQLite databases. I want to migrate to Mysql for performance reasons. I loaded the data into the sqlite db using reset_db I installed mysqlclient I created a mysql db I created a username and password for a user and granted all permissions I dumped the data into a file called dump.json using python manage.py dumpdata > dump.json I changed the settings file to use django.db.backends.mysql I tried to load data using python manage.py loaddata and with makemigrations, migrate, it fails with the following error (with ANY manage.py command): (eKichabiTest) ananditharaghunath@Anandithas-MacBook-Pro db-test % python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 398, in execute self.check() File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/opt/anaconda3/envs/eKichabiTest/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver … -
Order of operations in Django Templates
I'm trying to call a dictionary named test with a key 'example' corresponding to a value 'OK'. I am trying to call it inside of a Django template, i.e. {{test.example}}. The problem is that I want to call this dynamically, so I pass an object and it has an ID of 'example' -> {{test.(object.id)}}. How do I go about this? -
Command Cancelled! on running orator migrate command in django
When I'm running the orator migrate command then giving Command Cancelled! I have installed orator in Django Orator: 0.9 Python: 3.9.7 django: 4.0.5 I create created a migration and model that you can see my code and set the connection but when I'm running migrate command then comming Command Cancelled! db connection orator.py from orator import DatabaseManager import environ env = environ.Env() environ.Env.read_env() config = { 'mysql': { 'driver': 'mysql', 'host': 'localhost', 'database': env('DB_DATABASE'), 'user': env('DB_USERNAME'), 'password': env('DB_PASSWORD'), 'prefix': '' } } db = DatabaseManager(config) migration file from orator.migrations import Migration class CreateProductsable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('products') as table: table.increments('id') table.integer('category_id').unsigned() table.timestamps() table.foreign('category_id').references('id').on('jobs').on_delete('cascade') def down(self): """ Revert the migrations. """ self.schema.drop('products') model file from orator import Model class Product(Model): __table__ = 'products' -
What is this format? (similar to JSON)
I'm getting info from an API (Google Ads API) that looks like this on the browser: customer { resource_name: "customers/XXX" id: XXX } campaign { resource_name: "customers/XXX/campaigns/XXX" status: ENABLED name: "XXX" id: XXX } metrics { impressions: 0 } The source code looks like this: customer { resource_name: "customers/XXX" id: XXX } campaign { resource_name: "customers/XXX/campaigns/XXX" status: ENABLED name: "XXX" id: XXX } metrics { impressions: 0 } I guess this is similar to JSON, but not exactly. Is it a know-format or just random code? I want to turn this data into an HTML table (using Python/Django) and I'm not sure if I can use JSON solutions/libraries (or similar ones) or if I need to create my own custom solution. Thanks! -
Transform VB6 Applications to dual-platform using python
This is my first time asking here, just to be clear I don't want any code or anyone to make something for me, I'm searching for a solution, so I can start building what I want. I searched a lot but didn't find the answer. In our company we have an OLD "Legacy" VB6 application, and if we have a new employee we need to install and do multiple things to make this application work. I found a program called "Thinfinity" that take the application and sorta make it work like a web application and you can access it through an IP address. What I'm searching for here, Is there a way to make the same concept using Python? Again, I don't want someone to make it for me, I just want someone to put me in the right/correct direction to do it Excuse my English & Thanks in Advance -
How to integrate google celender using django rest api
I am unable to integrate Google calendar using Django rest API. I need to use the OAuth2 mechanism to get users' calendar access. -
How to correctly raise the desired error or override the error in the class?
In my code for validating a token, for any error or invalid token, I always gives an error 500. I need to get an error 401, or 403. Here is part of the code. class AzureVerifyTokenError(Exception): pass class InvalidAuthorizationToken(AzureVerifyTokenError): def __init__(self, details=''): super().__init__(f'Invalid authorization token: {details}') def verify_jwt(*, token, valid_audiences, jwks_uri, issuer, verify=True): public_key = get_public_key(token=token, jwks_uri=jwks_uri) try: decoded = jwt.decode( token, public_key, verify=verify, algorithms=['RS256'], audience=valid_audiences, issuer=issuer, ) except jwt.exceptions.PyJWTError as exc: raise InvalidAuthorizationToken(exc.__class__.__name__) else: return decoded What I already tried: In the part where there is a try, I tried to return 401. from rest_framework import status from rest_framework.response import Response ..... except jwt.exceptions.PyJWTError: return Response(status=status.HTTP_401_UNAUTHORIZED) ..... But this obviously doesn't work. Or I don’t import what I need, or I don’t use what I need. Am I doing something wrong, or am I missing something. I even think it should be easy, but I'm completely lost. Perhaps the class AzureVerifyTokenError(Exception): pass is empty for a reason and I can set error there, but how? Any hints and examples will help me. Thank you. -
Django redirect to another view not working, url redirect is though
I have a view that I just want to redirect to another view for test purposes. When I hardcode the URL it works. def testDirect(request): return HttpResponse("redirected to correct pagge") def randomQuestion(request): random_question = Question.objects.order_by('?')[0] return redirect("/polls/testDirect") However, what I really want to do is call it by it's view name. When I look at the docs it gives me this example below: By passing the name of a view and optionally some positional or keyword arguments; the URL will be reverse resolved using the reverse() method: def my_view(request): ... return redirect('some-view-name', foo='bar') But when I try it like that I get the following error def randomQuestion(request): random_question = Question.objects.order_by('?')[0] return redirect('testDirect') Not sure what I am doing wrong -
Django socketio client connects but returns 404 not found
here is my django server.py file import socketio import eventlet SOCKET_PORT = 8000 sio = socketio.Server() app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print(sid, 'connected') @sio.event def disconnect(sid): print(sid, 'disconnected') @sio.event def test(sid, data): print(data) def initSocket(request): eventlet.wsgi.server(eventlet.listen(('', SOCKET_PORT)), app) and this is my client.py file import socketio client = socketio.Client() client.connect('http://localhost:8000') client.emit('test', 'hello world') this is wsgi.py file from django.core.wsgi import get_wsgi_application import os import eventlet import eventlet.wsgi os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'b2b_backend.settings') application = get_wsgi_application() eventlet.wsgi.server(eventlet.listen(('', 8000)), application) and finally urls.py file from webSocket.views import initSocket urlpatterns = [ path('', initSocket) ] this is the output of the server when I launch the client.py file from cmd. Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (22588) wsgi starting up on http://0.0.0.0:8000 (22588) accepted ('127.0.0.1', 58933) Not Found: /socket.io/ 127.0.0.1 - - [29/Jun/2022 19:00:08] "GET /socket.io/ transport=polling&EIO=4&t=1656518406.600064 HTTP/1.1" 404 3092 0.010074 when the django server starts at port 8000, it will also start the socketio server on the same port by calling the initSocket method, then I start the client.py file from cmd (I'm using cmd for testing), all it should do is connect to the server and emit an event. All I'm trying to do is get the clients … -
Django - tests not discovered after moving code to another directory
When my app layout was project/ ├── app1/ │ ├── __init__.py │ ├── tests.py ├── app2/ ├── Dockerfile ... └── manage.py running python manage.py test worked just fine. Then code was moved to src/ dir, i.e. project/ ├── src │ ├── app1/ │ │ ├── __init__.py │ │ ├── tests.py │ ├── app2/ │ ... │ └── manage.py ├── Dockerfile ... and now no tests are discovered root@650001aeb6b5:/app# python src/manage.py test Found 0 test(s). System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK I have tried using the -t option but that didn't help root@650001aeb6b5:/app# python src/manage.py test -t src ... ImportError: Start directory is not importable: '/app' Any idea how to make this work? My guess is test discovery configuration should be updated but I have no idea how to do that. -
Django Ajax posting duplicate values to the view
Im trying to post the value of a html item(the id of the item) to the view so it can add the item to the cart, however it always posts the value of the last item printed by the django {% for %} even though the html source says the values are different here is my html <div class="container"> <div class="row row-cols-2 row-cols-md-3" data-masonry='{"percentPosition": true }'> {% for product in products %} <div class="col mb-4"> <div class="card h-100"> {% if product.image %} <img src="{{ product.image.url }}" class="card-img-top" alt="{{ product.description }}"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.description|slice:":100" }}...</p> <p class="card-text">${{ product.price }}</p> <p> <a class="btn btn-dark gap-2 mb-1" href="{{ product.get_absolute_url }}">View Item</a> <button class="btn btn-outline-success" id="add-to-cart" value="{{ product.id }}">Add to Cart</button> </p> {% if product.in_stock == False %} <p> Item is currently out of stock </p> {% endif %} </div> </div> </div> {% endfor %} </div> </div> Here is the Ajax $(document).on('click', '#add-to-cart', function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "add_to_cart" %}', data: { productid: $('#add-to-cart').val(), csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function(json){ }, error: function(xhr, errmsg, err) { } }); }) Here is my view def CartAddView(request): cart = Cart(request) … -
Django validate ModelInlines in Parent Model
Suppose we have 2 django models: class File: # Comma separated list of column names unique_columns = models.CharField(max_length=200) class Column: file = models.ForeignKey(File, on_delete=models.CASCADE) name = models.CharField(max_length=50) In admin.py class ColumnInline(nested_admin.NestedTabularInline): model = Column class FileAdmin(admin.ModelAdmin): inlines = [ColumnInLine] What I want to achieve When saving these models in the Admin page I want to validate whether the Files' unique_columns are also set as Columns related to this File (by validating a related object with that name exists) What I tried Obviously, a clean() method on File won't work as it's saved before Column. Overriding save_formset on FileAdmin, however I don't fully understand how to access the Column forms Question How to achieve this? Is it possible by using a custom form? Or can I override save_formset and do the validation I want? As a more general question: What is a good way to do such validations where validating one form depends on forms of other objects?