Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
websocket.send method not doing anything in javascript even if the connection established successfully
guys, I had to implement WebSockets using channels in Django,but even after the connection is established successfully, WebSocket.send method is not working in javascript and it works only inside websocket.onopen here's my javascript code for the socket let noteSocket = null function connect(){ noteSocket = new WebSocket('ws://' + window.location.host + `/ws/mycourses/{{ course.productId }}/chapters/{{ last_followed.chapter.chapterId }}/lessons/{{ last_followed.lessonId }}/notes/`) noteSocket.onopen = function(e) { console.log("Successfully connected to the WebSocket."); } noteSocket.onclose = function(e) { console.log("WebSocket connection closed unexpectedly. Trying to reconnect in 2s..."); setTimeout(function() { console.log("Reconnecting..."); connect(); }, 2000); }; noteSocket.onmessage = function(e){ const data = JSON.stringify(e.data) renderNote(data.note, data.timestamp) } } after executing the connect function I get these in the Django development server terminal WebSocket CONNECT /ws/mycourses/879521fa-75f9-4c95-8b61-039f7503ecae/chapters/91a12b16-35f7-4702-a002-35b228010a94/lessons/90a125ad-570e-437e-ac67-46cdeb55a068/notes/ [127.0.0.1:53424] and I get from my browser console: Successfully connected to the WebSocket. I am using google chrome, and my os is arch Linux(note: I even tried in firefox but it didn't work) -
Why Django does not recognize my USERNAME_FIELD in User Model
I have this error when I try to make migrations "django.core.exceptions.FieldDoesNotExist: User has no field named 'username'" This is the complete error log here below: Traceback (most recent call last): File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\db\models\options.py", line 668, in get_field return self.fields_map[field_name] KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\acer\Desktop\dev\python\djusers\djusers\manage.py", line 22, in <module> main() File "C:\Users\acer\Desktop\dev\python\djusers\djusers\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\base.py", line 443, in execute self.check() File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\contrib\auth\checks.py", line 55, in check_user_model if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any( File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\db\models\options.py", line 670, in get_field raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: User has no field named 'username' This is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin # Create your models here. class User(AbstractBaseUser, PermissionsMixin): """ clase para generar mi modelo personalizado de Users """ GENDER_CHOICES = [ ('1', 'hombre'), ('2', 'mujer') ] username = models.CharField("nombre de usuario", max_length=50, unique=True), full_name = models.CharField("nombre completo", max_length=150), gender = models.CharField("género", max_length=1, choices=GENDER_CHOICES), age … -
DJANGO - 404 media when debug is FALSE
I've a trouble with django and I don't know how to fix it. I use DJANGO 3.2.8 and Python 3.7.12 I code an app that allow a user to upload some file into my DB and when an admin are login he can select an user and clic on ID then it's display the user's ID. When I turn DEBUG = True, everything is ok but when I turn DEBUG = False, I've an 404 error when I try to display the user's ID and I don't know how to fix, I try many thing but nothing work (I use collectstatic for the CSS and it's work when DEBUG = FALSE I've got all my pictures ...) My ID are save in media folder. Setting BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = 'staticfiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Model def path_and_rename(path, prefix): def wrapper(instance, filename): ext = filename.split('.')[-1] project = "pid_%s" % (instance.name,) # get filename if instance.pk: complaint_id = "cid_%s" % (uuid.uuid4().hex,) filename = '{}.{}.{}.{}'.format(prefix, project, complaint_id, ext) else: # set filename as random string random_id = "rid_%s" % (uuid.uuid4().hex,) filename = '{}.{}.{}.{}'.format(prefix, project, random_id, ext) … -
Whats the point of using a virtual environment for flask and django?
I just want to try out django and or flask but all the videos I see say that I need to get a virtual env. I don't see the point and I don't really want to get one but all of the tutorials say I need one. Can someone explain too me if using a virtual env is required and if it is not what are the pros? -
how to send OTP in django via sms or email
I need some help sending and verifying OTP in Django. am trying to add 2FA to my authentication module and I came across a package called pyotp that helps generate and verify OTP. The good thing is that am able to use this package to generate OTP but my problem is how to verify this OTP if expired or incorrect when I prompt the user to supply the otp sent to his/her phone or mail. the below code is what I have implemented from the doc but I don't know why the verification part ain't working. I could actually verify manually but that wont tell me if OTP has expired or not and i don't also know how to expire OTP after a particular time TO GENERATE OTP import pyotp base32secret3232 = pyotp.random_base32() otp = pyotp.TOTP(base32secret3232) time_otp = otp.now() user.otp = time_otp user.save() TO VERIFY OTP if totp.verify(otp): user.is_verified = True user.save() -
Edit form Select field not shows the empty label or not show the selected value in DJango
I have a ModelForm name ProductForm with model Product, many to one relation with Type. So automatically this form creates me a Select for select the Type of Product. Then if I set all data in ModelForm according with the docs in Django, everything works well, but i would like add an emtpy label to the Select. Like this: class Product(models.Model): type= models.ForeignKey(Types, on_delete=models.CASCADE) code=models.CharField(max_length=50) name=models.CharField(max_length=1000) details=models.CharField(max_length=1000) um=models.CharField(max_length=50) def __str__(self): return self.name class ProductForm(ModelForm): class Meta: model = Product fields='__all__' labels = { 'code': 'Code', 'name': 'Product', 'type':'Product type', 'um': 'UM', 'details': 'Details' } widgets = { 'code': TextInput( attrs={ 'class':'form-control', 'placeholder':'Code' } ), 'name': TextInput( attrs={ 'class':'form-control', 'placeholder':'Product' } ), 'um': TextInput( attrs={ 'class':'form-control', 'placeholder':'UM' } ), 'type' : Select(attrs={'style':'width: 100%', 'class':'form-control select2bs4'}), 'details': Textarea( attrs={ 'style':'height:150px', 'class':'form-control', 'placeholder':'Details' } ), } But with this I have no idea where put the empty_label for the Select, because emtpy_label is for ModelChoise. So, I use another solution, changing the ModelForm like bellow (only that code, not the code above), works the empty label, but the edit form, not shows the selected value, So is one or other, but i like both of them: class ProductForm(ModelForm): code= CharField(label='Code',widget=TextInput(attrs={'class':'form-control','placeholder':'Code'})) name = CharField(label='Product',widget=TextInput(attrs={'class':'form-control', … -
Assignin object to self inside class method
I want to do a check inside model whether object already exists in DB or not, and if its exists to read all properties from DB and assign to same object. models.py class Obj1(models.Model) name prop1 prop2 prop3 def obj_check(self, name, prop1): objects = Obj1.object.filter(name=name, prop1=prop1) len = len(objects) if len == 0: # Object does not exists in DB self.name = name self.prop1 = prop1 self.save() return 0 elif len == 1: # Object does exists in DB self = objects[0] # <<< Is it possible to do like this? return 1 else: # Something wrong, too many objects in DB return len main.py ... obj = Obj1() check = obj.obj_check(name, var) if check == 0: print("Such object does NOT exists") print("New object created") elif check == 1: print("Such object already exists") obj.prop3 = "New Value" else: print("Something wrong, too many objects in DB") Is this possible/right to do like this? self = objects[0] I know I can use try: .. except Obj1.DoesNotExist: costruction, but wanted to create Object first. Thanks! -
Django admin panel is not displayed correctly, how to fix it?
This screenshot show the problem i am having. However, when you minimize window, the page is displayed normally.enter image description here -
no module named parsing when importing django models to python script
Hi there Im having issues importing my models into my application called parsing project structure looks like: manage.py enumproject/ db.sqlite3 parsing/ with enumproject/settings.py I have it in INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'parsing', 'parsing.apps.ParsingConfig', ] models.py under parsing/models.py has: from enumproject import models # Create your models here. class tbl(models.Model): nm=models.CharField(max_length=20, unique=True) dtAdded=models.DateTimeField() #etc... im attempting to run parse.py from parsing/parse.py from parsing.models import * #python code here when I run this file, I get: Traceback (most recent call last): File "parse.py", line 8, in <module> from parsing.models import * ModuleNotFoundError: No module named 'parsing' thoughts? -
Question about parsing a URL generated during a button click event in HTML
I built a form in HTML5 to take input from users. I'm using the GET method. I want to assign the data the user put into the form and assign it to variables in a python script, which will do some logic then render another page at the end of the script which will present the data to the user. I have been researching the past day or so about different methods by which this can happen. I'm running on Django right now. I was going to use CGI, because the syntax seemed pretty straightforward: import cgi form = cgi.FieldStorage() py_var = form.getvalue('name-in-html-tag') But from what I've read is that this method is only suitable for cgi scripts. When I print() py_var I continually get a value of None. So I started reading about using the urllib package to parse GET method urls. But the examples I keep finding online show the URL hardcoded into the scripts, which isn't much help in my situation. Is there a way that I can get the URL generated from the GET method so that I can parse it and use the data in a python script? Everyone seems to have their own way … -
Django save() method executed twice
I,m developing a simple CRUD app. There are two main models: empleado (employee) and oficina (office or department). Each "empleado" belongs to a "oficina" class empleado(models.Model): """Model definition for empleado.""" apellidos = models.CharField('Apellidos', max_length=50, blank=False) nombres = models.CharField('Nombres', max_length=50, blank=False) full_name = models.CharField('Nombre completo', max_length=50, blank=True) dni = models.CharField('DNI', max_length=50, blank=False, unique=True) habilidades = models.ManyToManyField(habilidad, blank=False) area = models.ForeignKey(oficina, on_delete=models.CASCADE, blank=False, related_name = 'area_empleado') The model for "oficina" has a field called "personal" that stores the number of employees in that department class oficina(models.Model): """Model definition for oficina.""" nombre = models.CharField('Nombre', max_length=50) nombre_corto = models.CharField('Nombre corto', max_length=50) personal = models.PositiveIntegerField(default = 0) I used generic views to create new employees class EmpleadoCreateView(CreateView): model = empleado template_name = "empleado/create.html" form_class = EmpleadoForm success_url = reverse_lazy('empleado_app:Lista de empleados') def form_valid(self, form): emp = form.save(commit=False) emp.full_name = emp.nombres + ' ' + emp.apellidos emp.save() return super(EmpleadoCreateView, self).form_valid(form) This is the EmpleadoForm class: class EmpleadoForm(forms.ModelForm): """Form definition for Empleado.""" class Meta: """Meta definition for Empleadoform.""" model = empleado fields = ('apellidos', 'nombres', 'dni', 'habilidades', 'area', ) widgets ={ 'habilidades' : forms.CheckboxSelectMultiple() In order to keep the number of employees updated, I use a couple of signals (for the "empleado" model): def update_personal_dec(sender, instance, **kwargs): … -
unable to render the context value in django template on ubuntu server
I have this piece of code that is working fine on my PC environment (virtual environment) but causing problems in a ubuntu, Nginx server. It is a digital ocean droplet actually. I am not very much familiar with ubuntu that's why I am unable to understand the cause of the problem. Now the problem is, that the 'checkout.html' template doesn't render the value of 'fire'. I have tried to troubleshoot manually and in the 'inspect' window I only see an empty label. Why is this happening, is it because of the django=2.2.3 version or ubuntu or Nginx or am I missing anything here? Note: I am updating the files through Filezilla. Kindly help, please. Views.py def checkout(request): return render(request, 'checkout.html', {'fire':"fire"}) checkout.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <label>{{fire}}</label> </body> </html> urls.py from .views import * path('checkout-page', checkout, name="checkout"), -
Urls file in django application
I am working with Django,have a type error TypeError: path() got an unexpected keyword argument 'name' but my urls.py file reads from. import views from importlib.resources import path from unicodedata import name urlpatterns=[ path('register_user/ ',views.register,name='user'), path('register/',views.registering_patient,name='register_patient'), ] -
Django i18n - how to translate included templates
I have a django project using i18n for translations. When I type : python3 manage.py makemessages -a All my project templates and views are processed to build the django.po file except the templates that are included within another template. Example the high-level template has: {% include 'journey/journeysTable.html' %} With journey/journeysTable.html looking like: {% load i18n %} {% load static %} <table class="table table-striped caption-top tableRowIsLink"> <thead> <tr> <th scope="col">{% trans "Code" %}</th> <th scope="col">{% trans "Name" %}</th> {%if hide_user is None %} <th scope="col">{% trans "Artist" %}</th> {% endif %} <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody id="journeysTableBody"> ... </body> </table> The {% trans %} tags do not produce any error, but associated text is not in the django.po file. journey is an app and the included template is in journey/templates/journey/ folder. Other templates in the same folder are translated. Is it a normal behaviour? I understand that both templates are rendered separately but they should both be translated. -
FileResponse with file opened using smart-open
I'm trying to let a user download a file from my webpage. The file is in an S3 bucket I'm accessing using smart-open. The issue I'm having is how to combine that with FileReader. Presently I'm getting a TypeError: "expected str, bytes or os.PathLike object, not Reader". The filetypes will be .txt, .pdf and .doc/.docx My view: @api_view(['GET']) def download_attachment(request, pk): session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) obj = Attachment.objects.get(id=pk) with smart_opener(f's3://______media/public/{str(obj)}',"rb",transport_params={'client':session.client('s3')}) as attachment: response = FileResponse(open(attachment, 'rb')) response['Content-Disposition'] = f'attachment; filename={obj.file.name}' return response -
define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
I have no idea what to Ive tried uninstalling python and django. Reinstalled it failed, installed it in Unbuntu still doesnt work. I get the same error message. Nothing works! ''' Traceback (most recent call last): File "/tmp/virtual-virgin_env/my_env/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/conf/init.py", line 92, in getattr self._setup(name) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/conf/init.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ''' -
how to find sum from foreign key table along with some filtering in django orm?
class UserAndQuiz(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) quiz = models.ForeignKey(QuizInfo,on_delete=models.CASCADE) created_at = models.DateTimeField(null=True,blank=True) is_submit = models.BooleanField(default=False) result = models.IntegerField(default=0) class QuizInfo(models.Model): quiz_name = models.CharField(unique=True,max_length=255) number_of_question = models.IntegerField() number_of_option = models.IntegerField() quiz_type = models.CharField(max_length=255,choices=quiz_status) price = models.FloatField(default=0.0,null=True,blank=True) image = models.ImageField(upload_to='pics') description = models.TextField() def __str__(self) -> str: return self.quiz_name Related SQL query = SELECT sum(price) from quizsession_quizinfo as q JOIN user_userandquiz as p on q.id = p.quiz_id where p.is_submit=1; what is the ORM of this query? -
Why i am getting this error no such table: main_person, if i never tried to create that table?
I am trying to create my first crud with django, but now i came across with this error i have the urls like this, this is in the same level with wsgi.py urlpatterns = [ path('admin/', admin.site.urls), path('getData/', include('main.urls')), ] now i create other urls in my app inside: from django.urls import path from .views import getCars urlpatterns = [ path('', getCars), ] this is the view import imp from urllib import response from django.shortcuts import render from django.http import JsonResponse from django.core.serializers import serialize from .models import Person def getCars(request): cars = Person.objects.all() response_object = {'data': serialize("json", cars)} return JsonResponse(response_object) and the model is this from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) in any moment i am using main_person but i am getting this error: django.db.utils.OperationalError: no such table: main_person -
Packages Are not Importing on Docker even though they seem to be installed
I have tried installing new packaged. they all seem to load without and issue but somehow they are not importing. I have tried docker-compose build to no avail. They show up on pip freeze. My guess is somehow these are not loaded on my docker container but I am not sure what else to do. Sorry if my question is too elementary for this sub. I am a CS major and this is our first large project working with backend and frontend and I have stayed up all night trying to figure this up but I am lost I feel. Thanks for your help. Here are some of the packages in question drf-spectacular 'rest_framework', 'rest_framework.authtoken', django-address here is the content of my requirement.txt: Django>=3.2.4,<3.3 djangorestframework>=3.12.4,<3.13 psycopg2>=2.8.6,<2.9 drf-spectacular>=0.15.1,<0.16 here is what I have under registered apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'rest_framework', 'rest_framework.authtoken', 'drf_spectacular', 'user', 'address', 'phonenumber_field', pip freeze shows the following Mobile>pip freeze absl-py==1.0.0 alabaster @ file:///home/ktietz/src/ci/alabaster_1611921544520/work anaconda-client @ file:///C:/ci/anaconda-client_1635342725944/work anaconda-navigator==2.1.1 anaconda-project @ file:///tmp/build/80754af9/anaconda-project_1626085644852/work anyio @ file:///C:/ci/anyio_1620153135622/work/dist appdirs==1.4.4 argh==0.26.2 argon2-cffi @ file:///C:/ci/argon2-cffi_1613037869401/work arrow @ file:///C:/ci/arrow_1617738834352/work asgiref==3.5.2 asn1crypto @ file:///tmp/build/80754af9/asn1crypto_1596577642040/work astroid @ file:///C:/ci/astroid_1628063282661/work astropy @ file:///C:/ci/astropy_1629829318700/work astunparse==1.6.3 async-generator @ file:///home/ktietz/src/ci/async_generator_1611927993394/work atomicwrites==1.4.0 attrs @ file:///tmp/build/80754af9/attrs_1620827162558/work autopep8 @ … -
Advance django filters
I am working on a management system. Where I have models: class FeeType(models.Model): name = models.CharField("fee Type", max_length=200) duedate = models.DateField("due date") class Meta: verbose_name_plural = "Fee Type" def __str__(self): return self.name class CollectFee(models.Model): boarder = models.ForeignKey(Boarder, on_delete=models.CASCADE) feetype = models.ForeignKey(FeeType, on_delete=models.CASCADE) amountpaid = models.PositiveIntegerField("amount Paid") class Meta: verbose_name_plural = "Collect Fee" def __str__(self): return self.boarder.name Now in a template I want to show the list of all the boarders/students, who have not been assigned the last fee. e.g if "July Fee" is the last object in the FeeType model then show all those boarders who have not been assigned the JulyFee. I have tried a view for this: def feedue(request): last_fee_type = FeeType.objects.last() boarders = CollectFee.objects.exclude(boarder__collectfee__feetype=last_fee_type) context = {'boarders':boarders} return render(request, 'fee-due.html', context) It does not show the boarders who have been assigned the last feetype, that's correct. But if the boarder is not assigned the last feetype then it shows the boarder name as many times as he have been assigned the previous feetypes. Hope you understand. Help please. -
Issues with connecting python/pandas, to a Postgress DB hosted on Django Digital Ocean
I have difficulty finding my known tables in a Django/Postgress DB hosted on Digital Ocean. I seem only to get an outer layer of the database and not the tables working on the site's front end. conn = psycopg2.connect( host=HOST, database=DATABASE, user=USERNAME, password=PASSWORD, port=PORT, ) cur = conn.cursor() cur.execute("""SELECT table_name FROM information_schema.tables""") for table in cur.fetchall(): print(table) Here is a portion of the results, and not a single one is a known table books. ('pg_type',) ('pg_foreign_server',) ('pg_roles',) ('pg_settings',) ('pg_cursors',) ('pg_stat_bgwriter',) ('pg_subscription',) ('pg_stat_progress_vacuum',) ('pg_stat_progress_cluster',) ('pg_attribute',) . . . ('view_table_usage',) ('foreign_server_options',) ('column_options',) ('foreign_data_wrapper_options',) ('foreign_tables',) ('foreign_data_wrappers',) ('foreign_servers',) ('foreign_table_options',) ('user_mappings',) ('user_mapping_options',) I hope to finally run: df = pd.read_sql('select * from books', my_eventual_successful_connection) I get more discouraging results from SQLAlchemy, which does not output a result nor logging info for the following: engine = create_engine(f"postgresql+psycopg2://doadmin:{PASSWORD}@{HOST}:{PORT}/{USERNAME}?sslmode=require") from sqlalchemy import MetaData metadata_obj = MetaData() for t in metadata_obj.sorted_tables: print(t.name) While this: metadata_obj.tables.keys() returns (including the logging): INFO:sqlalchemy.engine.Engine:SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = %(schema)s AND c.relkind in ('r', 'p') INFO:sqlalchemy.engine.Engine:[cached since 38.66s ago] {'schema': 'public'} dict_keys([]) Though when I run: with engine.connect() as connection: df = pd.read_sql('select * from user', connection) df I get user 0 doadmin note … -
Django rest framework - Limiting get request access to only authorized user
You can see in this serializer I am checking that the authenticated user matches the instance's user: class CreateSupplierSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=200) email = serializers.EmailField(max_length=200) phone = serializers.IntegerField() def update(self, instance, validated_data): if str(self.context['request'].user) != str(instance.username): raise exceptions.PermissionDenied('You do not have permission to update') supplier = Supplier.objects.create(user=instance, **validated_data) return supplier class Meta: model=Supplier fields=['name','email','phone'] I am wondering how I can implement this same method into my get request, here is my get request format... models.py: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.CharField(max_length=200) email = models.CharField(max_length=200) class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.IntegerField() email = models.EmailField(max_length=200) views.py: class getsuppliers(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = GetSuppliersSerializer lookup_field = 'username' serializers.py: class SuppliersSerializer(serializers.ModelSerializer): class Meta: model = Supplier fields = ['pk','user','name','email','phone'] class GetSuppliersSerializer(serializers.ModelSerializer): supplier_set = SuppliersSerializer(read_only=True, many=True) class Meta: model = User fields = ['supplier_set'] -
Django combine search filter and annotation does not work
i am try to filter by datetime range but get wrong annotation results. def is_valid_queryparam(param): return param != '' and param is not None def my_func(request, tenant): products = Product.objects.filter(tenant=tenant).annotate( s_product=Sum('order_items__quantity'), vlera=Sum('order_items__price')) date_min = request.GET.get('date_min') date_max = request.GET.get('date_max') if is_valid_queryparam(date_min): products = products.filter(Q(created__gte=date_min)) if is_valid_queryparam(date_max ): products = products.filter(Q(created__gte=date_max)) the filter date range works for objects products, but not for the order_items__quantity and order_items__price, the result are incorrect -
How do I add a manytomany model field instance inside a ModelForm?
I have implemented a CustomUser model(using AbstractUser) and it has some ManytoManyFields. Now I can add an instance of it inside the admin panel but I haven't found out any ways to do it inside a ModelForm(without already having some ready made instances of it in database). The pic below shows the difference I'm trying to describe between what is available inside the admin and inside html templates form. -
Django Safari Iframe Issue
We have shopify app in django that is embedded in shopify. But this app is facing issues as an iframe in Safari Browser. I have referenced this doc https://pypi.org/project/django-iframetoolbox/ . But I didnt understand the order in which I have to include this in the MIDDLEWARE_CLASSES in settings.py. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'csp.middleware.CSPMiddleware', 'shopify_app.middleware.LoginProtection', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'iframetoolbox.middleware.IFrameFixMiddleware', ] This is the current order in which I have given and this is giving me the following error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'shopify_django_app.wsgi.application' could not be loaded; Error importing module.