Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django admin options for model like ADD/DELETE/UPDATE not showing
I use Django rest framework. After run python manage.py runserver if I open http://127.0.0.1:8000/admin/ then attached below image showing same If I open any model then options like ADD/DELETE/UPDATE options are not showing. Attached above img for same (user model) Errors in console showing below- requirement.txt aiohttp==3.6.3 appdirs==1.4.4 asgiref==3.2.10 async-timeout==3.0.1 atomicwrites==1.4.0 attrs==20.2.0 awacs==0.9.6 aws-xray-sdk==0.95 awscli==1.20.34 boto3==1.18.32 botocore==1.21.34 certifi==2017.7.27.1 cffi==1.14.3 cfn-flip==1.0.3 chardet==3.0.4 click==6.7 colorama==0.4.3 colorclass==2.2.0 cryptography==3.1.1 dateparser==0.7.6 defusedxml==0.6.0 dictdiffer==0.7.0 distlib==0.3.1 Django==3.0.9 django-3-jet==1.0.8 django-admin-rangefilter==0.6.3 django-allauth==0.42.0 django-cors-headers==3.6.0 django-extensions==3.0.6 django-filter==2.4.0 django-flat-json-widget==0.1.1 django-grappelli==2.14.2 django-json-widget==1.0.1 django-money==1.1 django-nested-admin==3.3.2 django-otp==1.0.0 django-phonenumber-field==5.0.0 django-prettyjson==0.4.1 django-sendgrid-v5==0.9.0 django-simple-history==2.11.0 django-slack==5.15.3 django-sort-order-field==1.2 django-split-json-widget==1.16 django-storages==1.9.1 django-twilio==0.13.0.post1 djangorestframework==3.11.1 docker==4.3.1 docutils==0.14 ecdsa==0.16.0 filelock==3.0.12 flatten-json==0.1.7 future==0.16.0 futures==3.1.1 idna==2.6 importlib-metadata==2.0.0 jet-bridge-base==0.8.0 Jinja2==2.11.2 jmespath==0.9.3 jsondiff==1.1.1 jsonpickle==1.4.1 jsonschema==2.6.0 MarkupSafe==1.1.1 mock==4.0.2 more-itertools==8.5.0 moto==1.3.7 multidict==4.7.6 oauthlib==3.1.0 phonenumbers==8.12.8 Pillow==7.2.0 pluggy==0.13.1 prompt-toolkit==2.0.9 psycopg2-binary==2.8.5 py==1.9.0 py-moneyed==0.8.0 pyaml==20.4.0 pyasn1==0.4.8 pycparser==2.20 pycryptodome==3.9.8 PyJWT==1.7.1 pyotp==2.4.0 pytest==4.0.0 python-dateutil==2.6.1 python-dotenv==0.14.0 python-http-client==3.3.1 python-jose==2.0.2 python-monkey-business==1.0.0 python3-openid==3.2.0 pytz==2020.1 PyYAML==5.3.1 regex==2020.7.14 requests==2.24.0 requests-oauthlib==1.3.0 responses==0.12.0 rsa==4.5 s3transfer==0.5.0 sendgrid==6.4.7 six==1.10.0 slackclient==2.9.2 SQLAlchemy==1.3.19 sqlparse==0.3.1 standardjson==0.3.1 starkbank-ecdsa==1.1.0 stringcase==1.0.6 terminaltables==3.1.0 troposphere==2.6.2 twilio==6.45.0 tzlocal==2.1 urllib3==1.25.10 virtualenv==20.0.31 wcwidth==0.2.5 websocket-client==0.57.0 Werkzeug==1.0.1 whitenoise==5.2.0 wrapt==1.12.1 xmltodict==0.12.0 yarl==1.5.1 zipp==3.2.0 I use pyenv for environment. -
how to uplaod image in django rest framework with heroku and aws s3 bucket storage
i am using heroku for my django rest framework project and i am using whitenoise storage but the problem with this is that after image uploading image it is disappear after some time i want permanently image storage with aws s3 bucket help me with that models.py class UploadImage(models.Model): img_id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='media/images/') def __str__(self): return str(self.image) what changes i have to make to use and store the images in aws s3 bucket -
Reverse for '' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$']
I am currently running into the above error when trying to render a Model Form. My form looks like this at the moment: Form.py: class SettingUpdateForm(ModelForm): class Meta: model = SettingsClass fields = '__all__' Models.py: Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) When the form is trying to render, it gives the following error based on my views.py: Full Error Message: NoReverseMatch at /accConnect/setting/2 Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Request Method: GET Request URL: http://localhost:8000/accConnect/setting/2 Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Exception Location: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\\Users\\KylePOG\\Documents\\GMA Programming\\accConnect', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 20 Sep 2021 06:35:19 +0000 Error during template rendering In template C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\templates\main\base.html, error at line 11 Reverse for 'viewSettings' with arguments … -
django: Images(MEDIA) not displaying heroku server
I have developed an ecommerse site using django framework. All the images are uploading through the admin panel.Its works fine locally. But, the images are not loading.Other fuctions are working perfectly. I have installed whitenoise and adds it to setting.py.But,it still not working. settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') Models.py class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False,null=True,blank=True) image = models.ImageField(null=True, blank=True) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('store.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) store.html {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product={{ product.id }} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float:right;"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} {% endblock content %} -
Django static files are not loaded on cPanel
I deployed a django app on cPanel. I installed python, django and set the STATIC Variables in settings.py and ran collectstatic. and everything works fine. I get the message in terminal that the static files are copied. but when I launch the application static files are not loaded and gives 404 error. but those static file exists in my public_html folder. I'm really stuck what could be the problem. When i checked the log file I get the following error : /opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses App 2893412 output: import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno I can see that the error is in wsgi-loader.py file. but I can't find it anywhere on the server. Please help it's taken days for me already. -
Upload multiple photos in Django REST admin panel
I can't find a solution to upload multiple photos to one ImageField in admin panel. I had StackedInline but it's not what I need because there each photo must be upload to new ImageField. I've gone through many questions which might have been close to mine but haven't got a solution yet. Admin panel is pretty much main part of my app. Is is possible to achieve this result in admin panel? This is how I want to see it models.py from django.db import models class User(models.Model): first_name = models.CharField(verbose_name='Имя', max_length=40) last_name = models.CharField(verbose_name='Фамилия', max_length=40) rfid_mark = models.CharField(verbose_name='RFID', max_length=10, editable=True, unique=True) registration_date = models.DateTimeField(verbose_name='Дата регистрации', auto_now=True, editable=False) def __str__(self): return self.first_name + ' ' + self.last_name class UserImage(models.Model): user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) photo = models.ImageField(verbose_name='Фото') def __str__(self): return '' -
How to scale mysql table to keep historic data without increasing table size
I have a questionnaire in my app, using which I am creating data corresponding to user who have submitted it and at what time(I have to apply further processing on the last object/questionnaire per user). This data is saved inside my server's MySQL db. As this questionnaire is open for all my users and as it will be submitted multiple times, I do not want new entries to be created every time for same user because this will increase the size the table(users count could be anything around 10M), But I also want to keep the old data as a history for later processing. Now I have this options in mind: Create two tables. One main table to keep new object and one history table to keep history objects. Whenever a questionnaire is submitted it will create a new entry in history table, but update the existing entry in main table. So, is there any better approach to this and how other companies tackle such situations? -
How can I split orders by attributes in my API
I have a method that creates an order from the user's basket. In order for the courier to take an order from different restaurants, the order is divided into several. But at the moment I'm splitting the order just by the dish in the basket. How to make an order split by restaurants, that is, if a user orders 5 dishes from two different restaurants, then 2 orders were formed views.py @action(methods=['PUT'], detail=False, url_path='current_customer_cart/add_to_order') def add_cart_to_order(self, *args, **kwargs): cart = Cart.objects.get(owner=self.request.user.customer) cart_meals = CartMeal.objects.filter(cart=cart) data = self.request.data for cart_meal in cart_meals: order = Order.objects.create(customer=self.request.user.customer, cart_meal=cart_meal, first_name=data['first_name'], last_name=data['last_name'], phone=data['phone'], address=data.get('address', self.request.user.customer.home_address), restaurant_address=cart_meal.meal.restaurant.address, ) order.save() return response.Response({"detail": "Order is created", "added": True}) models.py class Order(models.Model): """User's order""" customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='related_orders') first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) phone = models.CharField(max_length=20) cart_meal = models.ForeignKey(CartMeal, on_delete=models.CASCADE, null=True, blank=True) restaurant_address = models.CharField(max_length=1024, null=True) address = models.CharField(max_length=1024) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default=STATUS_NEW) created_at = models.DateTimeField(auto_now=True) delivered_at = models.DateTimeField(null=True, blank=True) courier = models.OneToOneField('Courier', on_delete=models.SET_NULL, null=True, blank=True) class CartMeal(models.Model): """Cart Meal""" user = models.ForeignKey('Customer', on_delete=models.CASCADE) cart = models.ForeignKey('Cart', verbose_name='Cart', on_delete=models.CASCADE, related_name='related_meals') meal = models.ForeignKey(Meal, verbose_name='Meal', on_delete=models.CASCADE) qty = models.IntegerField(default=1) final_price = models.DecimalField(max_digits=9, decimal_places=2) class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price … -
How to create the login and signup urls/views with django rest framework + firebase auth
I was trying to configure django rest framework with firebase auth. I had a look into a few tutorials and firebase doc. So far what I did is, pip install firebase-admin Create Auth class (copied): class FirebaseAuthentication(authentication.BaseAuthentication): def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: raise APIException("No auth token provided") id_token = auth_header.split(" ").pop() decoded_token = None try: decoded_token = auth.verify_id_token(id_token) except Exception: raise APIException("Invalid auth token") pass if not id_token or not decoded_token: return None try: uid = decoded_token.get("uid") except Exception: raise APIException() user, created = User.objects.get_or_create(username=uid) user.profile.last_activity = timezone.localtime() return user downloaded the config file (Generate new private key) from firebase and add that in settings, cred = credentials.Certificate(os.path.join(BASE_DIR, "firebase_config.json")) firebase_admin.initialize_app(cred) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'myauth.authentication.FirebaseAuthentication', ] } I am just a bit lost after that. Lets say, I got the uid in an android application. What would be the url or views to login/signup users? Thanks in advance. -
how to screen share using python vidstream onto a django html page?
I am trying to get the python window to show on the django html page but im not sure how to as im new to django. I followed this video "https://www.youtube.com/watch?v=8xy4JKvqsV4" to set up the python script for screen sharing Im running the receiver.py on the linux machine and the sender.py on the windows virtual machine.. receiver.py from vidstream import StreamingServer import threading receiver = StreamingServer('ipaddr', 8080) t = threading.Thread(target=receiver.start_server) t.start() while input("") != 'STOP': continue receiver.stop_server() sender.py from vidstream import ScreenShareClient import threading sender = ScreenShareClient('ipaddr', 8080) t = threading.Thread(target=sender.start_stream) t.start() while input("") != 'STOP': continue sender.stop_stream() -
Tockenizing any model instance in django (DRF)
So i am working with Django and django-rest-knox for token based authentication. It works fine but what i want now is to tokenize any other model instance instead of a user istance. Normal way; from knox.models import AuthToken AuthToken.objects.create(user=myuser) What i tried; AuthToken.objects.create(some_other_model_instace) Which gives an error; AuthToken.user" must be a "User" instance Is there any way to do so? -
Django Makemigrations fails on new autoscaling instances (shows no new changes)
We have a django backend hosted on Autoscaling ec2 instances, and during the deployments it has found that makemigrations and migrate fails (with new models added) when the new ec2 replaces in auto scaling group, as the migrations were done from the old instances, it shows no new migrations on the latest ec2. What could be the efficient solution for this - To have a separate server only for database migrations To push the migrations file directly on git/bitbucket with code so that during deployments new changes are reflected. Is there any other good solutions for this in general? -
How to view contents of one model to another model?
I am doing an Inventory App that let the user add items in the inventory and once added, they can view it in the view page of the app. they can only see it in view only mode. class Inventory(models.Model): last_modified_by = models.ForeignKey(User, on_delete=models.PROTECT) last_modified = models.DateTimeField(auto_now=True) I want to access specific items inside the Inventory Class to another model. for example I want to use last_modified_by inside for instance a Testclass. and last_modifiedin let say anotherTest class. I want to seperate the items in Inventory class in tabs, for example i have a tab inside the Test class and have all the items in it. How can i do this? -
Changing primary key in Django caused constraint does not exist error
I have Django project with DigestIssue model among others and there were Django auto created primary key field id and my field number. I wanted to get rid of duplication and set number as PK because number is unique and with same values as id. But I have foreign keys referencing this model. I doubt that they will migrate automatically after such operation. I tried, hoping for such automigration and got constraint "idx_16528_sqlite_autoindex_gatherer_digestissue_1" of relation "gatherer_digestissue" does not exist error ("sqlite" in constraint name is historical thing, I switched to PostgreSQL a time go). I tried more complicated way, following https://blog.hexack.fr/en/change-the-primary-key-of-a-django-model.html but got same error on PK switching step. So the question is - how to replace in Django old primary key with new one with same values and referenced by other models? -
CSRF follies when trying to log in to Django with Python requests/sessions
I'm trying to log in to Django using Python requests. There are old questions about this, but none of them are answered due to inadequate details. There are two CSRF tokens involved in this. One is the cookie, and the other is part of the login form. I've verified that Chrome returns the cookie token in the cookies and the form token in the body, and my url encoded body matches the format of one my browser passes back. And yet I still get "Forbidden (CSRF token missing or incorrect.)" as my response. Can any one suggest what I might be doing wrong? My Python looks like this: def login(url, username, password): session = requests.Session() response = session.get(f"{url}/accounts/login/") print(f"First headers: {response.headers}") header_csrftoken = session.cookies['csrftoken'] print(f"Header csrftoken: {header_csrftoken}") soup = BeautifulSoup(response.text, "html.parser") form = soup.find("form", {"id":"login-form"}) found = form.find("input", {"name":"csrfmiddlewaretoken"}) form_csrftoken = found['value'] print(f"csrftoken2: {form_csrftoken}") data = {'csrfmiddlewaretoken': form_csrftoken, 'username': username, 'password': password, 'next': '/'} response2 = session.post(f"{url}/accounts/login/", data=data, headers={'content-type': 'x-www-form-urlencoded'}) print(f"outgoing: {response2.request.body}") print(f"Headers: {response2.request.headers}") First headers: {'Date': 'Mon, 20 Sep 2021 03:37:17 GMT', 'Server': 'WSGIServer/0.2 CPython/3.8.12', 'Content-Type': 'text/html; charset=utf-8', 'Expires': 'Mon, 20 Sep 2021 03:37:17 GMT', 'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate, private', 'Vary': 'Cookie, Origin', 'X-Frame-Options': 'DENY', 'Content-Length': '20609', 'X-Content-Type-Options': … -
Can anyone help me with this issue - Django View (Passing of keys)
I have the following views: def device_port(request): devices = Device.objects.all() if request.method == "POST": selected=request.POST.get('device') devices = Device.objects.get(pk=selected) tablename = 'dev_interface_'+selected print("tablename: " +tablename) cursor=connection.cursor() cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2") righttable = cursor.fetchall() return redirect('/device/port/selected',{'devices':devices, 'selected': selected, 'righttable':righttable} ) return render(request, 'interface/device_port.html',{'devices':devices}) def device_port_selected(request, pk): if request.method == "POST": job = JobForm(request.POST) device = devices.hostname print(devices) #job.associateddevice = devices.hostname try: selection=request.POST.get('portrange') except: selection = "" messages.warning(request, "Please select the ports") print(selection) #job.associatedinterface = selection return render(request, 'interface/device/port/selected/'+device+'.html',{'devices':devices, 'righttable':righttable} ) return render(request, 'interface/device_port_selected.html',{'devices':devices, 'selected': selected, 'righttable':righttable} ) urls.py urlpatterns = [ path('', views.home, name='interface-home'), path('device/', DeviceListView.as_view(), name='interface-device'), path('device_edit/<int:pk>/', views.device_edit, name='device-edit'), path('device_delete/<int:pk>/', views.device_delete, name = 'device-delete'), path('device_add/', views.device_add, name='device-add'), path('device/port/', views.device_port, name='device-port'), path('device/port/selected/', views.device_port_selected, name='device-port-selected'), path('device/routeport/', views.device_routeport, name='device-routeport'), path('interface/', views.interface_list, name='interface-list') ] device_port.html <form method="POST"> <div class="form-row align-items-center"> <div class="col-md-5 my-1"> {% csrf_token %} <label for="Hostname">Hostname</label> <div class="input-group"> <select id = "list" class="custom-select mr-sm-2" onchange="getSelectValue();"> <option selected>Select</option> {% for device in devices %} <option value={{device.id}}>{{device.hostname}}</option> {%endfor%} </select> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit">Go</button> </div> </div> </div> </div> <input type ="text" name="device" id= "txtvalues" style="display:none"> </form> So there are 2 page I am dealing with over here. (/device/port and /device/port/selected). In this first page /device/port, user is required to pick a … -
Object creation assigns proxy class based on base model field(s)
I'm hoping to be able to create an object using a base model but have that object actually be created as a proxy class depending on the object's field(s). So for example, for the following models: class Animal(models.Model): species = models.CharField() class Cat(Animal): class Meta: proxy = True class Dog(Animal): class Meta: proxy = True How can I set it up so that cat = Animal.objects.create(species="cat") dog = Animal.objects.create(species="dog") Animal.objects.all() # Returns queryset of [cat, dog] Cat.objects.all() # Returns queryset of [cat] Dog.objects.all() # Returns queryset of [dog] -
Story object doesn't expire when User post a story feed
How do i set time for a story to expire at a certain time when users post a story, I been working on this project where i want users to be able to post a story feed for a period of time then it get deleted. Here is my story model. actually i don't really understand the way to make the post story of users to expired at a certain time like after 48 hours the post should be deleted from the story feed. class StoryManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( expire__lt=Now() ) class Story(models.Model): title = models.CharField(max_length=250) story = models.FileField(upload_to="stories",blank=True,null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) images = models.ImageField(upload_to="ImageStorie", blank=True,null=True) created = models.DateTimeField(auto_now_add=True) expire = models.DateTimeField(db_index=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="like") image_thumbnail = ImageSpecField(source='images', processors=[ResizeToFill(500, 300)], format="JPEG", options={'quality':100}) objects = StoryManager() This my view for the story model, but the story doesn't delete after 48 hours when its been post? can someone kindly help me with this! def storie(request): context = {} videos = Story.objects.filter(expire__lt=Now()).delete() context['video'] = videos return render(request,'feed/feed.html', context) -
convert MYSQL four-table join query to Django ORM query
I have a web app, backend using Django. I want to convert a MYSQL four-table join query to the corresponding Django ORM query. The four-table join query is: 'SELECT distinct t.id, t.title as Textbook, GROUP_CONCAT(concat(ci.discipline_code, ci.code, " (" , ci.type , ")") SEPARATOR ', ') as CourseCode FROM TMS_UAT.bms_material m, TMS_UAT.bms_title t, TMS_UAT.bms_course c,TMS_UAT.bms_courseinfo ci where t.id = m.book_id and c.id = m.course_id and ci.id = c.id and isbn != "NA" GROUP BY t.id;' I want to convert it to Django ORM query and use with other filter in view.py: @csrf_exempt def Browse_and_adopt(request): Title_list = Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print")).select_related('publisher') //the four-table join query should be added to this , so the Title_list both have publisher and the column selected by the four-table join query -
Is there a way to seperate the description for the first image and the second image using django?
so for my website is there is 2 part to uploading an images, one is to upload images for the box and the other is to upload an images of the equipment but when it is uploaded the first image description is together with the second image description. Example shown below. Picture of what happens when it is uploaded (not I wanted) picture of what I wanted in my database. views.py @login_required() def ReceptionUnserviceable(request): descriptionbox = Photo.objects.all() if request.method == 'POST': data = request.POST images = request.FILES.getlist('images') for image in images: photo = Photo.objects.create( descriptionbox=data['descriptionbox'], image=image, serialno=data['serialno'], partno=data['partno'], reception=data['reception'], customername=data['customername'], descriptionequipment=data['descriptionequipment'], ) return redirect('success') context = {} return render(request, 'ReceptionUnserviceable.html', context) models.py class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' image = models.ImageField(null=False, blank=False) descriptionbox = models.TextField() serialno = models.TextField() partno = models.TextField() reception = models.TextField() customername = models.TextField() descriptionequipment = models.TextField() def __str__(self): return self.descriptionbox Receptionunservicable.html <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} <div> <label>Description Of The Box</label> <input required name="descriptionbox" type="text" placeholder="Enter a description" style="width:300px" class="form-control"> </div> <br> <div> <label>Upload Box Photo</label> <input required name="images" type="file" multiple class="form-control-file"> </div> <br> <div> <label>Part Number</label> <input required name="partno" type="text" placeholder="Enter part number" style="width:300px" class="form-control"> </div> <br> <div> <label>Serial … -
Why is my upload directory relative to the project directory but Django is trying to get it from an app related path?
I am building a Dev-blog to store and refer to project I've coded for my portfolio, and I've been trying to add a media upload capability to my post text boxes. I started off by using a standard RichTextField, which had a built-in function to add Images through URL(No uploading). It worked fine, but I wanted the ability to upload photos from my machine. The blog is fully operational (on a local server for development), so all irrelevant code was disregarded. The only problem is with setting the paths to my image files. models.py from django.db import models from django.utils import timezone from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title= models.CharField(max_length=40) text = RichTextUploadingField() create_date = models.DateTimeField(default=timezone.now()) publication_date = models.DateTimeField(blank=True,null=True) def publish(self): self.publication_date=timezone.now() self.save() def approve_comment(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk':self.pk}) def ckeditor_upload(self): return reverse('post_detail', kwargs={'pk':self.pk}) urls.py from django.contrib import admin from django.urls import path,include,re_path from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), path('accounts/login/',views.LoginView.as_view(template_name='registration/login.html'),name='login'), path('accounts/logout/',views.LogoutView.as_view(),name='logout',kwargs={'next_page':'/'}), #{'next_page':'/'} makes it go back to homepage re_path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] **settings.py** <pre> INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', 'blog' ] # # # CKEDITOR_UPLOAD_PATH = 'media/uploads' The file … -
Django manytomany field automatically populates with all objects of related Model
I just added two manytomany fields to a django model; however, when I create a new instance of the model with the manytomany fields, the fields automatically contain all instances of the models they are related to. Here is the model: class Thread(models.Model): title = models.CharField(max_length=250, unique=True) owner = models.ForeignKey(AuthorUser, null=True, on_delete=models.SET_NULL, related_name='+') articles = models.ManyToManyField(Article, null=True) authors = models.ManyToManyField(AuthorUser, null=True) date_created = models.DateTimeField(default=timezone.now) And after creating a new instance of a Thread, it automatically contains all articles and authors currently in the database. Is there a way to fix this so that it starts with nothing in it and I can add authors and articles? -
Configure logger Django
I have the following code: logging.config.dictConfig( { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} - {message}', 'style': '{', }, 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'simple' } }, 'loggers': { 'django': { 'handlers': ['mail_admins'], 'level': 'INFO', 'propagate': True, }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, }) The problem basically exists only at the "logger". Whenever i set any of the handlers at the root key it always works, but it never reaches any of the config loggers. Any guesses? -
Python Sockets: Socket not closing when connected = False
When the disconnect message is received from my client(A django site sending the data), my socket isn't closing and this is preventing the rest of the code in my python file from running. If anybody knows what is causing this, help would be great. My Code: HEADER = 64 PORT = 6060 SERVER = '0.0.0.0' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" my_queue = queue.Queue() print(SERVER) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: connected = False else: my_queue.put(msg) print(f"[{ADDR}] {msg}") conn.send("MSG Received".encode(FORMAT)) conn.close() def start(): server.listen() print(f"[LISTENING] Server Is Listening On {SERVER}") while True: conn, addr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}") print("[Starting] Server") start() msg = my_queue.get() print(msg) -
Django MySQL Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535
I am currently migrating my tables to a new MySQL database from SQLite. There were no issues when I migrate to SQLite but when I try to migrate on to MySQL, I get the error above. I think it was due to my textfields taking up much of the space so I added a max_length=500 attribute to all of them but the error persists. This is the error: Is there a way to resize the textfield, or resize the maximum row size? Thanks in advance.