Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my Javascript not working for checking is Username already exists?
I am super new to Javascript, and I'm trying to implement some code that will search if a username already exists and then display an error if it does dynamically rather than having to hit submit and then finding out the username already existed. I tried implementing some JS but it's not working. What am I doing wrong? reg.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} {% block javascript %} <script> $("#id_username").change(function () { var username = $(this).val(); $.ajax({ url: '/ajax/check_if_username_exists_view/', data: { 'username': username }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); </script> {% endblock %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > <div class="is-valid"> {% bootstrap_form registration_form%} </div> {% csrf_token %} {% for field in bootstrap_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> <br> <button type="submit">Register</button> </div> </form> {% endblock content … -
Why am I getting a WinError 32 while deleting a file on django?
I added a function to my code that deletes files and text, when there is just text it deletes it with no problem but when there is a file(video) involved it returns a permission error [WinError 32], I dont know where am I bad but I think it might be on the views.py because I initially setted that code to just delete text. views.py def delete_video(request, video_id): delete_v = Post.objects.get(id=video_id) delete_v.delete() return HttpResponseRedirect('/') models.py (it has a @property that when a file is deleted, it also deletes it from the media folder) class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank="True") user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') def __str__(self): return str(self.text) @receiver(models.signals.post_delete, sender=Post) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.video: if os.path.isfile(instance.video.path): os.remove(instance.video.path) urls.py urlpatterns = [ path('delete_clip/<int:video_id>/', views.delete_video, name='delete_video'), ] home.html <form action="delete_clip/{{ content.id }}/" method="post"> {% csrf_token %} <button type="submit">Delete</button> </form> -
Why do I keep getting a multiValueDictKey Error in my Django/Bootstrap project?
Here is the code for my login form: <form class="user" action="/returningAgent/" method="post" > <div class="form-group"> <input type="email" class="form-control form-control-user" id= "InputEmail" name="InputEmail" aria-describedby="emailHelp" placeholder="Enter Email Address..."> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" id="InputPassword" name="InputPassword" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox small"> <input type="checkbox" class="custom-control-input" id="customCheck"> <label class="custom-control-label" for="customCheck">Remember Me</label> </div> </div> <a href="/returningAgent/" class="btn btn-primary btn-user btn-block"> Login </a> <hr> <a href="/returningAgent/" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Login with Google </a> <a href="/returningAgent/" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Login with Facebook </a> </form> and here is the code that the form submission triggers: def returningAgent(request): #try: x = Agent.objects.get(bizEmail = request.POST["InputEmail"], password = request.POST["InputPassword"]) diction = { 'f' : x.firstName, 'l' : x.lastName, 'e' : x.bizEmail } return render(request, 'index.html', diction) #except: #return HttpResponseRedirect('/404/') I have tried switch request.POST to request.POST.get, and have the name of the field within the HTML form code, yet I still continue to get an error everytime I try to use credentials that are already in my database. Any ideas? -
Google Maps integration with Django
I am looking to integrate Google Maps or some sort of mapping system such that the user can just enter an address and it appears in a drop-down or they can drag across a map. I have tried using PostGIS, however, I couldn't figure it out. Further, I tried looking up some API's and messed around with them extensively, but due to the lack of documentation, I couldn't figure it out. Any advice? -
geodjango ubuntu upgrade reads coordinates backwards
Im updating a geodjango project from ubuntu 16 to 20, Ive tried with yml file, and with setting up a new env, but i cant figure out why the admin iis reading the database features coordinates backwards, it works fine in the ubuntu 16 prohect, I cant solve it, heres how it looks: the feature in the django admin the complete layer on qgis (postgres database connection) -
How to show data in template Django without refreshing the page
I have a django/python project, where i need to check every url and show its status on template, the urls are in a excel file, i was able to do this check with Python and print the status but i want to show a list of urls on template then every url will be checked and changed color according to the status( Ok or Ko) without refresing the page, i want to check every line on excel file then send the status to template and keep checking , i know i should use ajax but i don't know how to do this, i'm really lost, can i have your help pleaase! this is my code : (as you see i used to send a list but i want to show the status afetr every check ) check.py data_xls = pd.read_excel(r'C:....Check.xlsx', index=False) df = DataFrame(data_xls) s = requests.session() headers = {'accept': 'application/json;odata=verbose'} for index, row in df.iterrows(): res =s.get(login_url) if res.status_code == 200: list2 += row['login_url'] + "," + row['portail'] + ";" else: list1 += row['login_url'] + "," + row['portail'] + ";" return JsonResponse({'portails': list1,'names':list2}, status=200) Thank you in advance! -
Is accessing foreign key ID field directly faster in Django?
Please reference these example models: class Player(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) class Team(models.Model): captain = models.ForeignKey(Manager, on_delete=models.CASCADE) country = models.CharField() class Manager(models.Model): networth = models.FloatField() I am trying to figure out if the following is faster than the alternative (ie. accesses the database less): team = Team.objects.get() Player.objects.filter(team_id=team.id) Alternative: team = Team.objects.get() Player.objects.filter(team=team) -
Can't get Profile object that belongs to User in django
I have a blog app in Django and on the home page I display all posts as well as the user that posted. However, I'm now trying to add the user's profile image next to the usernames and I can't seem to pull any data from the Profile object. In my templates, when I loop through the posts, code such as {{ post.user }} works fine, but when I try to extend beyond that like post.user.profile.profile_image.url nothing shows up. models.py: class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) class Profile(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) profile_image = models.ImageField(default='image.png', upload_to='profile_images', blank=True, null=True) views.py: def home(request): posts = Post.objects.annotate(comments_count=Count('comments')).order_by('-created_date') common_tags = Post.tags.most_common()[:4] title = "" return render(request, 'post/home.html', {'posts': posts, 'common_tags': common_tags}) And in my html template I'm just doing a {% for post in posts %} loop. Any ideas? Thanks!! -
Django-taggit. How to add a tag to all the items in a category
I'd like to have the ability to add the same tag to all the items within a category. Let's say I have a category named Service and Service has 42 posts. I would like to be able to add a tag named "tire" for instance to every post in Service From admin, perhaps, how could this be done? Thanks in advance for any help. -
How give 2 parameter in PUT method?
I have a model of books with name and id. I want to change the name using PUT method requests, but I don't know how to handle put requests in django. I want to receive 2 parameter in PUT request: new name and id. the older name will be replaced by new name but the id won't change. this is my incomplete function: def change_book_name(request): put = QueryDict(request.body) new_name = put.get("name") -
django how to generate QR code in my model
I'm new to Django and I came to the part where I need to generate a QR barcode for each product in my App I found two libraries django-qr-code and django-qrcode what is the deference between these two libraries and which one I should use the other point is there any good tutorial I can follow to generate a QR code in a model ? -
I want to configure AWS S3 on my django project but many of my client's media files are on my pythonanywhere server already
I want to integrate AWS S3 now in my django project and i have done all that but the problem is many of my client's media files are already on the pythonanywhere server and now i want to change it to AWS S3 so the upcoming media files should be stored in S3 and the previous should be stored in pythonanywhere. But now what happens is that the new files are storing correctly and i can open them but the previous files, when i open them because of the media files url i suppose django looks it in AWS S3 but they are not there. So i need to django to understand to look for the media files where they are stored like for the previous files i want django to look in the server directory and for new files in S3 instance. Hope that makes sense. This is my AWS S3 configurations file for my django project This is my django settings file, mainly focuses on media files -
Change django admin label position
I need to change how the default admin form is rendered. It shows the label on the left like the image below. But I want it to be displayed on top of the input field, any idea? Here is my admin.py class ApplicationAdmin(admin.ModelAdmin): form = ApplicationAdminForm list_display = ['last_name', 'income'] fieldsets=( ("",{"fields": ( ('last_name',), ('income',), ), } ), ) -
Django-taggit migration fails at AlterUniqueTogether
I'm trying to migrate my Django application which uses jazzband django-taggit The error I get is: django.db.utils.IntegrityError: could not create unique index "taggit_taggeditem_content_type_id_object_i_4bb97a8e_uniq" DETAIL: Key (content_type_id, object_id, tag_id)=(41, 596, 242) is duplicated. The migration in question reads: migrations.AlterUniqueTogether( name="taggeditem", unique_together={("content_type", "object_id", "tag")} ) https://github.com/jazzband/django-taggit/blob/master/taggit/migrations/0003_taggeditem_add_unique_index.py#L12-L14 Which translates to the following SQL: ALTER TABLE "taggit_taggeditem" ADD CONSTRAINT "taggit_taggeditem_content_type_id_object_i_4bb97a8e_uniq" UNIQUE ("content_type_id", "object_id", "tag_id"); COMMIT; Checking the table in question I do get: # SELECT * FROM public.taggit_taggeditem WHERE tag_id=242 ORDER BY object_id; id | tag_id | object_id | content_type_id ------+--------+-----------+----------------- 691 | 242 | 356 | 41 2904 | 242 | 356 | 41 680 | 242 | 486 | 41 2893 | 242 | 486 | 41 683 | 242 | 596 | 41 2896 | 242 | 596 | 41 What is the suggested way to resolve the django.db.utils.IntegrityError error and successfully finish the migration? I think the same will happen with object_id 486 and 356 (+ several more). -
Django create a new record for each user every month
The title is self explanatory. I would like to create a new record for a user at the start of each month. What is the best way to achieve this in Django? My initial thoughts were to run a function that will check the date time every x amount of intervals and then if year and month of last record != then create a new record. Is this even possible? It seems that this constant checking of time would be inefficient but I am struggling to think of another solution. Am I headed in the right direction? -
C++ / Django Login
I have Django web application for login and register, and I need to write C++ program to login to existing account made in django register, how can I achieve this? -
how to add python in cpanel in ubantu server?
I have a VPS server with centos and I have Cpanel. How to after installing python from WHM it is not showing in Cpanel. I am not able to create a project in the Django. Please help -
How to save local data to a database in django?
I have a web scraper which is returning JSON data. I want to save that data to a database. I have gone through a lot of resources but none really explains how to perform a POST request on a local data or pass local data to a POST request. -
django admin : how can i use smart_selects in multi inline
how can i use smart_selects in multi inline i need in the admin django to select (Select Country) and show the cities of this country in inline i use : smart_selects : django_smart_selects_711-1.0.0.dist-info fieldsets_with_inlines : django_fieldsets_with_inlines-0.5 see what i need class Country(models.Model): status_choice = ( (1, 'Supprimé'), (2, 'Désactivé'), (3, 'Activé'), ) nom = models.CharField(max_length=100, blank=False,verbose_name="Nom") continents = models.ForeignKey(Continents, on_delete=models.CASCADE,verbose_name="Continents") region = models.ManyToManyField(RegionsMonde,verbose_name="Région") superficie = models.CharField(max_length=100, blank=True,verbose_name="Superficie") population = models.CharField(max_length=100, blank=True,verbose_name="Population") capitale = models.CharField(max_length=100, blank=True,verbose_name="Capitale") devise = models.CharField(max_length=100, blank=True,verbose_name="Devise") LangueOfficielle = models.CharField(max_length=100, blank=True,verbose_name="Langue(s) officielle(s)") formeEtat = models.CharField(max_length=100, blank=True,verbose_name="Langue(s) officielle(s)") chefEtat = models.CharField(max_length=100, blank=True,verbose_name="Chef de l'Etat") feteNationale = models.CharField(max_length=100, blank=True,verbose_name="Fête nationale") monnaie = models.CharField(max_length=100, blank=True,verbose_name="Monnaie") cgPm = models.CharField(max_length=100, blank=True,verbose_name="Chef du Gouvernement/Premier Ministre") ministreTutelle = models.CharField(max_length=100, blank=True,verbose_name="Ministre(s) de tutelle") lienMinistre = models.CharField(max_length=100, blank=True,verbose_name="Lien du Ministère") nbrUniversits = models.CharField(max_length=100, blank=True,verbose_name="Nbr d'Universités") status = models.IntegerField(choices=status_choice,default=3) def __str__(self): # __unicode__ for Python 2 return self.nom class Meta: ordering = ('nom',) verbose_name = 'Pays' verbose_name_plural = 'Pays' def regionName(self): return ', '.join([r.nom for r in self.region.all()]) regionName.short_description = "Regions" class City(models.Model): nom = models.CharField(max_length=100, blank=False) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.nom class Meta: unique_together = ('country', 'nom') verbose_name = 'City' verbose_name_plural = 'Cities' -
dj_database_url() loads empty dictionary for DATABASES when running locally
I have been following this tutorial: https://blog.usejournal.com/deploying-django-to-heroku-connecting-heroku-postgres-fcc960d290d1 It explains how to use the default SQLite3 database when running locally on your computer and postgreSQL when on Heroku. It has with the following steps: make an .env file with: 'DATABASE_URL=sqlite:///db.sqlite3' Then in settings.py add: dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) and DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) But now I can't connect to my SQLite database when running locally and when I print DATABASES it's empty. I use anaconda and have installed the packages with conda install Any idea what causes this? -
Annotate each query with a function of itself
I need to annotate each query in queryset using a model method: class myModel(models.Model): ... def myModel_foo(self): .... return myModel_foo I need something like .annotate(myModel_foo=myModel.myModel_foo()). The problem is myModel_foo() requires self. I tried iterating over queryset and using query.annotate(myModel_foo=myModel.myModel_foo(self)), but i got object has no attribute 'annotate' error. What's the correct approach? -
How to serve a djangoAPI and Angular frontend in Apache
I am trying to serve a DjangoAPI with an Angular frontend. It already works on localhost using apache2, however it doesn't work on the web. The API is directed to 127.0.0.1:8000. further more the back end has an /auth, /projects and /admin url I would like to use. My current Apache set up is: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /home/user/Websites/Webapp/WebappFrontEnd ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/user/Websites/Webapp/WebappFrontEnd> Require all granted </Directory> </VirtualHost> <VirtualHost *:8000> ServerAdmin webmaster@localhost DocumentRoot /home/user/Websites/Webapp/WebappAPI SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/user/Websites/Webapp/WebappAPI/Webapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/Websites/Webapp/WebappAPI/Webapp/wsgi.py WSGIDaemonProcess Webapp python-path=/home/user/Websites/Webapp/WebappAPI python-home=/home/user/Websites/Webapp/WebappAPI/venv WSGIProcessGroup Webapp </VirtualHost> I already tried adding the following and adjusting ports accordingly: <VirtualHost *:80> ProxyPreserveHost On ProxyRequests Off ProxyPass /api/ http://localhost:8000/api/ ProxyPassReverse /api/ http://localhost:8000/api/ ProxyPass /auth/ http://localhost:8000/auth/ ProxyPassReverse /auth/ http://localhost:8000/auth/ ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ </VirtualHost> which let to Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at [no address given] to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server … -
Passing the data from a sign up form through a python script to create a new field in the user database in Django
I would like to add a specific code to each user as as they sign up for example my current form is in html - **<form class="form-signin" method="post">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Get your SiD</h1> <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus> <input type="text" name="firstname" id="inputFirstname" class="form-control" placeholder="First Name" required> <input type="text" name="middlename" id="inputMiddlename" class="form-control" placeholder="Middle Name" required> <input type="text" name="lastname" id="inputLastname" class="form-control" placeholder="Middle Name" required> <input type="text" name="idnumber" id="inputIdnumber" class="form-control" placeholder="ID number" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Verify & Get SiD</button> </form>** At the moment all of the fields save fine in my user database. However once doing the form I would like to automatically add another field to the user "customercode" which would be created through using the following python script - **import random import string def randomStringDigits(stringLength=6): """Generate a random string of letters and digits """ lettersAndDigits = string.ascii_letters + string.digits return ''.join(random.choice(lettersAndDigits) for i in range(stringLength)) email = input(); firstName = input(); firstInitial = firstName[0]; middleName = input() or "0"; middleInitial = middleName[0]; lastName = input(); lastInitial = lastName[0]; idnumber = input(); import datetime # Current time now = datetime.datetime.now() month = now.strftime("%m") day = now.strftime("%d") hour = now.strftime("%H") minute = now.strftime("%M") … -
Django: Does the virtual environment have to be on every time i develop my django app
i have installed and set up the virtual environment using the command line. i am using pycharm to develop my django application. so that was day 1. On day 2 when i put my laptop back on to go back to working on my django application do i need to go back to command line and type in workon 'virtualenvironment-name' or can i just develop the django app without switching on the virtual environment. -
Use Django Money field as default value in Django Case
I am trying to set a default value In Django Case but it complains django.db.utils.ProgrammingError: can't adapt type 'Money' Here is my code from djmoney.models.fields import MoneyField def method(self): clauses = [ When( value_currency=u.value_currency, then=Value(u.value) ) for u in Price.objects.all() ] return Case( *clauses, default=Value(Money('0.0', settings.DEFAULT_CURRENCY)), output_field=MoneyField() ) In [1]: type(Price.objects.first().value) Out[1]: djmoney.money.Money I have used that method in query set like this qs = qs.annotate( _price=self.method() ) I can use DecimalField() Like this and it works. def method(self): clauses = [ When( value_currency=u.value_currency, then=Value(u.value.amount) ) for u in Price.objects.all() ] return Case( *clauses, default=Value(0.0), output_field=models.DecimalField() ) But I want qs._price to be Money type. Can we use Money field value in Django Case?