Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send excel file as a parameter from angular to an endpoint in django
Good I have a query, the question is that I need to upload an excel file with records (to overwrite said records in a BD / or create new records) from angular to django, that is to say I upload the file and I need to process it in a view of django or django rest framework, my question is if it is possible to pass that parameter to an endpoint and how would it be? I'm new to both technologies and I need this for my project -
i can't install hazm on cpanel host
i want to install hazm on cpanel .I use this command to install this package : 'pip install hazm' but it's work in my pc and dont work in my host and get this error : ERROR: Complete output from command /home/newsir/virtualenv/mySite/3.7/bin/python3.7 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-2kptnz5u/libwapiti/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-8l3jvmao --python-tag cp37: -
Automatically adding a slash at the end of a url
I've got all urls configured correctly, with a trailing slash. Now, whenever I visit a correct url that has no trailing slash, I get the "homepage" (since this is the page to show when a url is wrong). This is a pain in the ass since the url is 'somewhat' correct. I've tried to explicitly enable this with APPEND_SLASH = True in the settings.py but without any success. I'm still in the development phase so no weird rewrite rules from a server. What could be the cause of this? Thanks in advance! -
issue with selenium - find_elements_by_xpath or find_elements_by_tag
I'm having an issue where I'm not sure where lies the issue. I've created a functional test for, called func_tests1.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it(self): self.browser.get('http://localhost:8000') self.assertIn('To-do',self.browser.title) header_text = self.browser.find_elements_by_tag('h1') #this is where lies the issue inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual( inputbox.get_attribute('placeholder'), 'Enter a to-do item' ) inputbox.send_keys('Buy peacock feathers') #Functional test now checks we can input a to-do item inputbox.send_keys(Keys.ENTER) time.sleep(1) table = self.browser.find_element_by_id('id_list_table') rows = table.find_element_by_tag_name('tr') self.assertTrue( any(row.text == '1: Buy peacock feathers' for row in rows), "New to-do item did not appear in table" ) # There is still a text box inviting her to add another item. # She enters "Use peacock to make a fly" # Edith is very methodical self.fail('Finish the test!') if __name__ == '__main__': unittest.main(warnings='ignore') This is my template, hme.html <html> <head> <title>To-do lists</title> </head> <body> <h1>Your To-do list <h1> <input id="id_new_item" placeholder="Enter a tod-o item"/> <table id="il_list_table"> </table> </body> <!-- --> </html> And last, but not least, this is my test case, tests.py from django.urls import resolve from django.test import TestCase from django.http import HttpRequest from django.template.loader import render_to_string from lists.views import home_page … -
How to stop the active failed error in gunicorn?
I am trying to get the gunicorn to be active and for some reason it failed. When I use --bind 0.0.0.0:8000 myproject.wsgi. It work! I can get on the website fine, but I am getting this error when I input sudo systemctl status gunicorn I get an error and cannot move on to nginx. To give you understanding where everything in my file, I entered a dir command to show. nyfl_djangoline@DjangoNFL:~/sportsproject/portfolio-project/my_app1/first_app$ dir db.sqlite3 first_app1.sock pg_hba.conf requirements.txt sports_app first_app manage.py postgresql.conf sites-enabled todo_list Also sudo nano /etc/systemd/system/gunicorn.service provided me this output: [Unit] Description=gunicorn daemon After=network.target [Service] User=nyfl_djangoline Group=www-data WorkingDirectory=/home/nyfl_djangoline/sportsproject/portfolio- project/my_app1/first_app/first_app ExecStart=/home/nyfl_djangoline/sportsproject/sports_app/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/nyfl_djangoline/sportsproject/portfolioproject/my_app1/first_app/first_app1.sock first_app.wsgi:appliioncation [Install] WantedBy=multi-user.target *Sports_app is the environment for this project I receive a sock file and even sites-enabled for ngnix(whole seperate issue), but when I try to move ngnix I am getting issues and I believe it goes back to gunicorn. I have tried changing the file direction on sudo nano /etc/systemd/system/gunicorn.service, but I keep getting the same issue. I also use sudo journalctl -u gunicorn and I do not get an entries. [Unit] Description=gunicorn daemon After=network.target [Service] User=nyfl_djangoline Group=www-data WorkingDirectory=/home/nyfl_djangoline/sportsproject/portfolio- project/my_app1/first_app/first_app ExecStart=/home/nyfl_djangoline/sportsproject/sports_app/bin/gunicorn -- access-logfile - --workers 3 --bind unix:/home/nyfl_djangoline/sportsproject/portfolio- project/my_app1/first_app/first_app1.sock first_app.wsgi:appliioncat [Install] WantedBy=multi-user.target … -
django+heroku error in createsuperuser "psycopg2.errors.UndefinedTable: relation ”users_profile“ does not exist"
i am new to django,there is no problem in local system for this ,makemigrations,migrate and createsuperuser everything works fine in local system.but when i am trying to deploy in heroku with postgresql makemigrations and migrate ran fine, problem is when i am trying to createsuperuser, it is giving me an error. (djangoenv) E:\youngminds>heroku run bash Running bash on ? youngminds... up, run.8229 (Free) ~ $ python manage.py createsuperuser Username (leave blank to use 'u21088'): johnson Email address: johnson@gmail.com Password: Password (again): Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils .py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_profile" does not exist LINE 1: INSERT INTO "users_profile" ("user_id", "image", "descriptio... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_ _init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_ _init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b ase.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana gement/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b ase.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana gement/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user _data) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mode ls.py", line 161, in create_superuser return self._create_user(username, email, password, … -
create facebook like notification system in django
Say user a liked user b. I want to show this as a notification in the notification panel of user b when she logs in. She can also view her previous notifications (basically like facebook notification). This is not email notification or a success/warning type one time notification. I want to know the right track to follow. Do I use django-notifications or django-messages-framework? Where is the use of channels and web sockets in all of these? My steps: 1) create a notification app 2) create a notification model (what fields do I put here if since django-notification already has actor, verb, action object and target fields?) 3) Do i have to create forms.py? How is the notification message getting passed? 4) What view do I put in views.py? (please give an example code) If there is any example project that implemented the notification system please provide a link. -
RelatedObjectDoesNotExist for a model with foreginkey with standard user model
I have this issue :RelatedObjectDoesNotExist I add a UserProfile to my models (for now there is only avatar to be added to User Model. It is not mandatory to add a picture. So some userProfile are null. The proble is when I edit Userform and ProfileUserform. I had an error : RelatedObjectDoesNotExist at /accounts/user_edit/ User has no profile. I try to add a try: except in views but seems not working Models.Py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') # il s'agit d'ajouter des infos au modele User # add any additional attributes needed avatar = models.ImageField(upload_to='profile_pics', blank=True) # avatar of the user in director profile_pics def __str__(self): return self.user.email Views.py: @login_required(login_url='account/sign_up.html') def user_edit(request): # Get info from "both" forms # It appears as one form to the user on the .html page user_form = UserFormEdit(instance=request.user) profile_form = UserProfileForm(instance=request.user.profile) # Check to see both forms are valid if user_form.is_valid() and profile_form.is_valid(): # Prepare Save User Form to Database user = user_form.save() profile = profile_form.save(commit=False) # Check if they provided a profile picture if 'profile_pic' in request.FILES: print('found it') # If yes, then grab it from the POST form reply profile.profile_pic = request.FILES['profile_pic'] profile.save() messages.success(request, 'User updated') return render(request, 'account/user_edit.html', {'user_form': … -
Display data through StreamListener
I am using tweepy with django. I have the problem that I can print the data on the terminal but when I also use django, everything get complicated. I use this code: class MyStreamListener(tweepy.StreamListener): def on_status(self, status): print(status.text) def on_data(self, data): all_data = json.loads(data) tweet = all_data["text"] print(tweet) return True def home(request): auth = tweepy.OAuthHandler( consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) return HttpResponse("") When I run a similiar code to this, through the terminal (python app.py) it works. But not with django. I have problems to display the outputs. And I know that I can display it through the httpResponse, but the tweets are in the on_data function in the data parameter. So how can I do it? -
How to solve : AH01630: client denied by server configuration
I am trying to configure my django project with Apache 2.4.29. when trying to open the application from browser : Forbidden You don't have permission to access / on this server. Apache/2.4.29 (Ubuntu) Server at localhost Port 85 The error log says AH01630: client denied by server configuration: /home/dev-py/blog/ I've written the config as 'blog.conf' in the /etc/apache2/sites-available I tried changing the ownership to www-data and also tried to use chmod -R 777. Nothing worked. Listen 85 ServerAdmin roni@xxx.mail DocumentRoot /home/dev-py/ Alias /static /home/dev-py/blog/static_cdn <Directory /home/dev-py/blog/static_cdn> Options All AllowOverride All Require all granted </Directory> Alias /media /home/dev-py/blog/media <Directory /home/dev-py/blog/media> Options All AllowOverride All Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/blog_error.log CustomLog ${APACHE_LOG_DIR}/blog_access.log combined WSGIDaemonProcess blog python-home=/home/dev-py/blog/venv python-path=/home/dev-py/blog WSGIProcessGroup blog WSGIScriptAlias / /home/dev-py/blog/ <Directory /home/dev-py/blog/blog> <Files wsgi.py> Require all granted </Files> </Directory> -
ValueError in submitting a form to another URL for handling
I have a problem with submitting a form to a different URL using the form “action” attributes. I have a DetailView (as shown below) that shows information about a particular Teacher, like a profile page and the HTML template the DetailView renders contains a form which would be handled by another URL/view. views.py class TeacherDetail(DetailView): model = Teacher template_name = ‘teacher_info.html’ user_info.html #showing the form <form method="POST" action="/inter/account/start/">{%csrf_token%} <input type="hidden" name="teacher" id="object.id" value="{{object}}"> <button type="submit" name="invite">Invite Teacher</button> </form> My intention is to also send the object itself from this particular DetailView to the url the form would be sent to because it would be needed for the form validation. views.py #where the form is been sent to class MakeInvitation(CreateView): model = Invitation fields = [] def form_valid(self, form): form.instance.inviter = self.request.user.student form.instance.invitee = self.request.POST['teacher'] return super().form_valid(form) The model “Invitation” has only two fields, inviter and invitee. I made the form.instance.inviter to be the current student user and the form.instance.invitee (a ForeignKey to a Teacher model) to be the teacher whose profile page was where the form was coming from, so I am trying to use request.POST to get the object from the form in the DetailView Page. I get a … -
I'm doing a view count, but it causes an error
Name of error 'page_hits' is decorated with takes_context=True so it must have a first argument of 'context' I make the view counter. It is necessary that the function handles the entry of a person to the site and output it to a template. Please give ready-made code for fix already read a lot about https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/ Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\MAestro\Desktop\RapterGame.com\RapterGames\news\views.py" in Detail 195. return render(request,'news/post_detail.html') File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py" in render_to_string 61. template = get_template(template_name, using=using) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py" in get_template 15. return engine.get_template(template_name) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py" in get_template 34. return Template(self.engine.get_template(template_name), self) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py" in get_template 143. template, origin = self.find_template(template_name) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py" in find_template 125. template = loader.get_template(name, skip=skip) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loaders\base.py" in get_template 30. contents, origin, origin.template_name, self.engine, File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in __init__ 156. self.nodelist = self.compile_nodelist() File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in compile_nodelist 194. return parser.parse() File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in parse 478. raise self.error(token, e) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in parse 476. compiled_result = compile_func(self, token) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\library.py" in compile_func 121. kwonly, kwonly_defaults, takes_context, function_name, File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\library.py" in parse_bits 250. "have a … -
Django remove trailing slashes - urls or redirect
I'm trying to remove the trailing slashes in my urls or make redirection happen if a slash is added at the end. I tried to do it on resources from the Internet but it does not work for me. I guess I'm doing something wrong. urls.py - app app_name = 'shop' urlpatterns = [ # product path('', views.product_list, name='product_list'), path('show/<slug:slug>', views.product_show, name='product_show'), path('<slug:category>', views.product_list, name='lst_by_ctgry'), path('<slug:category>/<slug:subcategory>', views.product_list, name='lst_by_subctgry'), path('<slug:category>/<slug:subcategory>/<slug:kind>', views.product_list, name='lst_by_knds'), # info - these urls doesn't work without slashes. works only with slashes path('pad', views.pad, name='pad'), path('guarantee', views.guarantee, name='guarantee'), path('contacts', views.contacts, name='contacts'), path('about', views.about, name='about'), path('privacy', views.privacy, name='privacy') ] urls.py - project urlpatterns = [ path('', include('orders.urls')), path('', include('cart.urls')), path('', include('shop.urls')), path('admin/', admin.site.urls), ] settings.py APPEND_SLASH = False MIDDLEWARE = [ ... 'django.middleware.common.CommonMiddleware', ... ] Сan you give an example please how can i remove trailing slashes in all urls or get redirect -
Django-storages : Keeping a cached version locally to increase read speed
With Django-storages, is it possible to keep a cached version locally for subsequent requests? I'm trying to read few large files (~10 mb) on user requests. Since I'm using elastic-beanstalk and multiple instances, I've to keep them on S3. Those files are updated using an external script. Django app only reads them. Is there a way I could keep a cached version locally when using Django-storages? -
best practice to count unread message in a social app project
i have a project something like Instagram . user can send message, sharing story. what is best practice to count and export unread message and new shared post for each user? i have some idea about it: 1- Add unread_count and unread_messages and new_shared_related_post field to User's model and every time new event happened adding +1 to unread_count and when user get new message or get new post the unread_count` set with 0 or decrease by suitable nuber. in this method we need to add a "last_seen_unread_msg" to User's model too so we can export new post/new message when needed. 2- Adding new model related to every user to store new messages and new related shared post so we can easily have all we need but database will be bigger.(i'm just explained simple , in the main i mean storing new messages and new related shared posts to the fields of User's model. this fields can be models.JSONField or can have relation by models.ManyToManyField ) 3- Storing new message or new related shared story to redis to cache them fast!every time new message or new post happens we can add them to redis related to user .(this is something like … -
how can I select items from one table and and sort it by his attribute mark as FK
I want to select items of reservation and sort it by option.effectif where option is declared as FK in table reservation. The sql that I want to have is: select * from configuration_option, configuration_reservation where configuration_reservation.option_id= configuration_option.id and valide=True order by configuration_option.effectif; for this selection I have tried : p=Reservation.objects.all().filter(Q(option_id__in=Option.objects.all().order_by('effectif'), valide=True)) The models are: class Reservation( models.Model): cours=models.ForeignKey(Cours, on_delete=models.CASCADE) enseignant=models.ForeignKey(Enseignant, on_delete=models.CASCADE) date_du_jour_reserve=models.DateField("Date du jour reservé") option=models.ForeignKey(Option,on_delete=models.CASCADE ) valide=models.BooleanField(blank=True, default=False) class Meta: ordering=('date_du_jour_reserve') class Option(models.Model): code_option=models.CharField("Code de l'option", max_length=6,) libelle_option= models.CharField("Libélle de l'option", max_length=100) effectif=models.IntegerField("Effectif", default=0, validators=[ MinValueValidator(limit_value=0 , message=" Attention votre option a un effectif négatif"), ]) def __str__(self): return self.libelle_option class Meta: ordering=('libelle_option',) -
Django migrations conflict multiple leaf nodes in the migration graph
With Django 1.11.22 I'm trying to run migrations python manage.py migrate django.db.migrations.exceptions.InconsistentMigrationHistory: Migration base.0036_auto_20190227_1226 is applied before its dependency base.0027_auto_20170801_1228_squashed_0037_auto_20190222_1347 on database 'default'. My first try to solve this was sudo -u postgres psql -d albatros -c \ "DELETE FROM django_migrations WHERE name = '0036_auto_20190227_1226' AND app = 'base'" In the hope of deleting the migration from the migration table would fix it. Unfortunately I'm now getting: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0037_auto_20190222_1347, 0036_auto_20190227_1226 in base). To fix them run 'python manage.py makemigrations --merge' When tryin makemigrations --merge it does not find any migrations to merge. This is what showmigrations looks like: ./manage.py showmigrations base base [X] 24_initial [X] 24_to_26 [X] 26_to_27 [X] 0027_auto_20170801_1228 [X] 0028_resourcebase_is_approved [X] 0029_auto_20171114_0341 [X] 0030_auto_20180309_0833 [X] 0031_auto_20180309_0837 [X] 0032_auto_20180329_1844 [X] 0033_auto_20180330_0951 [X] 0034_auto_20180606_1543 [X] 0035_resourcebase_dirty_state [ ] 0036_auto_20190227_1226 [ ] 0036_auto_20190129_1433 [ ] 0037_auto_20190222_1347 Can one say how to correctly apply the migrations and solve the multiple leaf nodes error? -
How to disable browse server option for non admin while uploading image in django-ckeditor?
I have a blog on django on which any public can post. In post content I am using django-ckeditor RichTextUploadingField. There is button for in ckeditor, that let users browse images of server's upload directory and embed images in post. But i want to restrict public from browsing images on server when they make post. They should be able upload images only, not browse every image on server that is uploaded. Here is my models.py class Article(models.Model): title = models.CharField(max_length = 200) content = RichTextUploadingField() author = models.ForeignKey(User, on_delete= models.CASCADE, null=True) def __str__(self): return self.title Forms.py class ArticleForm(ModelForm): class Meta: model = Article widgets = { 'content': RichTextUploadingField() } -
How to make search bar working in django?
I made a search bar and I want it to search the titles which is in the site. Before typing nothing appears but whenever I type one title all the titles appear. How to resolve this issue? index.html def index(request): query = request.GET.get('srh') if query: target1 = Destination.objects.filter(title__icontains=query) target1 = a, b= [Destination() for __ in range(2)] a.img = 'Article.jpg' b.img = 'Micro Tasks.jpeg' a.title = 'Article Writing' b.title = 'Micro Tasks' context = {'target1': target1} return render(request, 'index.html', context) else: return render(request, 'index.html') views.py <form class="love" method="GET" action=""> {% csrf_token %} <input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br> <button type="submit" class="btn btn-danger"> Search </button> </form> <div> {% for dest1 in target1 %} {% if dest1 %} <div> <a href="{{baseUrl}}/{{dest1.img}}"> <img src="{{hiUrl}}/{{dest1.img}}" alt="" /> <h3>{{dest1.title}}</h3> </a> </div> {% endif %} {%endfor%} </div> -
How to Pass an Image File to a API Endpoint
I have a web services with DRF, I have POSTMAN passing the right all fields right with success including the image file ['avatar'] []1 Now how do i pass the image file from a Django Form, but i keep getting Error 400, Bad request. Please how do i encode the image file to be passed into the API endpoint . html <form method="post" action="#" enctype="multipart/form-data"> {% csrf_token %} <label for="phone">Enter Phone</label> {{ form.phone }} <br /> <label for="bvn">Enter BVN</label> {{ form.bvn }} <br /> <label for="avatar">Upload Avatar</label> {{ form.avatar }} <br /> <button type="submit" class="btn btn-primary" >Submit</button> </form> views.py def form_valid(self, form): token = self.request.session['session_token'] headers = {"Content-Type": 'application/json', "Authorization": "Token " + token} parameters = { 'bvn': form.cleaned_data['bvn'], 'phone': form.cleaned_data['phone'], 'avatar': self.request.FILES['avatar'] } response = requests.put(str(settings.API_END_POINT + '/customer_profile_api/'), data=parameters, headers=headers) if response.status_code in settings.SUCCESS_CODES: messages.success(self.request, 'Successfully updated profile') else: messages.error(self.request, 'API Error %s' % response.status_code) return super(CustomerDashboard, self).form_valid(form) form.py class ProfileUpdateForm(forms.Form): """customer profile update form""" phone = forms.CharField(required=False, widget=NumberInput(attrs={'class': 'form-control', 'type': 'number', 'id': 'phone', 'placeholder': 'Enter Phone Number'})) bvn = forms.CharField(required=False, widget=NumberInput(attrs={'class': 'form-control', 'type': 'number', 'id': 'bvn', 'placeholder': 'Enter BVN'})) avatar = forms.ImageField(required=False, widget=ClearableFileInput(attrs={'class': 'form-control', 'type': 'file', 'id': 'avatar', 'placeholder': 'Upload Avatar'})) -
Install needed libraries for Weasyprint on pipenv (Windows environment)
In order to start generating documents with Weasyprint I installed it on my Windows machine following these instructions: https://weasyprint.readthedocs.io/en/stable/install.html#step-5-run-weasyprint On my computer it works but I have a Django project where I want to integrate this library and I use pipenv. How to install the necessary libraries even in the virtual environment? I tried setting the path for the pycairo package into the Pipfile like pycairo= {path= "C:/Program Files/GTK3-Runtime Win64/bin/"} but still it throws the error: OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2 / cairo.so.2 I have 64bit Windows machine and this is the Pipfile: [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] pylint = "*" [packages] django = "*" mysql = "*" ipython = "*" django-webpack = "*" django-webpack-loader = "*" django-livereload-server = "*" pylint = "*" reportlab = "*" weasyprint = "*" django-weasyprint = "*" pycairo= {path= "C:/Program Files/GTK3-Runtime Win64/bin/"} cairocffi = "*" [requires] python_version = "3.7" -
Why collectstatic still uses local directory when it's specified to use s3 bucket
I'm trying to transfer static files to s3 bucket but when running python3 manage.py collectstatic in terminal it tells me it will keep static files at local directory. Full message is: You have requested to collect static files at the destination location as specified in your settings: /Users/username/Desktop/issue_tracker/staticfiles I've set up s3 variables in settings.py already. # AWS settings 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 = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'CacheControl': 'max-age=94608000', } DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-west-2' AWS_DEFAULT_ACL = None STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) Why does it still wants to store static files in local folder? -
Change Django model name index in the admin view
Whether I am trying to access all the instances of "Project" model class from the admin page or in the python shell I still get (Project.objects.all() in pyhon shell or in admin : https://ibb.co/S7F491d) <Project: Project object (4)>, <Project: Project object (5)>, <Project: Project object (6)> but instead i want <Project: Project object (1)>, <Project: Project object (2)>, <Project: Project object (3)> the indexing seems to show the ith Project created. class Project(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=200, blank=True) image = models.ImageField(null=True) data = models.DateField(blank=False, null=10 / 20 / 2009) objects = models.Manager() -
I make a counter using HitCount and get an error in import transactions django.db
I was told that the problem is in the decorator, as I add a simple decorator in CBV https://docs.djangoproject.com/en/2.2/topics/class-based-views/intro/#decorating-class-based-views enter image description here models.py class PageHit(models.Model): url = models.CharField(unique=True) count = models.PositiveIntegerField(default=0) decorators.py from functools import wraps from django.db.models import F from django.db import transaction from .models import PageHit def counted(f): @wraps(f) def decorator(request, *args, **kwargs): with transaction.atomic: counter, created = PageHit.objects.get_or_create(url=request.path) counter.count = F('count') + 1 counter.save() return f(request, *args, **kwargs) return decorator views.py from .decorators import counted @counted def post_detail(request, pk): article = Article.objects.get(id=pk) return render(request, 'news/post_detail.html', {'post': article}) templatetags/counter.py @register.simple_tag(takes_context=True) def page_hits(ctx, page_url=None): counter = (PageHit.objects .filter(url=(ctx['request'].path if page_url is None else page_url)) .first()) return 0 if counter is None else counter.count news/post_list.html {% load counter %} {% for article in object_list %} <h3>{% page_hits article.get_absolute_url %}</h3> {% endfor %} news/post_detail.html {% load counter %} <span>{% page_hits %}</span> -
Django post items for loop in javascript
I have a lineside and i want to show last posts title and some words However, i failed What should you suggest to me views.py post_list=Post.objects.filter(status=2).order_by('-created_date') context={ 'posts':post_list } return render(request,'base.html',context) js new lineside({ startOffset: 100, lineslideItems:[ {% for post in posts %} { title: '<a href="{{ post.get_absolute_url }}" class="link">{{ post.title }}: </a>', content: '{{ post.content|truncatewords_html:10 }}', separator: '<span class="separator"><span class="separator-bar">/</span><span class="separator-bar">/</span></span>' }, {% endfor %} ] }) original lineslideItems: { title: '<a href="link" class="link">Title: </a>', content: 'content', separator: '<span class="separator"><span class="separator-bar">/</span><span class="separator-bar">/</span></span>' }, { title: '<a href="link" class="link">Title: </a>', content: 'content', separator: '<span class="separator"><span class="separator-bar">/</span><span class="separator-bar">/</span></span>' }, { title: '<a href="link" class="link">Title: </a>', content: 'content', separator: '<span class="separator"><span class="separator-bar">/</span><span class="separator-bar">/</span></span>' }