Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Manager
I have a Django Model where users can create objects and keep them private for a certain period of time. class MyModel(models.Model): creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) private_until = models.DateField(null=True, default=None, blank=True) objects = MyModelManager() In my ListView, I want for visitors only the "non-private" objects to appear and for authenticated users the "non-private" objects plus their own private objects. So my Manager looks like this: class MyModelManager(models.Manager): def include_his_private(self, user): if user.is_authenticated: include_his_private = super().get_queryset().filter(~Q(private_until__gt=datetime.date.today())) include_his_private |= super().get_queryset().filter(Q(creator=user)) return include_his_private else: return super().get_queryset().filter(~Q(private_until__gt=datetime.date.today())) def get_queryset(self): return super().get_queryset().filter(~Q(private_until__gt=datetime.date.today())) For my ListView this works great. But when I click on an object to get its DetailView, I get a 404 error right on "URL-Level". In my URLs I have: path('<slug:slug>', MyModelDetailView.as_view(), name='mymodel_detail'), ... and somehow, Django checks already in advance the whole slug against the per Manager allowed slugs, before I have the chance to pass the user in. What is the way to solve my problem? Any help is appreciated. Thanks in advance! -
Google Maps API close Info windows automatically
I'm working with the google maps API, I'm completely new to javascript and have no idea what I'm doing. Could you please tell me how to edit this code so that the infowindows close by themselves when I click on another marker? Right now when I click on a marker and the infowindow pops up it stays open when I click on a second marker. I've found similar questions on stack overflow but I'm completely lost in javascript and it's too complicated for me. Thanks! {% for party in parties %} var marker = new google.maps.Marker({ position:{lat:{{ party.latitude }},lng:{{ party.longitude }}}, map:map, }); var infoWindow = new google.maps.InfoWindow({ content:"{{ party.name }}" }); marker.infoWindow = infoWindow; marker.addListener('click', function(){ return this.infoWindow.open(map, this); }); {% endfor %} -
why does this error appear even if the folder is correct?
I did everything according to the tutorial, why this error? -
Django - Save a Excel file to a model's FileFild
I want to save a file in my excel_file field but i have this error : 'utf-8' codec can't decode byte 0x9d in position 15: invalid start byte class Product(models.Model): excel_file = models.FileField(upload_to='upload', blank=True) def save(self, *args, **kwargs): try : myFile = open('excel_file.xlsx', 'r') name = "new_test.xlsx" self.excel_file.save(name, File(myFile)) super().save(*args, **kwargs) except Exception as e: print(e) -
folium.Marker does not does decode
I have a folium map called imap. I have created a string object called test_mark which is a string 'Hà Nội' test_mark = 'Hà Nội' folium.Marker(location=(43.30,-8.30),popup= test_mark, icon= folium.Icon()).add_to(imap) When I check the marker on the map, what I get is 'hà ná»i'. I guess it might be some kind of encoding problem, but I can not figure out how to solve it. Thanks in advance -
Django: AttributeError at /tickets/post/1/like/ 'str' object has no attribute 'fields'
I have a problem when I am trying to 'upvote' a ticket in my app. There is a button on my app that adds one to the upvotes field, but as soon as I press on the button I get the error. I have refreshed all of my migrations as I had a problem with an old field that was being picked up but I may need to run something else? Here is the traceback: Environment: Request Method: GET Request URL: http://3231d88fef004534aa79ab40a77c1898.vfs.cloud9.us-east-2.amazonaws.com/tickets/post/1/like/ Django Version: 1.11 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'accounts', 'tickets', 'checkout'] Installed 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Template error: In template /home/ubuntu/environment/issuetracker/templates/base.html, error at line 0 'str' object has no attribute 'fields' 1 : {% load staticfiles %} 2 : 3 : <html> 4 : 5 : <head> 6 : <meta charset="UTF-8"> 7 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 : <meta http-equiv="X-UA-Compatible" content="ie=edge"> 9 : <title>IssueTracker{% block page_title %}{% endblock %}</title> 10 : <link rel="icon" href="media/img/bug.jpg"> Traceback: File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/environment/issuetracker/tickets/views.py" in … -
filter home page(blog posts) by category on button press
I currently have a page which displays all the blog posts, which updates when a new post has been added. Each blog has a department and a category I am looking to have 2 buttons ontop of the page which have 'department' and 'category', when the user loads the home page he/she will see all blog posts but when the user wants to see the category they simple need to press the CATEGORY button which will dynamically update the blog posts to show all the blog posts that match the category. I have say 5 categories: programming, onboarding, coding, help. I have spent hours and creating new issues trying to filter the current blog posts to show a button which filters the posts by 'programming'. end goal: 2 buttons above posts department = filter the current posts by the department that the user is a part of (department is assigned to the user when they update their profile) category = filter the posts by a choice of categories (programming, coding etc) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Category (models.Model): named = models.CharField(max_length=100) def __str__(self): return self.named def get_absolute_url(self): … -
Folder for static images can't be accessed/found
I tried following this or this or this but nothing works for me - I have a directory called media which has uploaded files in it - but I cannot access it with http://127.0.0.1:8000/media/ - Page not found (404). My settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'PROJECT/static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL = "/media/" and my urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView, from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('home/', RedirectView.as_view(url='/')), path('admin/', admin.site.urls), path('', include('appname.urls')), path('', include('django.contrib.auth.urls')), path(r'^login', auth_views.LoginView.as_view(template_name='registration/login.html')), ] if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) from django.conf import settings from django.conf.urls.static import static if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Bonus question because I could not try it until now: How would I access an image with filename.jpg in /media/ in a template? -
React favicon not displayed after run build
I changed the favicon.ico to image.svg in my react app. When running development server it is showing the icon fine, but when I run build, the favicon is not there. My stack is Django DRF, React and Nginx. I tried to bypass this issue by setting favicon in the nginx config and changing permissions on the image to 755. But If I do that I receive 404 on the file. nginx config file: location = /favicon.ico { alias /home/user/pyapps/project/image.svg; } Do I have to change owner of the file or something similar to that? -
How do I cache form data in Django?
I'm creating a single page application in Django. It mainly consists of multiple, small forms that are filled in and validated independent from each other. Every form looks similar to this: With a final button press at the end though, the input of all those forms should be processed together. How can I save/cache all data of the submitted forms to process them with a final form submit at the end? I tried creating only one big form, but then I can't validate each field one after the other, when the user clicks the 'Next' button. -
Django not getting id from the url parameter
i have these serializer on Django class CarManagerSerializer(serializers.ModelSerializer): class Meta: model = Manager fields = '__all__' and this view class class CarManagerViewSet(APIView): allowed_methods = ('GET',) def get(self, request, manager_id = None): if manager_id is None: managers = Manager.objects.all().order_by('-name') serializer = CarManagerSerializer(managers , many=True) serializer_data = serializer.data return Response(serializer_data, status=status.HTTP_200_OK) else: managers = Manager.objects.get(id = manager_id).select_related('cars') serializer = CarManagerSerializer(managers , many=True) serializer_data = serializer.data return Response(serializer_data, status=status.HTTP_200_OK) im trying to get the manager by its manager id http://127.0.0.1:8000/carmanagers/3 but the manager_id wont get passed to the view, i keep getting 'None' where did i miss ? below is the url urlpatterns = [ url( r'carmanagers/(?P<manager_id>[0-9]+)/$', CarManagerViewSet.as_view(), name='car-managers' ), url( r'carmanagers', CarManagerViewSet.as_view(), name='car-managers' ), ] -
Dynamic form in Django
I am trying to make a dynamic form in Django that asks according to the user's answers. For example, in this google form when you select option 1, it sends you to the section of option 1 with their respective questions. Google Form Example -
Import error while running specific test case
Before I say something, let me show the current project hierarchy. The app name is api. ── api │ ├── │ ├── admin.py │ ├── apps.py │ ├── init.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_wallet_customer_id.py │ │ ├── 0003_auto_20201201_1103.py │ │ ├── 0004_auto_20201203_0703.py │ │ ├── 0005_auto_20201207_1355.py │ │ ├── __init__.py │ │ │ ├── models.py │ ├── permissions.py │ ├── serializers.py │ ├── stellar.py │ ├── te_s_ts_bk.py │ ├── te_sts_2.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── debug.log ├── manage.py └── myapp ├── __init__.py ├── asgi.py ├── settings-local.py ├── settings-remote.py ├── settings.py ├── urls.py └── wsgi.py As it was suggested here, I even removed __init__.py file from the api app folder, yet having the issue. My TestCase Class look like below: class CreateWalletTestCase(APITestCase): app_id = 0 app = None def test_create_wallet(self): response = self.client.post( '/wallets/', data={'app_id': self.app_id, 'customer_id': 'A-001'}, **{'HTTP_api_key': 'test-api', 'HTTP_api_secret': 'test-api-password'} ) data = json.loads(response.content) self.assertEqual(data['status'], 'OK When I run as python manage.py test api.CreateWalletTestCase.test_create_wallet or even python manage.py test CreateWalletTestCase.test_create_wallet, it generates the error: ImportError: Failed to import test module: CreateWalletTestCase Traceback (most recent call last): File "/usr/local/lib/python3.9/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module … -
Pillow issue : writing on the same image -> save image with random name for each model
I got a question. Is it possible to save an image with an other and unique name from one image. I got a default image, which is located into invitation/defaut.png. I'm using a form with only one field dedicated to nom I'd like to get save this image, with the writing of nom, with different name. for example: if name louis => defaut_randomletters.png if name mike => defaut_randomletters.png The issue I'm facing is that all the writing are save on the same image. class Invitation(models.Model): nom = models.CharField(max_length=200) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='invitation_user') image = models.ImageField(upload_to='invitation/', default='invitation/defaut.png') slug = models.SlugField(max_length=200, editable=False, unique=True) def save(self, *args, **kwargs): if not self.slug: self.slug = self.nom super(Invitation, self).save(*args, **kwargs) #img = Image.open(os.path.join(settings.BASE_DIR, 'media/invitation/defaut.png')) img = Image.open(self.image.path) draw = ImageDraw.Draw(img) path_to_media_popstick = os.path.join(settings.BASE_DIR, 'media/font/gillsans.ttf') path_to_media_emo = os.path.join(settings.BASE_DIR, 'media/font/Symbola.ttf') #fnt = ImageFont.truetype(path_to_media_emo, 50) fnt = ImageFont.truetype(path_to_media_emo, size=50, layout_engine=ImageFont.LAYOUT_RAQM) font = ImageFont.truetype(path_to_media_popstick, 200) draw.text((50, 200),self.nom,(255,255,255),font=font) img.save(self.image.path) super(Invitation, self).save(*args, **kwargs) -
Use the more descriptive name in Django choices
I am creating an eCommerce app and have come into a problem where I can't seem to make Django display the 2nd item in the tuple. For example, my models.py... class ProductItem(models.Model): OPTIONS = [ ("RED","Red"), ("DBL","Dark Blue"), ("LBL","Light Blue"), ("DGR","Dark Green"), ("LGR","Light Green"), ("PNK","Pink"), ("GRY","Gray"), ("BLK","Black"), ("BRO","Brown"), ("WHT","White"), ("MAR","Marroon"), ("ORG","Orange"), ("BEG","Beige"), ("GLD","Gold"), ("SLV","Silver"), ("MLT", "MultiColour") ] product = models.ForeignKey(Product, on_delete=models.CASCADE) colour = models.CharField(choices=OPTIONS, default="BLK", max_length=20) quantity_available = models.PositiveIntegerField() def __str__(self): return f"{self.product} -> ({self.colour})" And in my views.py... def product_detail(request, id): products = Product.objects.filter(id=id).first() context={ "product": products, "options": ProductItem.objects.filter(product=products) } return render(request, "store/product_detail.html", context) And finally in my template... <select id="style"> {% for option in options %} <option value="{{option.colour}}">{{option.colour]}}</option> {% endfor %} </select> In this case, let's assume that the Dark Blue Colour should appear. I want the value to be DBL as I have mentioned in the CHOICES and want the Dark Blue to be displayed for the user. But in this case, only DBL is shown, something that I don't want. Any idea on how to tackle this? Thanks! -
Why Django is not rendering some HTML files from Django app directory?
I am new to djando and building my first project app 'accounts' in django framework. The 'accounts' app has a templates\accounts folder where all the .html files are residing. The problem is, django is rendering all the .html files except reso.html located in my templates directory. While rendering reso.html, its throwing following error when http://127.0.0.1:8000/masterdata/ is typed in URL bar: OSError at /masterdata/ [Errno 22] Invalid argument: 'C:\\Users\\Parijat\\Desktop\\Theis project\\CRM\\accounts\\templates\\accounts\reso.html' Request Method: GET Request URL: http://127.0.0.1:8000/masterdata/ Django Version: 3.1.4 Exception Type: OSError Exception Value: [Errno 22] Invalid argument: 'C:\\Users\\Parijat\\Desktop\\Theis project\\CRM\\accounts\\templates\\accounts\reso.html' Exception Location: C:\Users\Parijat\Desktop\Theis project\env\lib\site-packages\django\template\loaders\filesystem.py, line 23, in get_contents Python Executable: C:\Users\Parijat\Desktop\Theis project\env\Scripts\python.exe Python Version: 3.9.0 Python Path: ['C:\\Users\\Parijat\\Desktop\\Theis project\\CRM', 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39', 'C:\\Users\\Parijat\\Desktop\\Theis project\\env', 'C:\\Users\\Parijat\\Desktop\\Theis project\\env\\lib\\site-packages'] I tried setting up the TEMPLATE variable in setting.py so that django can search templates from my directory but everytime its throwing the same error. For example I changed 'DIRS': [], to 'DIRS': [BASE_DIR / 'accounts'], Below is an image showing the location of my .html files:- Setting.py BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'ss3@*&2)-+e!3bxok+afpflc&j!e(6tz^z_+80a*yh)oos8@m!' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
How to get last message of your bot?
I'm newbie in programming and trying to write a Telegram Bot, just using the telegram documentation. From frameworks, I'm only using Django for structure and admin I want to build the roadmap of my bot, so trying to get the last message which my bot sends to the user. Can somebody help me how to do it. I read the documentation, but can't find nothing about it, only know how to get users message which he just wrote such as: r = request.read().decode('utf-8') r = json.loads(r) chat_id = r['message']['chat']['id'] message_text = r['message']['text'] -
I need to keep push the "Make public" button to make images readable(can see the image) in my django project website deployed on heroku
I'm currently doing my django project, and I deployed it at heroku. And for the static files and uploads, I made a bucket at aws s3. But from my website deployed at heroku, I couldn't see the image I've uploaded, like below. I figured out that I need to make my bucket publicly accessible, and to push the "Make Public" button, which is at the 'action' of the dashboard of s3 like the below, to make that readable(visible). But everytime I upload image file to my website, I need to push that "Make Public" button to make the image readable(visible). This is my settings.py STATIC_URL = "/staticfiles/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles")] AUTH_USER_MODEL = "users.User" MEDIA_ROOT = os.path.join(BASE_DIR, "uploads") MEDIA_URL = "/media/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") DEFAULT_FILE_STORAGE = "config.custom_storages.UploadStorage" STATICFILES_STORAGE = "config.custom_storages.StaticStorage" AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = "heroku-nbnb-clone-bucket" AWS_AUTO_CREATE_BUCKET = True AWS_BUCKET_ACL = "public-read" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/staticfiles" urls.py urlpatterns = [ path("", include("core.urls", namespace="core")), path("rooms/", include("rooms.urls", namespace="rooms")), path("users/", include("users.urls", namespace="users")), path(f"{admin_url}/", admin.site.urls), path("reservations/", include("reservations.urls", namespace="reservations")), path("reviews/", include("reviews.urls", namespace="reviews")), path("lists/", include("lists.urls", namespace="lists")), path("conversations/", include("conversations.urls", namespace="conversations")), url(r"^media/(?P<path>.*)$", serve, {"document_root": settings.MEDIA_ROOT}), url(r"^static/(?P<path>.*)$", serve, {"document_root": settings.STATIC_ROOT}), ] urlpatterns = urlpatterns + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) custom_storages.py from storages.backends.s3boto3 import … -
how to write a query to display all tickets assigned and escalated to a technician
Am working on an helpdesk management system. In this project each user or customer has a profile. which all tickets raised by that user displays on their dashboard when they login. Now the problem here is how to display all tickets assigned and escalated to a technician when they login in to their dashboard. here is part of my model.py class Grade(models.Model): grade_name = models.CharField(max_length=100) def __str__(self): return self.grade_name class Prority(models.Model): level_name = models.CharField(max_length=100) def __str__(self): return self.level_name class Region(models.Model): region_name = models.CharField(max_length=100) def __str__(self): return self.region_name class District(models.Model): district_name = models.CharField(max_length=100) region = models.OneToOneField(Region,blank=True,null=True, on_delete= models.CASCADE) def __str__(self): return self.district_name class Status(models.Model): status_name = models.CharField(max_length= 100) def __str__(self): return self.status_name class agent_Status(models.Model): astatus_name = models.CharField(max_length= 100) def __str__(self): return self.astatus_name class Category(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Profile(models.Model): user = models.OneToOneField(User,blank=True,null=True, on_delete= models.CASCADE) name = models.CharField(max_length=200,null=True) telephone = models.CharField(max_length=20) grade = models.OneToOneField(Grade,on_delete= models.CASCADE) region = models.OneToOneField(Region,blank=True,null=True, on_delete= models.CASCADE) district = models.OneToOneField(District,blank=True,null=True, on_delete= models.CASCADE) is_staff = models.BooleanField(default=False) is_agent = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_director = models.BooleanField(default=False) is_new = models.BooleanField(default=False) def __str__(self): return self.name class Ticket(models.Model): name = models.ForeignKey(Profile,on_delete= models.CASCADE) subject = models.CharField(max_length=200,null=True) description = models.CharField(max_length=200,null=True) region = models.CharField(max_length=200,null=True) district = models.CharField(max_length=200,null=True) category = models.ForeignKey(Category,on_delete= models.CASCADE) status = … -
Django Channels - Receiving Messages with Javascript Websocket
I have just started out with Django Channels and have worked through the tutorial on their website. I am trying to understand how to do something. In consumers.py I have managed to receive data from the client and send back messages to the JavaScript websocket. My question is, how would I differentiate the data sent back. For example in one case I am sending a message back to indicate that the user successfully sent their name. Then they can create a room and I am sending back a list of rooms. At the client front end, I want to be able to tell when it is a list of rooms or successfully added the name and respond accordingly. Here is an example of what I have: python code: #Send room list await self.channel_layer.group_send( self.room_group_name, { 'type': 'room_data', 'message': [r.name for r in rooms.rooms] } ) #Send to individual success message when their name has been added await self.send(text_data=json.dumps({'success':True})) #This is the function for the room data message async def room_data(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'rooms': {'message': message} })) Javascript: const chatSocket = new WebSocket( `ws://${window.location.host}/ws/risla/` ); chatSocket.onmessage = (e) => { const data … -
wrong E rro r display django
I am working on my Blog website and in the registration template i should insert username and email and password so i can register but if i have an error it should give me what is it BUT every error i have it goes to the bottom of the template not under the field i want. P.S.: i am using Django framework!! template.html: <h1>Register</h1> <form action="" method="post"> {% csrf_token %} <div class="form-floating mb-3"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com" name="username"> <label for="floatingInput">Username</label> </div> <div class="form-floating mb-3"> <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com" name="email"> <label for="floatingInput">Email</label> </div> <div class="form-floating"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password1"> <label for="floatingPassword">Password</label> </div> <div class="form-floating"> <input type="password" class="form-control mt-3" id="floatingPassword" placeholder="Password" name="password2"> <label for="floatingPassword">Re-Type Password</label> </div> {% if forms.errors %} {% for field in forms %} {% for error in field.errors %} <h5 style="color: red;">{{ error|escape }}</h5> {% endfor %} {% endfor %} {% for error in forms.non_field_errors %} <h5 style="color: red;">{{ error|escape }}</h5> {% endfor %} {% endif %} <br> <button type="submit">Register</button> </form> </div> if anything need to be added other then the template please tell me in the comment!! Thanks in advance!! <3 -
Django- IntegrityError at /tickets/new/ null value in column "payment_amount" violates not-null constraint
I am facing an Integrity Error in Django admin while trying to add data to the database. The traceback is referring to a field that I added some time ago and then removed. I have migrated the database and deleted all of the entries in the database but I am still getting the error. I have searched for payment_amount in my environment and I cannot find any lines with it mentioned. Could someone please help? The traceback is as follows: Environment: Request Method: POST Request URL: http://3231d88fef004534aa79ab40a77c1898.vfs.cloud9.us-east-2.amazonaws.com/tickets/new/ Django Version: 1.11 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'accounts', 'tickets', 'checkout'] Installed 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Traceback: File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 65. return self.cursor.execute(sql, params) The above exception (null value in column "payment_amount" violates not-null constraint DETAIL: Failing row contains (67, test, tsetes, 2020-12-28 11:59:48.049459+00, 2020-12-28 11:59:43+00, 0, , 0, , BUG, TO_DO, null). ) was the direct cause of the following exception: File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/environment/issuetracker/foo/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/ubuntu/environment/issuetracker/tickets/views.py" … -
CSS not being applied correctly and it looks wrong
I'm trying to apply this code as a css: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static '/css/main.css' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous"> <title>Email Scrapper</title> </head> <body> <div class="container"> <br/> <div class="row justify-content-center"> <div class="col-12 col-md-10 col-lg-8"> <form class="card card-sm" action="{% url 'scrap' %}" method="GET"> <div class="card-body row no-gutters align-items-center"> <div class="col-auto"> <i class="fas fa-search h4 text-body"></i> </div> <!--end of col--> <div class="col"> <input type="text" class="form-control form-control-lg form-control-borderless" placeholder="Search topics or keywords" name="q" id="InputSearch" value="{{ q.get }}" aria-describedby="searchHelp"> </div> <!--end of col--> <div class="col-auto"> <button class="btn btn-lg btn-success" type="search>Search</button> </div> <!--end of col--> </div> </form> </div> <!--end of col--> </div> </div> </body> </html> css: body{ background:#ddd; } .form-control-borderless { border: none; } .form-control-borderless:hover, .form-control-borderless:active, .form-control-borderless:focus { border: none; outline: none; box-shadow: none; } The problem is that when I run it, the following thing appears: [Image of the output][1] When it should be more like this: [This should be the output][2] Before it worked, but when I applied some code of my own it suddenly stopped working. This code is running in django and python. [1]: https://i.stack.imgur.com/SHXFe.png [2]: https://i.stack.imgur.com/4dKle.png -
Generate an excel file based on multiple django models and generate download Link
Say I Have a Models and I have a web page where users can click a download button, which on clicking, they get a .xlsx file in their downloads. The .xlsx file is modeled in a way such that I get the fields of the model in each column, and the details for each instance are filled row-wise. I want the data pulled fresh from the DB.sqlite3 file the link is clicked, and I do not want to save anything on the server. How do I do this? Thanks! -
Make PyPy in virtualenv use shared library from OS rather than its own copy (libsqlite3)
In a Python/Django based open source project I am working on we use Travis and GH Actions for CI. We support PyPy and hence run our CI tests for PyPy as well. Since a couple of months we were not able to run those PyPy tests successfully anymore, because we kept hitting this error: OSError: Cannot load library libgdal.so.20: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name, occuring if we would run Django's manage.py test command (traceback at end of post). Some GIS-related features in Django required the GDAL library, which in turns requrires the SQLite3 library. And it seems to requires sqlite3 to be compiled with column meta data enabled. This was reproducible locally only if the installed sqlite3 library would be compiled without SQLITE_ENABLE_COLUMN_METADATA. After searching all installed sqlite3 libraries on the CI servers, it became clear that PyPy has its own copy of libsqlite3.so.0 installed, which it clearly prefers over the OS installed version during runtime, even though ldd would refer to the OS library: $ ldd -d /usr/lib/libgdal.so | grep sqlite3 libsqlite3.so.0 => /usr/local/lib/libsqlite3.so.0 (0x00007f09d6124000) I suspect the reason PyPy uses a different library (its own copy) during runtime is its dynamic loader (referenced in the traceback) and where it …