Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
MultiValueDictKeyError hen adding lines with inlineformset
I am trying to add more lines on the inline formset factory using the same methodology that I used before on a formset factory but is getting an error: MultiValueDictKeyError form-TOTAL_FORMS' models.py: class ttransactions(models.Model): transaction_type = models.CharField(max_length=10, choices=tx_choices) description = models.CharField(max_length=50, null=False, blank=False, default='Description') transaction_date = models.DateField(default=datetime.today, db_index=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT, db_index=True) def __str__(self): return self.description class ttransaction_lines(models.Model): transaction = models.ForeignKey(ttransactions, on_delete=models.PROTECT, db_index=True) sequence = models.IntegerField() transaction_type = models.CharField(max_length=6, choices=debit_credit) ledger_account = models.ForeignKey(tledger_account, on_delete=models.PROTECT, db_index=True) amount = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) vat_amount = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) vat_code = models.ForeignKey(tvat, on_delete=models.PROTECT, blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) posted = models.BooleanField(default=True) forms.py: class TransactionsForm(forms.ModelForm): transaction_date = forms.DateField(widget=forms.SelectDateWidget(years=year_range), initial=datetime.today) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(TransactionsForm, self).__init__(*args, **kwargs) class Meta: model = ttransactions fields = ['description', 'transaction_date'] class TransactionLinesForm(forms.ModelForm): class Meta: model = ttransaction_lines fields = ['transaction_type', 'ledger_account', 'amount'] class BaseTransactionLinesFormSet(BaseModelFormSet): def clean(self): super(BaseTransactionLinesFormSet, self).clean() # Check errors dictionary first, if there are any error, no point in validating further if any(self.errors): return balance = 0 for form in self.forms: if form.cleaned_data['DELETE'] == True or form.cleaned_data['DELETE'] == '': continue if form.cleaned_data['transaction_type']=='Debit': balance = balance + form.cleaned_data['amount'] else: balance = balance - form.cleaned_data['amount'] if balance != 0: message = 'Transactions not balanced (excluding … -
MySQL root user not able to create new database and perform other operations
I created a user named 'root', by setting a password for it by using: create user 'root'@'localhost' identified by 'some_password'; It successfully created a user and I assigned all the privileges to it against a particular database that I created, and was able to connect successfully to that database. But when I logged in using: mysql -u root -p with the password I set in first step and tried performing operations like Create New Database, Select user from mysql.user, and all other operations not related to that particular database against which the permissions are assigned , it is throwing mysql> SELECT user,authentication_string,plugin,host FROM mysql.user; ERROR 1142 (42000): SELECT command denied to user 'root'@'localhost' for table 'user' mysql> mysql> grant usage on *.* to 'root'@'localhost'; ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) mysql> GRANT ALL PRIVILEGES ON * . * TO 'root'@'localhost'; ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) mysql> SHOW GRANTS FOR 'root'@'localhost'; +-------------------------------------------------------------+ | Grants for root@localhost | +-------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'root'@'localhost' | | GRANT ALL PRIVILEGES ON `navi`.`navi` TO 'root'@'localhost' | +-------------------------------------------------------------+ 2 rows in set (0.00 sec) mysql> create user 'django'@'localhost' identified by 'django-user-password'; ERROR … -
Getting profile picture of blogposter in Django
When I display a blog post in HTML using a for loop {% for post in posts %} <div class="blogpost"> <h3><strong>{{post.title}}</strong></h3> <img class="thumbnail" src="{{author.imageURL}}"> <h7>{{post.date}} - {{post.author}}</h7> <br> <hr> <br> {{post.context|linebreaks}}<br><br> </div> <br> {% endfor %} it works perfectly fine, except the authors profile picture does NOT get displayed. I get the posts by getting all posts in my views.py from my models.py. The thing is that the profile picture of the user posting the blog isn't stored in the "post" model in the database. It is stored in the "Customers". Everybody should be able to read and post blogs. The admin (me) can later delete unwanted posts. I have tried making a for loop using an array key:value in JavaScript. That is not very secure, because everybody just gets all users and all profilepictures through the whole database. That might not be a good idea. This is my models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) about = models.CharField(max_length=100, null=True) image = models.ImageField(null=True, blank=True) @property def imageURL(self): try: url = self.image.url except: url = 'placeholder.png' return url def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, null=True) context … -
Django Profile model not showing first_name and last_name fields in sign up form
I created a Profile model with Django. The profile inherits from a CustomUser class which I wrote by inheriting AbstractBaseUser. However, when I go to the sign up page, even though first_name and last_name are required in the Custom User class, it doesn't show. It only shows the fields of the profile model, and email and password. I am using Django all auth. How do I make the required fields of the custom user (and other fields I want e.g middle_name) and the fields of the profile all show up in the same form, and still save both the custom user model, and the profile model in the database all at the same time? models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) USER_TYPE_CHOICES = ( (1, 'student'), (2, 'department'), (3, 'admin'), ) first_name = models.CharField(max_length=70, blank=False, default="") middle_name = models.CharField(max_length=70, blank=False, default="") last_name = models.CharField(max_length=70, blank=False, default="") is_active = models.BooleanField(default=True) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) is_staff = models.BooleanField(default=False) # a admin user; non super-user is_superuser = models.BooleanField(default=False) # a superuser last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] # Email & Password are required by default. objects = UserManager() … -
I have created a system which generates the image for user, and now i want to upload that on S3 and GCP in backgroud using Django
How can I achieve this, suggest any python library if you know that? -
django update portion of a template dynamically post a model save without re rendering
I have a side bar in my template with three event columns (All, Active, Inactive). The activity of the items in the side bar is controlled in backend. I want to dynamically update the list of events shown under (Active, Inactive), when ever their status changes and saved into the database. I can do this by constantly making an Ajax Request and update the template based on the response from view. But I was wondering if django signals can be used and post_save trigger and update the items on the template. Please let me know if u need more details. Code snippets: <!-- sidebar --> <div class="container"> <div class="sidebar"> <div class="side-filter-header"> <a class="selected">All Events</a> <a class="" >Active Events</a> <a class="" >Inactive Events</a> </div> <div class="side-filter-list"> <a href="#" class="list-group-item active-event"> <ul> <li>Event 1</li> </ul> </a> <a href="#" class="list-group-item inactive-event"> <ul> <li>Event 2 </li> </ul> </a> <a href="#" class="list-group-item inactive-event"> <ul> <li>Event 3</li> </ul> </a> </div> </div> </div> Django models.py class EventStatus(Enum): ACTIVE = "ACTIVE" INACTIVE = "INACTIVE" class Event(models.model): eventNo = models.IntegerField() eventStatus = models.CharField(max_length=255, default=EventStatus.INACTIVE, choices=[(tag,tag.value) for tag in EventStatus]) Django views.py def update_sidebar(): event = Event.objects.filter().last() # example # some condition event.eventStatus = "ACTIVE" event.save() # I want to … -
Adding addition field in Django rest framework modelserializer (write_only && read_write) in mixin
I want to create a mixin for additional fields in Modelserializer. Please refer the code below class AdditionalFieldsMixin(object): additional_fields = dict() def __init__(self, *args, **kwargs): super(AdditionalFieldsMixin, self).__init__(*args, **kwargs) for field_name, field_instance in self.additional_fields.items(): self.fields[field_name] = field_instance print(self.fields) def additional_field_before_create(self, additional_field_data): pass def additional_field_after_create(self, additional_field_data, instance): pass def additional_field_before_update(self, additional_field_data): pass def additional_field_after_update(self, additional_field_data, instance): pass def create(self, validated_data): additional_field_data = {} for additional_field in self.additional_fields.keys(): additional_field_data[additional_field] = validated_data.pop(additional_field, None) self.additional_field_before_create(additional_field_data) instance = super(AdditionalFieldsMixin, self).create(validated_data) self.additional_field_after_create(additional_field_data, instance) return instance def update(self, instance, validated_data): additional_field_data = {} for additional_field in self.additional_fields.keys(): additional_field_data[additional_field] = validated_data.pop(additional_field, None) self.additional_field_before_update(additional_field_data) instance = super(AdditionalFieldsMixin, self).update(instance, validated_data) self.additional_field_after_update(additional_field_data, instance) return instance in main class i decleared additional_fields = dict( reference=CharField(write_only=True, allow_blank=True, allow_null=True, default=None), ) but when retrieving the data in list mode the it gives me an error AssertionError: It is redundant to specify `source='reference'` on field 'CharField' in serializer 'MySerializer', because it is the same as the field name. Remove the `source` keyword argument. why this is happening ? also i noted that after starting runserver first time it doesn't give that error but if I query again it gives error second time and so on. and another general question what is the proper way to add … -
How do i create working search bar on ListView
I search in youtube and google for creating a working search bar on ListView but no one use on class allPostList(ListView): could you explain to me how to make it? here is my code table.html {% block container_content %} <form class="d-none d-sm-inline-block mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search justify-content-end"> <div class="input-group"><input class="bg-light form-control border-0 small" type="text" name="q" placeholder="Search for ..."> <div class="input-group-append"><button class="btn btn-primary py-0" type="button"><i class="fas fa-search"></i></button></div> </div> </form> {% endblock %} on the table.html i didnt show all the code because it is to much and messy but that is the form html code and its created on html not in forms.py my views.py class AdminShowAllPostList(ListView): model = Post template_name = 'admini/table.html' ordering = ['category'] paginate_by = 10 a screenshoot on table.html models.py if needed class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) page_link = models.SlugField(max_length=255, unique=True) body = RichTextField(blank=True, null=True, config_name='special', external_plugin_resources=[ ('youtube', '/static/ckeditor_plugins/youtube/youtube/', 'plugin.js'), ] ) category = models.ForeignKey(Category, default="", on_delete=models.CASCADE) # parent_check = models.CharField(max_length=255) meta_description = models.TextField(null=False, blank=False) meta_keyword = models.TextField(blank=False, null=False) i really hope it if the search bar can use complex Q lookup thanks -
How to subtract dates
Hey thanks for checking the question First, see my code class ConfirmationKey(models.Model): key = models.CharField(max_length=20,blank=True) username = models.CharField(max_length=100) email = models.EmailField() confirmation_key = models.CharField(max_length=10,null=True,blank=True) key_generated_at = models.DateTimeField(blank=True,null=True) key_valid_till = models.DateTimeField(blank=True,null=True) def save(self,*args,**kwargs): if self.key is None or len(self.key)== 0 : self.key = binascii.hexlify(os.urandom(20)).decode() self.confirmation_key = binascii.hexlify(os.urandom(8)).decode() self.key_generated_at = datetime.datetime.now() self.key_valid_till = datetime.datetime.now() + datetime.timedelta(minutes=10) super().save(*args,**kwargs) def is_valid(self): """Returns weather the key is still valid or not""" if datetime.datetime(self.key_valid_till) < datetime.datetime.now(): return True return False Now , in the sceond function, how can I subtract self.key_valid_till from current time — where key_valid_till is stringfied datetime.datetime.now() + datetime.timedelta(minutes=10) -
after deploy django project it showing this error AttributeError: 'str' object has no attribute 'tzinfo'
After move localhost to cpanel it shwoimg me that error AttributeError: 'str' object has no attribute 'tzinfo'. How can I fix it? please suggest to me. -
PHP (WordPress) Website deployment on Python environment
I'm a PHP developer. A new project came which requires me to develop a site on subdomain. That main domain is already covered by a Python website developed in Django CMS. Just wanted to know which kind of complications can come? For example, PHP uses My SQL and in PHP website the version should be same. Kindly, tell me how this can be managed. Thanks. -
Is there a way to link a local file stored on server to a django Model?
I want to create a django model that stores a Video and converts it to different resolutions but i don't know how can i link the converted videos back to the same model or save it another model with foriegn key to the base video. Its just like how youtube saves their videos