Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Views.py Validate Phone Number
I would like to use something like django-phonenumber-field or another method but strictly for views.py to be able to validate or display an error message if the user does not give a valid international phone number in the format of +12125552368 as an example. This form does not use models.py or forms.py and I would like to keep everything inside of views.py if possible. Also do not want to use JavaScript for security and people disabling it reasons. Html: https://dpaste.org/sgyo Views.py: https://dpaste.org/vjZZ How can this be accomplished? -
New and updated Django CRM available as open source in GitHub
Customer relationship management (CRM) is the combination of practices, strategies and technologies that companies use to manage and analyze customer interactions and data throughout the customer lifecycle, with the goal of improving customer service relationships and assisting in customer retention and driving sales growth. What is the best open soure CRM available? -
Nginx docker container is accessible the local network
I am running an Nginx container in the docker with default configs. it is working as expected in the host machine. But not able to access it via another pc in the same network. Details : Host machine: windows (192.168.168.54) Docker VM type: Linux Nginx container mapping : 0.0.0.0:7777->80/tcp Nginx is accessible on the following host in the host pc localhost:7777 127.0.0.1:7777 192.168.168.54:7777 But 192.168.168.54:7777 can't be accessed from another pc in the same network -
PHP API is not working With Django on apache2 Ubuntu server | Google Cloud
I have successfully deployed a Django project on the apache2 web server on Linux Ubuntu machine on Google Cloud. It is working fine. Also, I have PHP API that connects with the MySQL database the same Django connects. But the issue is that the Django application works fine and PHP API is not working. I have also placed the index.html page in my /var/www/html/api_folder/index.php path. so when I type my_ip/api_folder in a browser it opens index.html page but the API is not working. the api files are in api_folder as in the index.html page. below is my conf file in /sites-available directory of apache2. even the basic PHP file works and prints the message in echo. but when I type My_ip/api_folder/api/get_about_us/?key=xxxx it shows me 404 Error page. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a … -
Uncaught SyntaxError: Unexpected token a in JSON at position 2
For several hours now I have been crazily trying to get and display json data externally using JSON.parse but am having this error below VM935:1 Uncaught SyntaxError: Unexpected token a in JSON at position 2 at JSON.parse () at Object. ((index):698) at fire (jquery-3.3.1.js:3268) at Object.fireWith [as resolveWith] (jquery-3.3.1.js:3398) at done (jquery-3.3.1.js:9305) at XMLHttpRequest. (jquery-3.3.1.js:9548) Here is my code and effort so far. can somebody help me fix this issue. I will appreciate. tacker.html {% load static %} {% block title %} Shop - Tracker {% endblock %} {% block content %} <section> <center> <div class="container"> <div class="row"> <div class="col-md-6 p-b-30"> <form class="leave-comment" method="POST" id="trackerForm" action="#"> {% csrf_token %} <h4 class="m-text26 p-b-36 p-t-15"> Track Your order </h4> <div class="bo4 of-hidden size15 m-b-20"> <input class="sizefull s-text7 p-l-22 p-r-22" id="orderId" type="text" name="orderId" placeholder="Order Id" required> </div> <div class="bo4 of-hidden size15 m-b-20"> <input class="sizefull s-text7 p-l-22 p-r-22" id="email" type="email" name="email" placeholder="Email Address" required> </div> <div class="w-size25"> <!-- Button --> <button class="flex-c-m size2 bg1 bo-rad-23 hov1 m-text3 trans-0-4"> Track your Order </button> </div> </form> </div> </div> </div> </center> <div class="container1"> <div class="row"> <div class="col-md-6 p-b-30"> <h4 class="m-text26 p-b-36 p-t-15"> Track order </h4> <ul class="list-group" id="track"> </ul> </div> </div> </div> <div class="container1"> <div class="row"> <div … -
How to post the multi selected ids to the table consisting ManyToManyField in django?
I am having 4 bootstrap cards consisting of some goals the user can selected any number of goals so I had the users model and goals model like this class users(models.Model): email=models.CharField(max_length=50,default='0000000') password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) goal = models.ManyToManyField(goals) class goals(models.Model): id=models.IntegerField(primary_key=True) goal = models.CharField(max_length=50,default='0000000') And my goals display html page is <div class="row"> {% for j in goal %} <div class="col-4" onclick="getGoal({{j.id}})"> <div class="card4 mt-3" id="room_{{j.id}}" style="width: 12rem; height:9rem;"> <center> <div class="card-body"> <p class="card-text mt-4" id="cont_{{j.id}}"><b>{{j.goal}}</b></p> </div> </div> </div> {% endfor %} </div> And onclick function written in javascript the clicked goals details are taken to an array now I want to take only the ids in the js array and want to send as an value in the form to database and my form.html is <form action="{% url 'car:user_register' %}" method="POST" > {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control" required> </div> <div class="form-group"> <label for="room">room</label> <input type="number" name="room" id="name" value=""> </div> <div class="form-group"> <label for="goal">goal</label> <input type="number" name="goal" id="goal" value=""> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" required> </div> <div class="form-group"> <label for="password2">Password</label> <input type="password" name="password" class="form-control" required> </div> <input type="submit" value="Register" class="btn btn-secondary btn-block"> </form> And my view is def user_register(request): … -
Set-Cookie is not working in Chrome - with two websites
I have a problem with Set-Cookie not working in Chrome (I didn't check other browsers). It worked in the past but it stopped working recently. I have two websites with two domain names, and I need to set the cookie in both websites. I'm calling a URL in each of the domain names to set the cookie. But it doesn't set the cookie on the other website (the website I'm not browsing now). The users login or logout or sign up to one website, and I want them to login or logout from the other website too, automatically. Currently if they login or logout to one website, it doesn't affect the other website. The Django view code is: @csrf_exempt def set_session(request): """ Cross-domain authentication. """ response = HttpResponse('') origin = request.META.get('HTTP_ORIGIN') if isinstance(origin, bytes): origin = origin.decode() netloc = urlparse(origin).netloc if isinstance(netloc, bytes): netloc = netloc.decode() valid_origin = any(netloc.endswith('.' + site.domain) for site in Site.objects.all().order_by("pk")) if (not (valid_origin)): return response if (request.method == 'POST'): session_key = request.POST.get('key') SessionStore = import_module(django_settings.SESSION_ENGINE).SessionStore if ((session_key) and (SessionStore().exists(session_key))): # Set session cookie request.session = SessionStore(session_key) request.session.modified = True else: # Delete session cookie request.session.flush() response['Access-Control-Allow-Origin'] = origin response['Access-Control-Allow-Credentials'] = 'true' return response And the … -
Pass URL variables and use it for queries
The initial flow of the app is like this: User clicks a language Url fires a GET request based on the id of the language given Returns and displays all frameworks that are related to the given language Without DRF, it would look something like this: views.py: def frameworks_from_language(request, language_id): language = Language.objects.get(pk=language_id) if language == None: # Do some stuffs frameworks = language.framework_set.all() template = 'app/language.html' context = { 'frameworks': frameworks } return render(request, template, context) And in urls.py: path('language/<int:language_id>', views.frameworks_from_language, name='getframeworks') This would return a template with an object frameworks that you could just simply display in a for-loop. However I have no idea on how to do something like this on DRF. I tried this (as suggested by a friend): serializers.py class LanguageRelationSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ('frameworks',) extra_kwargs = { 'frameworks': { 'source': 'framework_set', 'many': True } } views.py class SelectedLanguageViewSet(ReadOnlyModelViewSet): queryset = Language.objects.all() serializer_class = LanguageRelationSerializer And in urls.py router.register('selected-language', views.SelectedLanguageViewSet) But it doesn't seem to work. It would just display something like this: { "count": 3, "next": null, "previous": null, "results": [ { "frameworks": [ 3 ] }, { "frameworks": [ 2 ] }, { "frameworks": [] } ] } I … -
Error in Django when I play uploaded media files through media url
Here is my models.py file : class ForumThread(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.CharField(max_length=500) thread_video = models.FileField(upload_to='forum_videos') slug = models.CharField(max_length=200, editable=False, blank=True) def __str__(self): return str(self.owner) + '-' + str(self.title) Here is my FormView Code which I am using to upload videos along with other model data : def handle_uploaded_file(f): with open('media/forum_videos/' + str(f), 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class CreateThread(FormView): form_class = ThreadForm template_name = 'forum/create_thread.html' success_url = 'home' def form_valid(self, form): forum_obj = form.save(commit=False) forum_obj.owner = self.request.user forum_obj.slug = slugify(forum_obj.title) handle_uploaded_file(self.request.FILES['thread_video']) forum_obj.save() return HttpResponseRedirect(reverse('blog:list')) def form_invalid(self, form): print('Some errors occurred..') return HttpResponse('Some errors on the page') And here is the error I'm getting when I open an uploaded video through media url. For example : http://localhost:8000/media/forum_videos/16.Using_value_counts.mp4 and obviously, this error is also occurring on the detail page where I want to show video with other details of the model post. I also encountered the same error with 'Audio' files in one of my other Django Projects. Any idea about how to fix this ? Any help from seasonal Django users would be much appreciated, I am kind of stuck. 11/Dec/2019 21:27:53] "GET /media/forum_videos/16.Using_value_counts.mp4 HTTP/1.1" 200 7405568 Traceback (most recent call last): … -
use URL passed values in django views and render it to template
Views.py class citydetailview(generic.DetailView): #Generic class-based list view for a list of authors. model = City def get_city_value(request, pk): mycity=City.objects.all() if pk==1: hyd=Type_city1.objects.all() elif pk==2: hyd=Type_city2.objects.all() elif pk==3: hyd=Type_city3.objects.all() return (request,{'hyd':hyd}) urls.py path('city/<int:pk>', views.citydetailview.as_view(), name='city_ads_detail'), I want to use the 'pk' value from the url.py in one of my class and render the output accordingly to template -
I can't get Django with reCaptcha v2 and django-cors-header to work
Here's what I have in the settings.py file. ALLOWED_HOSTS = ['host_created_prod.elasticbeanstalk.com', 'www.publicfacingwebsite.com', 'host_created_test.us-east-2.elasticbeanstalk.com', 'localhost', '127.0.0.1'] CORS_ORIGIN_ALLOW_ALL = False INSTALLED_APPS = [ 'corsheaders', 'pages.apps.PagesConfig', ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ... CORS_ORIGIN_REGEX_WHITELIST = [ 'http://localhost:8000', r'https://www.google.com/recaptcha/api/siteverify*', ] CORS_URLS_REGEX = r'^/api/.*$' This is the JS code I'm using: reCaptchaUrl = "https://www.google.com/recaptcha/api/siteverify?secret=".concat(secret_key, '&response=', response); This is the URL: https://www.google.com/recaptcha/api/siteverify?secret=<MY SECRET KEY>&response=<RESPONSE CODE> However this is the error message I'm getting: Response Headers: HTTP/1.0 200 OK Date: Thu, 12 Dec 2019 03:19:51 GMT Server: WSGIServer/0.2 CPython/3.6.4 Content-Type: text/html; charset=utf-8 X-Frame-Options: SAMEORIGIN Content-Length: 41154 Request Headers: Host: 127.0.0.1:8000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:70.0) Gecko/20100101 Firefox/70.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Upgrade-Insecure-Requests: 1 This is the error message I'm getting: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/recaptcha/api/siteverify?secret=<SECRET KEY>&_=1576120792258. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Please help. I've been stuck for a couple of hours. -
How to find which database entry has been created using celery task id
In one of my celery tasks, I'm creating database entries. I know how to read the status of my celery tasks : from celery.result import AsyncResult res = AsyncResult("my-task-id") res.ready() But I want to know that exactly which database entry was created on a specific task by using a celery task ID. How can I do this? Thanks in advance. -
Request URL was not found, Django deployed
I have a project where a user can upload an image and then, the server display it. I have not problems in the production phase but when I upload my project to the server, this images are not displayed and when I click in the alt tag image I get redirected to a NOT FOUND page. Note that the URL is right: www.example.com/media/news_img/img.png Project folder server templates static media news_img img.png This just works when I enable Debug mode HTML <a href="{{ news_f.news_img.url }}"><img src="{{ news_f.news_img.url }}" alt="{{news_f.news_tittle_es | safe}}"></a> I've seen this problem so many times but the solutions are from 2010-2013, I'm currently working on Djangno 2.7. I've tried: Images from ImageField in Django don't load in template -
ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
When I am trying to django server using "python3 manage.py runserver", its showing me the following error: ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' I am using django: 2.2.5 python: 3.7.5 Can anyone suggest, what i am missing out? -
How to filter images?
The truncatechars and safe filters work the way I want the problem is the image shows up too in my descriptions and I don't want images to show up like they do in this image. https://i.imgur.com/KjcX5NQ.png {% for post in post_entries %} <div class="post-preview"> <h3 class="post-subtitle">{{ post.post_text|truncatechars:125|safe }}</h3> </div> {% endfor %} <h3 class="post-subtitle"><p><img alt="" src="./Journal_files/1555448282201.jpg" style="float:right; height:155px; width:55px">"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrup…</p></h3> </a> -
Django Subquery Multiple OuterRef
I am trying to annotate a queryset with an aggregate of a subset of previous rows. Take the following example table of a player's score in a particular game, with the column, last_2_average_score being the rolling average from the previous two games score for a particular player. +----------+-----------+---------+-------------------------+ | date | player | score | last_2_average_score | +----------+-----------+---------+-------------------------+ | 12/01/19 | 1 | 10 | None | | 12/02/19 | 1 | 9 | None | | 12/03/19 | 1 | 8 | 9.5 | | 12/04/19 | 1 | 7 | 8.5 | | 12/05/19 | 1 | 6 | 7.5 | +----------+-----------+---------+-------------------------+ In order to accomplish this, i wrote the following query, trying to annotate each "row" with the corresponding 2 game average for their score ScoreModel.objects.annotate( last_two_average_score=Subquery( ScoreModel.objects.filter( player=OuterRef("player"), date__lt=OuterRef("date") ) .order_by("-date")[:2] .annotate(Avg("score")) .values("score__avg")[:1], output_field=FloatField(), ) ) This query however, does not output the correct result. In fact the result is just every record annotated with {'last_two_average_score': None} I have tried a variety of different combinations of the query, and cannot find the correct combination. Any advice that you can give would be much appreciated! -
Django HStoreField different output from shell
here is my sample model class PaymentPlan(TimeStampedModel): payment_list = HStoreField( _('payment dates'), null=True, blank=True ) shell_plus In [3]: i=EnrollmentInfo.objects.get(pk=580441) In [4]: i.payment_plan.payment_list Out[4]: '"Invoice-1"=>"2019-07-31"' <--- str In [5]: e=EnrollmentInfo.objects.get(pk=580441) In [6]: e.payment_plan.payment_list Out[6]: {u'Invoice-1': u'2019-07-31'} <---dict im having an error on my code because i was expecting the hstorefield to be a dictionary. -
How to use firebase and SQL Server together?
What would be the best approach to connect SQL Server and Firebase? The purpose of the app would be to pull data and display on the browser. I've found resources about MYSQL with Firebase using Node, but wondering how I would do the same with SQL Server (preferably using a Python based app) -
Showing default nginx page instead of application
settings.py: ALLOWED_HOSTS = ['64.225.1.249', 'domain.az'] nginx: server { listen 80; server_name domain.az; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/progbash/ccproject; } location / { proxy_set_header Host $host; include proxy_params; proxy_pass http://unix:/home/progbash/ccproject.sock; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; } } error: 2019/12/12 02:51:50 [crit] 23765#23765: *1 connect() to unix:/home/progbash/ccproject.sock failed (2: No such file or directory) while connecting to upstream, client: 188.253.227.99, server: domain.az, request: "GET / HTTP/1.1", upstream: "http://unix:/home/progbash/ccproject.sock:/", host: "domain.az" 2019/12/12 03:05:57 [alert] 24056#24056: *12 open socket #3 left in connection 4 2019/12/12 03:05:57 [alert] 24056#24056: *13 open socket #11 left in connection 5 2019/12/12 03:05:57 [alert] 24056#24056: aborting 2019/12/12 03:09:16 [alert] 24143#24143: *11 open socket #11 left in connection 3 2019/12/12 03:09:16 [alert] 24143#24143: *12 open socket #12 left in connection 5 2019/12/12 03:09:16 [alert] 24143#24143: aborting Although I have project.sock in the shown location, I've bought domain, connected DigitalOcean's DNS Servers, set up everything as in DigitalOceans's official manual. But still seeing this trashy nginx default page instead of application. -
How to download export csv file like a save as button (data send from ajax request)
So i want to export a csv file from query (the parameter i send with the ajax function) in database with django , i already follow the documentation , and it seems success, but the browser didnt have anything like save as .csv file and i dont see my file been created by the system here's the code html code <form class="form-horizontal style-form" action="#"> <div class="form-group"> <label class="control-label col-md-3">Database Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <!-- <li><a href="#"></a></li> --> {% for table in obj2 %} <option value = "{{table}}" >{{ table }}</option> {% endfor %} <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> <div class="form-group"> <button class="btn btn-theme" onclick="return appendBox()">Add</button> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4" id ="test"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> <div class="form-group"> <button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button> <label class="control-label col-md-3">Filter</label> <div class="col-md-4" id="filtbox"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> </select> <select id="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> <option> > </option> <option> < </option> <option> ≥ </option> <option> ≤ </option> <option> = </option> </select> <input id="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> </input> </div> </div> </div> </div> <div class="form-group"> <div class="col-md-4" id="showquery"> <div … -
How to implement a manual security procedure with Djano
I'm writing a web application with Django framework. This web application is API based and I'm using Django rest_framework. I have a security issue: On the first page, the user must solve a Recaptcha. After solving the Recaptcha my site gives a session ID to the user and after this, the user must post this session ID in the body of all his/her API calls and every API can be called just once with a specific session ID. In other words, I have a state machine for the APIs being called by the user and in each state, the user can call the APIs which have corresponding outgoing edges from that state. The purpose of all of the above procedures is preventing the user from crawling my website. (User can't call an API many times with a session ID and he/she should act as a normal user and call every API at most two or three times) Now my question is that how should I handle this in my Django app? Before this, I've just used the ordinary Django session middleware for handling sessions. Now should I handle the authentication process and passing and getting session ID completely in a … -
ModuleNotFoundError No module named 'Home'
I am facing no Module found error in Django, please help. My Home URL- urlpatterns = [ path('login', views.home, name="homePath"), enter code here ] Project Settings - urlpatterns = [ path('admin/', admin.site.urls), path('', include('InsertPage.urls')), path('Home/', include('Home.urls')), ] Only Home path is throwing error rest of the paths are working fine. -
How to show in the Django administration only the data corresponding to the current user's company
I'm developing a project in Django. I have several registered companies, and all models are based on the company. My question is this: how can I do that when a user enters the administration can only see the data of their company. models.py class Company(models.Model): name = models.CharField(max_length=100) country = models.CharField(max_length=100) class XUser(User): phone = models.CharField(max_length=20, null=True, blank=True) card = models.CharField(max_length=20, null=False, blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.nombre class Book(models.Model): user = models.ForeignKey(XUser, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=30) For example, when a user enters the administration they can only see the books that belong to their company. Thanks in advance. -
How could I set the default time for the datetimepicker that should be save on the database
How could I set the default time for this datetimepicker, right now when i save it to the database it shows the YYYY-MM-DD-00:00:00 format. I wanted to set to YYYY-MM-DD-00:59:59 $(document).ready(function(){ $(".dtpicker").datetimepicker({ format: "YYYY-MM-DD", useCurrent: false, icons: { next: 'fa fa-angle-right', previous: 'fa fa-angle-left' } }) -
'admin_static' is not a registered tag library
When going to /admin I am getting the folowing error. I believe this is being caused by djangosuit. TemplateSyntaxError at /admin/ 'admin_static' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static suit_forms suit_list suit_menu suit_tags tz