Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
This site can’t be reached localhost refused to connect. ERR_CONNECTION_REFUSED
Hello i have the weirdest bug ever : yesterday in the morning i was using my program without any issues (web application made with Django + react/redux & javascript). After some bugs i decide to take again from scratch so i clone the git then i am trying to relaunch my app and i have this : However i have no issues when i launch my app : Backend : Frontend : and the weird thing is i can't see any proccess running on port 8000 of my computer : and the code which is on git was working perfectly like 2 days ago so if someone got an idea i would like to hear it. -
Selecting a favourite image from a list of associated images in Django Models
I have the following AlbumImage model which is for the images my users upload: ` class AlbumImage(models.Model): image = ProcessedImageField(upload_to='albums', processors=[ResizeToFit(1280)], format='JPEG', options={'quality': 70}) alt = models.CharField(max_length=255, default=uuid.uuid4) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=70, default=uuid.uuid4, editable=False) ` and the model of people who might appear in the aforementioned pictures: ` class People(models.Model): name = models.CharField(max_length=30,default='John Doe') remind_on = models.DateField() event = models.TextField(default='No Event') associated_with = models.ManyToManyField(AlbumImage) ` Problem: I want my user to be able to select one of the images from the many associated images. How do I represent that in my models? -
Django python hangs during threading operation
I'm running a migration script in Django which is supposed to loop but ends up hanging and halting ipdb (which I have set up breakpoints with in the code). As it stands, it imports one line of the json file to be imported and doesn't deal with the rest. When it gets to the breakpoint, I can step through all the way until /usr/lib/python3.6/threading.py(1268)enumerate() when ipdb stops entirely (I can't quit it with q or CTRL + C or CTRL + D or anything). Calling locals() just before it halts returns {} My importation script blocks.py has a breakpoint about 2/3 through at line 112. Any help most welcome! blocks.py def process(self): for item in self.source_data: if item["visibility"] == '0' or item["pages"] == '': return else: pages = [item["pages"]] # Turns list of urls into list of ids # TODO ensure that Wagtail can handle taxonomy # and node numbers if "\r\n" in pages[0]: pages = pages[0].split('\r\n') for page in pages: if page.startswith('node'): pages[pages.index(page)] = page.strip('node/') elif page.startswith('taxonomy/term/'): pages[pages.index(page)] = page.strip('taxonomy/term/') else: if pages[0].startswith('node'): pages = [pages[0].strip('node/')] elif pages[0].startswith('taxonomy/term/'): pages = [pages[0].strip('taxonomy/term/')] data_dict = {} region = item["region"] body = self.convert_rich_text(item['body']) if (region == "highlight_bar" or region == "topnav" or … -
One view two pages DJANGO signup with verification
can anyone suggest a best way to get my code work I have created a signup view where the logic looks like this def signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) verify=VerificationForm(request.POST) print(verify) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] email = userObj['email'] password = userObj['password'] and here is the signup.html {% extends 'question/index.html '%} {% block body_block %} <div class="conrainer"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <a href="{% url 'social:begin' 'facebook'%}">facebook auth</a> </div> {% endblock %} and i want when the user clicks on submit he must be redirected to another page like verfication.html where user must submit the six digits code and when he clicks submit then the usercreation logic should takes place if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): User.objects.create_user(username, email, password) user = authenticate(username = username, password = password) login(request, user) return HttpResponseRedirect('/') else: raise forms.ValidationError('Looks like a username with that email or password already exists') else: raise forms.ValidationError('Looks like form is invalid') else: form = UserRegistrationForm() return render(request, 'question/signup.html', context= {'form' : form }) can anyone suggest me the best way to make this happen any kind of help is appreciated thanks in advance -
"Uncaught SyntaxError: Unexpected identifier" in Javascript in Django Template
I'm building a Dajngo Weather App, where there is a search input field and and by writing city name in input we can get weather details in console for now. But when typing any city name in input form, its showing "Uncaught SyntaxError: Unexpected identifier" error in console. I am unable to debug this error. models.py class City(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name forms.py class CityForm(forms.ModelForm): class Meta: model = City fields = ('__all__') urls.py urlpatterns = [ path('ajax5',views.ajax5view) ] views.py def ajax5view(request): return render (request,'ajax5.html') ajax5.html <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script src="{% static 'js/ajax5.js' %}" type="text/javascript"> </script> </head> <body> <form method="GET" action=""> <span><input type="text" name='city_name' id="city" placeholder="Search: city_name" value="{{ request.GET.get }}"/></span> <span><input class="btn btn-primary btn-sm" type="submit" value="Search" ></span> </form> </form> </body> </html> javasript(ajax5.js) $(document).ready(function(){ $('.btn').click(function(){ var city = $('#city').val(); $.ajax({ url: 'https://api.openweathermap.org/data/2.5/forecast?q='+ city +'&appid=026b9c980571390d69406536cdaaccea', method : 'GET', dataType: 'json' success: function(data){ console.log(data); } }) }); }); -
Maps is not displaying in admin site using geodpositions
Django: 2.0.7 django-geopositions: 0.3.0 I have configured everything in SETTINGs but map does not show at admin site, only lat and long fields are shown. My model is very simple as: class Shop(models.Model): name = models.CharField(max_length=100) position = GeopositionField() Any idea? -
Heorku - Can't connect to local MySQL server
I have deployed my project containing Django Rest-framework Reactjs to Heroku using this medium post as reference. Now, I have my code in deploy-heroku branch so I did: git push heroku deploy-heroku:master Now, the build was successful but the deployment got failed. Here's the traceback Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") 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/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 57, in _run_checks issues = run_checks(tags=[Tags.database]) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in … -
Filter items in manyToManyField according to the selected option from the ForeignKey list
I have a need for filtering that filters a group of elements, not by name but by another field. screenshot In the screenshot there is a field material when you select an item from this list in the bottom list, the items should be filtered by the group, depending on what was selected in the field material Example: in the lower selection there is such a list, and they have the field material. When you select from the material oak field, only the first 2 elements must remain. name = white, material = Oak name = Red, material = Oak name = purple, material = Metal name = glossy, material = Metal Django as I understand there is already an implementation of such filtering is not inlines and just using list_filter, but unfortunately in the inlines form it does not work( Perhaps you can somehow use or write your widget. But maybe there are ready-made solutions? Or I something not so understand. -
Django admin title "Select <model_name> to change"
How can I change the title for Django admin specfic model? Automatically it write "Select to change"... I am try each from this options but do nothing: admin.site.site_header = "aaa" admin.site.site_title = "bbb" admin.site.index_title = "ccc" -
How do I pass data from the views.py backend to html template frontend in Django?
I am very new to coding and Django and have read the documentations but couldn't seem to figure out the answer, your guidance would be greatly appreciated! I have variables in my Django views.py file and want to pass it into my template file so it can be displayed in html. How do I do that? For example, in views.py list = [2,5,10,"string,99] And I wish to this use list in my frontend HTML or javascript -
Django Admin Search DateTime Field without miliseconds
I have Django instance with postgres. By default with this configuration DateTimeFields in Django are saved with miliseconds. # models.py class LogModel(models.Model): date_logged = models.DateTimeField( "Logged", auto_now_add=True ) # admin.py class LogAdmin(admin.ModelAdmin): list_display = ('date_logged',) search_fields = ('date_logged') I'd like to search in date_logged field without including milliseconds or searching by this field while it has custom datetime format. Is there any easy way to do it? -
Django model design issue with relationship
I have an problem where I can’t decide how to design the models for the following scenario I want to create a companies table that will hold a list of companies. This table will have a comment field in it I want that comment field to be able to hold multiple comments that are dated A company can have multiple comments but a comment can only belong to only one company Here the Comments table class Comments(model.Models): date = models.DateField(auto_now_add=True) comment_text = models.TextField(required=True) If I create the Companies table like this; class Companies(models.Model): name = models.CharField(max_length=30) country = models.CharField(max_length=30) comment = models.ForeignKey(Comments, on_delete=models.SET_NULL, null=True) Then I can only attach one comment to one specific row of the Companies table If I create the Companies table like this; class Companies(models.Model): name = models.CharField(max_length=30) country = models.CharField(max_length=30) comment = models.ManyToManyField(Comments) Then a comment can belong to multiple companies which I don’t want. In the Django documentation https://docs.djangoproject.com/en/2.0/topics/db/examples/ there is only one other options left which is the one-to-one mapping and this is clearly not what I want. How can achieve what I want ? -
Use Django ORM values and call member functions
I have below model in my Django app. class Revenue(models.Model): from_a = models.IntegerField() from_b = models.IntegerField() def get_total(self): return self.from_a + self.from_b Now I am retrieving data using Revenue.objects.filter(from_a__gt = 10).values('from_a', 'from_b'). From the above queryset I am getting values, now I want to call get_total function on objects. I didn't found a way to call that function. Is there a way to retrieve the data only I needed using values and also can call member_functions of that objects? Revenue.objects.filter(from_a__gt = 10) should not be the solution if I have 100s of columns for my model. -
Authentication for class based views in Django
class AdminView(generic.ListView): model = get_user_model() fields = ['first_name', 'username', 'is_active'] template_name = 'users/admin.html' class AdminUpdateView(UpdateView): model = get_user_model() fields = ['is_active'] template_name = 'users/user_update.html' success_url = reverse_lazy('users:admin') There are two views in django which I have created and I want them to be accessed only when the admin/staff logins. How do I go about it? -
Invalid block tag on line 1: 'set'. Did you forget to register or load this tag
page.html {% set x = 5 %} I am getting below error when running the website. Invalid block tag on line 1: 'set'. Did you forget to register or load this tag? -
Change way2sms otp verification service to the msg91 message service
We have a Django project in which we need to change way2sms otp verification service to the msg91 message service. The code needing to be changed is given below: (I am a beginner in Django framework. Please help me to resolve this problem. MSG91 message service website API documentations can be found here.) def trainer_verify(request): request.session["first_name"] = request.POST["first_name"] request.session["last_name"] = request.POST["last_name"] request.session["phone"] = request.POST["phone"] request.session["email"] = request.POST["email"] request.session["train"] = "true" # request.session["skills"] = request.POST["skills"] # request.session["experience"] = request.POST["experience"] # request.session["language"] = request.POST["language"] # request.session["date"] = request.POST["date"] # request.session["city"] = request.POST["city"] # request.session["address"] = request.POST["address"] r = random.randint(1111,9999) sms_OTP = str(r) r = random.randint(1111,9999) email_OTP = str(r) username = "9629493491" passwd = "aviakash.96" message = sms_OTP number = request.POST["phone"] message = "+".join(message.split(' ')) url = 'http://site24.way2sms.com/Login1.action?' data = 'username='+username+'&password='+passwd+'&Submit=Sign+in' data = data.encode('utf-8') cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) opener.addheaders = [('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')] try: usock = opener.open(url, data) except IOError: print ("Error while logging in.") sys.exit(1) jession_id = str(cj).split('~')[1].split(' ')[0] send_sms_url = 'http://site24.way2sms.com/smstoss.action?' send_sms_data = 'ssaction=ss&Token='+jession_id+'&mobile='+number+'&message='+message+'&msgLen=136' send_sms_data = send_sms_data.encode('utf-8') opener.addheaders = [('Referer', 'http://site25.way2sms.com/sendSMS?Token='+jession_id)] try: sms_sent_page = opener.open(send_sms_url,send_sms_data) except IOError: print ("Error while sending message") fromaddr = 'avinashravi96@gmail.com' toaddrs = str(request.POST["email"]) # container = MIMEBase('multipart', … -
Music website with Django Framework
I am trying to make a music streaming website with django framework. Also i have a music steaming templates from bootscrap link : https://w3layouts.com/mosaic-entertainment-category-flat-bootstrap-responsive-web-template/ please help me further -
Django Runserver Without Workers
I'm hoping someone knows off the top of their head... but how do I use runserver without the 4 default channel workers for Django? I have seen it somewhere before but can't find the arguments anywhere... I only want the request listener to start since I am scaling workers from another image. -
How to url-reverse the delete url for an item in django rest framework
I am testing my delete item API, but i cannot determine how to get the URL for the delete request. I am using: Django==1.11.13 and djangorestframework==3.7.7 What is the right way to url_reverse for the DELETE request to <api-path>/favorite-items/1/ ? I am trying to url-reverse the delete of the item at: <api-path>/favorite-items/1/delete. url.py file: from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'favorite_item', FavouriteItemAPI, base_name='favorite-items') urlpatterns = router.urls i have tried also: view = FavouriteItemAPI() # extends the Destroy mixin and has a destroy method url = view.reverse_action('destroy', args=[request_instance, a1.id]) as it is described in documentation at: http://www.django-rest-framework.org/api-guide/viewsets/#reversing-action-urls -
JavaScript Reload Function Not Working Properly
On my webpage I have a piece of JavaScript to reload/refresh an iframe every three seconds. window.setInterval(function() { reloadIFrame() }, 3000); function reloadIFrame() { var frame = document.getElementById("iframe"); var len = frame.getElementsByTagName("TABLE").length; if ( len == 0 ){ console.log('reloading..'); document.getElementById('iframe').contentWindow.location.reload(); } } However, I don't want the function to work when there is a table present in the iframe, and it still runs when there is a table. Please let me know if there is something I am missing or your suggestions for alternative solutions. (I do believe that the iframe which I am referencing is local on localhost:8000. I'm working with Django, if that matters, and this is part of a template.) -
multivalue dictionary key error in django server
while I was writing my html form which takes input from drop down menu and in return it displays the machine learning code output to the user which is written Python Below is my html drop down code which contains the pin code of different cities and I also attached my j query code which is not working after alert response and whenever I am running my code on djang server it is displaying multi value dict key error: < script > $(document).ready(function() { $("select[name='pin code']").change(function() { var pin = $("#ptext").val(); $.get('/index', { pin: pin }, function(resp) { $("#nresult").html(resp); }); }); }); < /script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <form action="/action_page.php"> <h2>Enter your Pin Code:</h2><br> <select name="pin code"> <option value="282002">282002</option> <option value="211016">211016</option> <option value="202001">202001</option> <option value="223225">223225</option> <option value="244221">244221</option> <option value="206120">206120</option> <option value="276001">276001</option> <option value="131021">131021</option> <option value="271801">271801</option> <option value="221602">221602</option> <option value="271201">271201</option> <option value="210001">210001</option> <option value="224116">224116</option> <option value="243001">243001</option> <option value="272001">272001</option> <option value="244602">244602</option> <option value="243601">243601</option> <option value="203001">203001</option> <option value="232104">232104</option> <option value="210202">210202</option> <option value="274001">274001</option> <option value="204211">204211</option> <option value="206001">206001</option> <option value="224001">224001</option> <option value="202625">202625</option> <option value="212601">212601</option> <option value="283203">283203</option> <option value="110025">110025</option> <option value="283203">110093</option> <option value="233001">233001</option> <option value="271001">271001</option> <option value="273001">273001</option> <option value="177001">177001</option> <option value="241001">241001</option> <option value="285205">285205</option> <option value="222001">222001</option> <option value="284001">284001</option> <option value="209725">209725</option> <option value="206246">206246</option> <option value="208001">208001</option> <option value="207123">207123</option> <option value="210209">210209</option> <option … -
I want to edit my product details Django
I am trying to edit the details I gathered using a form with POST method now I want to edit those details. I tried it but it is not working can you guys tell what am I doing wrong ? View of edit post @login_required() def edit_product(request, product_id): form = NewPro() edit = get_object_or_404(Product, product_id) if request.method == 'POST': form = NewPro(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('product') else: form = NewPro() return render(request, "default/edit.html", {'form': form, 'edit': edit}) Url pattern path('<int:product_id>/edit_product', views.edit_product, name='edit_product') Html where I am trying to add the button {% extends 'default/dashboard.html' %} {% block content %} <h1>Products Details </h1> <p>These are the details of your product, {{ user.username }}</p> <ul> <li>{{ product_details.name }}</li> <li>{{ product_details.price }}</li> <li>{{ product_details.category }}</li> <li>{{ product_details.store }}</li> <li>{{ product_details.user }}</li> </ul> <a href={% url 'edit_product' edit_details.id %}> <button>Edit Product</button> </a> {% endblock %} Html where I am trying to show the form {% extends 'default/dashboard.html' %} <html> <head><title>E-Commerce App</title></head> {% block content %} <h2>Edit Product</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> {% endblock %} </html> -
Why is my virtual environment runs system Python 2.7 instead of virtual Python 3.6
I've created a Django project in a virtual environment, and venv was activated by PyCharm automatically, as usual. Everything was fine, but when I placed my project into another folder, Project Interpreter settings were corrupted because of old interpreter path. So now, when I provide a new path for the interpreter (and, of course, with activated venv), python runs from my base system location of version 2.7, not from venv. Check this: archeski@archeski-Inspiron-5558:~/Source/ecom/ecom$ source venv/bin/activate (venv) archeski@archeski-Inspiron-5558:~/Source/ecom/ecom$ python --version Python 2.7.15rc1 (venv) archeski@archeski-Inspiron-5558:~/Source/ecom/ecom$ python -c "import sys; print sys.executable" /usr/bin/python The same thing happened about a half year ago on Windows 10, and the solution was only to create a project in PyCharm from scratch and then move all the source, db and etc. Now, I'm running on Ubuntu 18.04 -
Uploading Django app to Python anywhere
I'm currently trying to upload my django app to pythonanywhere and i keep running into errors with my wsgi application, it says "sys" is not defined. I have correctly followed all the steps in the manual that pythonanywhere provides, yet it is still not working. I want to know if anyone has successfully uploaded a django app with pythonanywhere and how he/she got it done; or if there are better alternatives i can explore. Thanks. I would be waiting for an answer. -
How can I keep the text format the same way it was captured in the django admin
I would to know if its possible to render the text in the template and keep the same text format as the text was captured in the admin. I've attached a picture of my problem. As can be seem in picture below. The text is formatted in paragraphs and sometimes there is some bold text, the problem is that when the text is render to the template, all the formatting is removed. Thanking you in advance.