Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mypy throws invalid syntax on method signature
A method called within the below method triggers mypy to lint with test_get_all_boards: test_get_all_boards invalid syntax mypy(error). The method in question returns a boolean. I just understand what is wrong with the syntax at test_get_all_boards:. Any ideas? @action(detail=False, methods=["post"]) def try_connection(self, request, *args, **kwargs): result = False cache = caches["instance_details"] if request.data: try: details = Jira(**request.data) if details: if cache[details.uuid]['valid_credentials']: result = True else test_get_all_boards(details): cache[details.uuid]['valid_credentials'] = True result = True except: pass return Response({"test_result": result}, status=status.HTTP_200_OK) -
Application error django blog app with heroku
I deployed a Django blog app to Heroku and the build was successful but on opening the app I got a page saying application error, it said to check the logs but I don't get the message. Here's the log 2021-04-27T15:41:49.301926+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=campusstory.herokuapp.com request_id=c5396159-b7e0-4ada-8764-54d40add0bc2 fwd="102.89.3.201" dyno= connect= service= status=503 bytes= protocol=https 2021-04-27T15:41:49.674072+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=campusstory.herokuapp.com request_id=22a9b86c-9b7a-4851-8ff1-7c0c8c733a44 fwd="102.89.2.205" dyno= connect= service= status=503 bytes= protocol=https 2021-04-27T15:47:31.201263+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=campusstory.herokuapp.com request_id=477c9fb1-4b53-4bb8-9fc2-1f4e66604ff0 fwd="102.89.2.205" dyno= connect= service= status=503 bytes= protocol=https 2021-04-27T15:47:31.619852+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=campusstory.herokuapp.com request_id=3ef7ae48-18cb-4979-8bce-ef80dc4e021f fwd="102.89.3.44" dyno= connect= service= status=503 bytes= protocol=https 2021-04-27T15:47:33.950102+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=campusstory.herokuapp.com request_id=4abaafe0-8bd6-4d0c-a7fb-c0524fc4ca00 fwd="102.89.3.201" dyno= connect= service= status=503 bytes= protocol=https 2021-04-27T15:47:34.389228+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=campusstory.herokuapp.com request_id=3b3953cf-8f47-4de9-ba88-4da2c4e14249 fwd="102.89.2.205" dyno= connect= service= status=503 bytes= protocol=https -
Is it possible to create a django superuser via management.call_command?
The issue I'm encountering is that "password" is not a valid flag option. management.call_command( 'createsuperuser', interactive = False, username = "user" password = "password" ) gives error: TypeError: Unknown option(s) for createsuperuser command: password Valid options are: ... -
I want to export a table's data into excel sheet in django i have done the exact thing and written the code for it but getting FieldError
enter image description herehere is my views.py this code is for exporting to excel sheet def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="candidates.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('candidates') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Full Name ', 'Email', 'Notice Period (in Days)', 'Current Location', 'Expected Location', 'Current CTC (Per Annum)', 'Expected CTC (Per Annum)', 'Upload CV', ' Gender'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = ApplyForm.objects.all().values_list('full_name', 'email', 'noticeperiod', 'preferredlocation', ' expectedlocation', 'currentctc', ' expectedctc', ' cv', 'gender' ) for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response this is the code for filling up the form and submitting to databasein views.py def applyform(request): data = ApplyForm.objects.all() print(data) if request.method == "POST": full_name = request.POST['full_name'] email = request.POST['email'] noticeperiod = request.POST['noticeperiod'] preferredlocation = request.POST['preferredlocation'] expectedlocation = request.POST['expectedlocation'] currentctc = request.POST['currentctc'] expectedctc= request.POST['expectedctc'] gender = request.POST['gender'] cv = request.FILES['cv'] ins = ApplyForm(full_name = full_name, email = email, noticeperiod = noticeperiod, preferredlocation = preferredlocation, expectedlocation= expectedlocation, currentctc =currentctc, expectedctc = expectedctc, gender = gender, cv = cv) ins.save() print("the data has … -
TemplateSyntaxError at /messages/inbox/ 'account_tags' is not a registered tag library. Must be one of:
I am using pinax_messages and pinax_templates. I am not able to go to the page : http://127.0.0.1:8000/messages/inbox/ I am getting a strange error and dont understand the problem. I am getting the error: TemplateSyntaxError at /messages/inbox/ 'account_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls bootstrap cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils i18n l10n log pinax_messages_tags static tz I am not able to find any help on google. -
Django: sorting querysets to have a specific order of objects
I've a model with two fields, say deprecated and new. When I'm listing the objects, I'd like the ones with new=True at the beginning, followed by the objects where deprecated=True and then the rest. I've seen a bunch of answers about ordering by multiple fields but that doesn't seem to work for me. This is how I'm doing the ordering now: class Meta: ordering = ['new', 'deprecated'] I've tried using multiple order_by on the queryset as well but that doesn't do the trick either. Right now I get a list with the new ones at the beginning butthe deprecated ones at the bottom. Is there a direct way to do what I want? This doesn't work for me as the order should be based on fields rather than specific ids. -
django check values if they are empty
All fields have values, however, the app is redirected to the first if condition('Fields are empty!'). If I remove the condition the form is submitted. What am I missing here? Any help is appreciated, thank you! def application(request): if request.method == 'POST': name = request.POST['name'] surname = request.POST['surname'] email = request.POST['email'] address = request.POST['address'] city = request.POST['city'] country = request.POST['country'] zipcode = request.POST['zipcode'] phone = request.POST['phone'] if(name,surname,email,address,city,country,zipcode,phone == ""): return HttpResponse("<h3 style = 'background:#000;color:red; display:flex;justify-content:center;align-items:center;width:100%;height:100%;font-family:lato;'>Fields are empty!!</h3>") else: application = Application(name = name, surname = surname, email = email, address = address, city = city, country = country, zipcode = zipcode, phone = phone) application.save() thename = name.capitalize() thesurname = surname.capitalize() ) messages.success(request, 'Your request has been submitted, a representative will get back to you soon') return render(request, 'application.html') -
How to list the titles of html pages with links on the home page in Django
Picture of my window I am sorry if this is a stupid question but I am new to Django. I am building a website and I have articles saved as template files. I want to display all of their titles with links directed to those templates but I want to automatically list them so if I add a new template to the folder, the home page will have the new link to that template. Is there a way to do that? So as I show in the picture... I have a folder for article sites, but I want to list their titles and the URLs on the home page. I know we can do it manually but I want to automatically list them, so every time we add one or remove an article, the home page list should get modified automatically. Thank you for your help. -
Why the platform create a new wallet?
enter code here @login_required def wallet_new(request): wallets = Wallet.objects.all() if request.method == "POST": form = WalletForm(request.POST) if form.is_valid(): new_wallet = form.save(commit=False) new_wallet.profile = request.user new_wallet.save() for wallet in wallets: if new_wallet.profile == wallet.profile: new_wallet.delete() return render(request, 'app/error.html') else: new_wallet.save() return render(request, 'app/response_wallet_executed.html') form = WalletForm() contex = {'form': form} return render(request, 'app/wallet_new.html', contex) I don't understand why the view create always a new wallet, please help me.The scope is to create a new UNIQUE wallet for user, and when a user that has a wallet, he would create a new wallet, the viewmust not allow it -
Editing form data in django
I am trying to edit a form data but instead of editing, it adds new data. I actually referred the codes online, but I couldn't figure out where I have got wrong. The following is the snippet of where I call the edit button <a class="btn btn-secondary" href="{% url 'ride:edit-ride' i.id %}">Edit</a></td> veiws.py def edit_ride(request, pk): obj = Ride.objects.get(id=pk) form = RideForm(instance=obj) if request.method == 'POST': form = RideForm(request.POST, instance=obj) if form.is_valid(): form.save() return redirect('ride_list.html') context = {'form': form} return render(request, 'offerride/create_ride.html', context) -
javascript onclick function not working in django template (problem most certainly is with the js code, i have verified the correctness of django)
what i am trying to do is create a like button just like Instagram's heart. The page must not reload when the like button is clicked, it must simply fill in with the specified color. This is how i am rendering the button in my page: <a href="#" onclick= "favPost('{% url 'events:post_unfavorite' post.id %}', {{ post.id }} );return false;" {% if post.id not in favorites %} style="display: none;" {% endif %} id="favorite_star_{{post.id}}"> <span class="fa-stack" style="vertical-align: middle;"> <i class="fa fa-star fa-stack-1x" style="color: yello;"></i> <i class="fa fa-star-o fa-stack-1x"></i> </span> </a> <!-- the second href --> <a href="#" onclick= "favPost('{% url 'events:post_favorite' post.id %}', {{ post.id }} );return false;" {% if post.id in favorites %} style="display: none;" {% endif %} id="unfavorite_star_{{post.id}}"> <span class="fa-stack" style="vertical-align: middle;"> <i class="fa fa-star fa-stack-1x" style="display: none; color: yello;"></i> <i class="fa fa-star-o fa-stack-1x"></i> </span> </a> here, events is the name of my django app, "post" is the relevant post on which i need to add the like and "favorites" is a list of favorite posts associated with any posts. Though i have double checked and i am almost certain that there are no issues with my python code. But i'll still provide the functions for reference. These are the … -
about django template url parameter without db
I am creating a bulletin board that communicates by DB <> API <> WEB method. Can django templates url parameter be used on 'Web' without db? I need to get two acquisitions, how should I use them? I've Googled and tried many things, but there was nothing I wanted to find. I must use the url tag. please help me. THANK YOU urls.py path('board/<int:pk>/comment/<int:id>/delete/', views.Commentapi_delete.as_view(), name="comment_delete"), template <form action="{% url 'comment_delete' ? ? %} method='POST'"> -
Django static files uploaded to folder in Amazon S3 that can't be found
I'm trying to set up Django so that all static files are uploaded to s3, but for whatever reason, it's not working. Here is the relevant section in settings.py: AWS_STORAGE_BUCKET_NAME = "bucket_name" AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_S3_FILE_OVERWRITE = False AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = ( f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com" ) AWS_S3_ENDPOINT_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}" AWS_LOCATION = "static" STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/{AWS_LOCATION}/" STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" Supposing that my bucket is called bucket_name, this is what will happen: In my bucket_name bucket, there will be a folder called "bucket_name" with a static folder inside which contains all of my files. On the server, none of the assets will load. This is because they are looking for the url https://bucket_name.s3.us-east-2.amazonaws.com/static whereas it's written in https://bucket_name.s3.us-east-2.amazonaws.com/bucket_name/static. How do I either get the django assets to use this new address, or change the address on aws so that it aligns with django? I've done some things to debug this. It seems that if I redefine AWS_STORAGE_BUCKET_NAME after all of these lines, all that will change is the folder name will change from bucket_name to whatever else. Except I don't want to rename this folder, I want to either remove it entirely or get django to understand this folder. … -
How can I get MINIO access and secret key?
I'm new to minio and I want to use it in a Django app, I read the documentation of minio python library and there is a field for MINIO_ENDPOINT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY. I read the Quickstart documentation of minio but I didn't figure out how to find these parameters. -
Unable to insert into django model with foreign key pointing to user model
I am pretty new to django and I am working on a job portal website. My users are recruiters and students. When a recruiter posts a job, i am able to retrieve all the values from the form but unable to insert in my Internship Model. Can you guys help please? Here is my code: models.py class Recruiter(models.Model): STATUS_CHOICES = ( ('Pending', 'Pending'), ('Accepted', 'Accepted'), ) user = models.ForeignKey(User,on_delete=models.CASCADE) position = models.CharField(max_length=50) status = models.CharField(max_length=20, choices=STATUS_CHOICES) user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES) def __str__(self): return self.user.username class Internship(models.Model): recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True) internship_title = models.CharField(max_length=100) internship_desc = RichTextField() start_date = models.DateField() end_date = models.DateField() posted_date = models.DateField() def __str__(self): return self.internship_title views.py def post_internship(request): if not request.user.is_authenticated: messages.warning(request,"Please login first") return redirect('login') if request.method == 'POST': start_date = request.POST['start_date'] end_date = request.POST['end_date'] internship_title = request.POST['internship_title'] internship_desc = request.POST['internship_desc'] user = request.user recruiter = Recruiter.objects.get(user=user) try: Internship.objects.create(recruiter=recruiter, internship_title=internship_title, internship_desc=internship_desc, start_date=start_date, end_date=end_date, posted_date=date.today()) except: print('error') return render(request, 'post_internship.html', context) -
remove registred celery tasks from drop down menu django admin
I have several registred tasks. Сan I not show some of them? For example, so that the drop-down menu does not have main.tasks._start_proxy_loading -
In django template when scrolling remove div blocks
In django template (queryset) when scrolling remove div blocks as soon as they disappear from the browser's field of view, i.e. dynamically when scrolling down, delete blocks from the top, when scrolling up, delete blocks from the bottom and when need to re-display them? (Sorry for my English) -
Handle static and media files on django develop and production environment
I'm trying to understand how static and media files have to be handled on Django in Development and production environment. On development I have a folder called "media" where, for example, user's images are stored. My settings.py and urls.py, looks like this and works fine: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,"media") urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My question is regarding to production environment. I want that media files (After run collectstatic) to be saved on another folder (/api/vol/media) on the production server. Should I have another settings.py for my production environment? Or how should I handle this? Thanks a lot -
Django testing - subclassing tests and project directory structure
I am developing a django app, and for the first time, I want to do so, using TDD. This is my directory structure: /myproject manage.py /app1 models.py views.py urls.py /tests test_models.py test_forms.py test_views.py /myproject settings.py # ... etc. /tests __init__.py functional_tests.py base.py visitor.py loggedin.py member.py functional_tests.py import unittest from visitor import VisitorTest from loggedin import LoggedInTest from member import SpecialMemberTest if __name__ == '__main__': unittest.main() base.py import os from pathlib import Path from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import unittest # https://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class class BaseTestCases: class BaseTest(unittest.TestCase): def get_browser(self, is_headless=False): chrome_options = webdriver.ChromeOptions() chrome_options.headless = is_headless chrome_options.add_argument("--disable-notifications") chrome_options.add_argument(f"user-data-dir={str(Path.home())}") # https://stackoverflow.com/questions/31062789/how-to-load-default-pro chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36") browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) return browser def setUp(self): self.browser = self.get_browser() def tearDown(self): self.browser.quit() def test_common(self): pass logedin.py from base import BaseTestCases class LoggedInTest(BaseTestCases.BaseTest): pass member.py from base import BaseTestCases class SpecialMemberTest(BaseTestCases.BaseTest): pass visitor.py from base import BaseTestCases class VisitorTest(BaseTestCases.BaseTest): def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new online to-do app. She goes # to check out its homepage self.browser.get('http://localhost:8000') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # She is invited to enter a to-do … -
Show field only once after created Django admin
I'm trying to create an implementation of API Keys for my API, so the Externals can request an API Key and they will have access to my resources. Right now I'm using the Django admin to show and create these API Keys class External(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) name = models.CharField(max_length=255, null=False, blank=False) is_enabled = models.BooleanField(default=True) revenue_percentage = models.FloatField() created = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class ApiToken(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) name = models.CharField(max_length=255, null=False, blank=False) external = models.ForeignKey(External, on_delete=models.CASCADE) token_hash = models.CharField(max_length=128) token = models.CharField(max_length=128) created = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): if self._state.adding: # In order to know if it's being created api_key = get_random_string(length=32) concat = f'{self.id}:{api_key}' key_bytes = concat.encode('ascii') base = base64.b64encode(key_bytes) token = base.decode('ascii') self.token = token self.token_hash = make_password(api_key) super(ApiToken, self).save(*args, **kwargs) and this is the admin class ApiTokenAdmin(admin.TabularInline): model = ApiToken extra = 0 fields = ('id', 'name', 'token', 'created') readonly_fields = ('created', 'token') exclude = ('id',) class ExternalAdmin(admin.ModelAdmin): search_fields = ('id', 'name',) list_display = ('id', 'name', 'revenue_percentage', 'is_enabled',) list_filter = ('is_enabled',) fields = ('id', 'name', 'is_enabled', 'revenue_percentage') readonly_fields = ('id', 'created') inlines = [ApiTokenAdmin] admin.site.register(External, ExternalAdmin) As you see I'm storing the token that I want to share self.token = token … -
how to get logged in user data(username) in the models.py file of different app in django?
My django project has two apps - home App and models App. Home App is responsible for creating users(signup and login) into database. models App is responsible for predicting heart disease of user and storing disease result. My problem is I want to create a database in models app and want to retrieve the logged in user data in models App database. -
copying to STATIC_ROOT using collectstatic but image not visible
Need to access static files from common directory as suggested in https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/ command, python manage.py collectstatic copies to STATIC_ROOT but when referring to it in html, it throws error Not Found: /static/teststatic/images/product-5.jpg How to make it work with files from the STATIC_ROOT location ? I have tried this and has worked <img src="{% static 'teststatic/static/teststatic/images/product-5.jpg' %}" alt="Trulli" width="500" height="333"> urls.py from django.urls import path from . import views app_name = 'teststatic' urlpatterns = [ path('tstatic/', views.tstatic, name='tstatic'), ] views.py from django.shortcuts import render # Create your views here. def tstatic(request): return render(request, 'tstatic.html', {}) settings.py . . STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = ( ('testcss', os.path.join(BASE_DIR, 'testcss', 'static', 'testcss')), ('helpdesk', os.path.join(BASE_DIR, 'helpdesk', 'static', 'helpdesk')), ('teststatic', os.path.join(BASE_DIR, 'teststatic', 'static', 'teststatic')), (os.path.join(BASE_DIR, 'staticfiles')) ) STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' tstatic.html {% load staticfiles %} <!DOCTYPE html> <html> <body> <h2>HTML Image</h2> <img src="{% static 'teststatic/images/product-5.jpg' %}" alt="Trulli" width="500" height="333"> </body> </html> Error : 2021-04-27 12:42:47,744: Not Found: /static/teststatic/images/product-5.jpg -
save method in django views.py not working after overriding it in models,py
this is my home function from views.py file, I am trying to update the count of comments on respective blogs if anyone have commented on my blog post. everything was working fine before but then I added save method in models.py and from then even if i change keywords of blog from admin panel and tries to save it , it saves but don't update the keywords and keeps the previous one. [ i printed every blog and their respective comments and they are printing the right result suppose my blog 1 had 2 comments and someone added new comment i get three as comment count for blog 1 ] Can someone please tell me what's the issue and help me to solve it. def home(request): all_blogs = Blog.objects.all() for b in all_blogs: comment_per_blog = Comment.objects.filter(blog=b.id, active=True).count() print(f"blog {b.id} has {comment_per_blog} comment") b.blog_comments = comment_per_blog b.save() This is my blog model from the models.py file. class Blog(models.Model): objects = models.Manager() slug = models.SlugField(default="", null=True, blank=True, max_length=255) keywords = models.CharField(max_length=500, default="", null=True, blank=True) title = models.CharField(max_length=500) main_image = models.ImageField(upload_to='Blog', null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) body = RichTextUploadingField(null=True, blank=True) tags = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) likes = … -
Not authenticating in DRF
I want to log in using email and password. But the authentification is not happening. have a look at the codes. class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=50) password = serializers.CharField(max_length=50) def validate(self, data): email = data.get("email") password = data.get("password") if email and password: user = authenticate(username=email, password=password) print(user) if user: data['user'] = user print(user.id) else: msg = 'login failed' raise exceptions.ValidationError(msg) else: msg = 'provide credientials' raise exceptions.ValidationError(msg) return data views. class LoginView(APIView): def post(self, request): serializer = TokenObtainSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] djangologin(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'message':'You have successfully Logged in.','user':user.id,'token': token.key}, status=200) -
Winerror8 while installing Django 3.2
I was trying to install Django 3.2 using pip.The installation was completed 50% but suddenly an error popup showing [winerror8] not enough storage can someone help me with this.