Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template how to fix error "Could not parse the remainder: '|' from '|' "
mydict = {"book1":["user1", "user2", "user3"], "book2":["user1", "user4", "user5"],} I want to check "Does user2 read book1?" in mydict in template, I do the following: {% if "user2" in mydict | get_item: "book1" %} However, i getting an error: " Could not parse the remainder: '|' from '|' ". How do I fix it? -
How to redirect url for CreateView in views.py
class A_modelCreateView(CreateView)in views.py path('create/'),view.A_modelCreateView().as_view(),name='create' in urls.py build an HTML as form for A_model form but not in its default directory(my_app/A_model.form) Is there filled parameter somewhere for redirect the url you want? -
Display all paragraphs of a scraped HTML div in Django
So I have a scraped HTML div from a news website. Which is this piece of HTML: <div class="cn-content"> <figure><img src="https://cimg.co/w/articles-attachments/1/5ca/71a090479e.jpg" sizes="(min-width: 640px) 720px, 100vw" srcset="https://cimg.co/w/articles-attachments/1/5ca/71a090479e.jpg 300w, https://cimg.co/w/articles-attachments/2/5ca/71a090479e.jpg 600w, https://cimg.co/w/articles-attachments/3/5ca/71a090479e.jpg 720w, https://cimg.co/w/articles-attachments/4/5ca/71a090479e.jpg 900w, https://cimg.co/w/articles-attachments/0/5ca/71a090479e.jpg 1337w" alt="OKEx Announced its First Token Sale via IEO 101" class="content-img"><figcaption>Source: iStock/baona</figcaption></figure> <p>Major cryptocurrency exchange <b>OKEx</b> has announced an initial exchange offering (IEO) for the <b>BLOC</b> token, on their newly-presented OK Jumpstart token sale platform. The sale marks the first such endeavor of the exchange, joining the likes of <a href="https://cryptonews.com/ext/binance/" target="_blank" rel="nofollow noopener">Binance </a>and <a href="https://cryptonews.com/ext/bittrex/" target="_blank" rel="nofollow noopener">Bittrex </a>in the so-called killer app club.</p> <p>The token in question is BLOC, native to the <b>Blockcloud</b> blockchain, and the sale is set to start at AM 12:00 UTC on April 10th. “Combining the advantages of blockchain and Future Internet technology, it reconstructs the technology layers below where current blockchain networks and Internet applications operate,” explains the project’s website. In short, it is a blockchain-based TCP/IP architecture, where TCP/IP is a suite of communication protocols used to interconnect network devices on the internet. </p> <p>The token sale uses a subscription + allotment approach. Users will have a timeframe of 30 minutes to subscribe, and allotment will be … -
Django Updateview not saving when in html but saves in admin
I have a big form, some fields, depends on other fields value to compute. Since so, i used jquery blur to submit the form each time user done editing a field and redirect it to updateview again with new values. I have this day_absent and amount absent to test this. If i just put form.day_absent in the form and put object.amt_absent, it doesnt save the form. But if i put form.amt_absent, it saves the form. Why is that? I do not wish to put amt_absent as editable, it should just be the day_absent. class PayrollTransactionUpdate(LoginRequiredMixin,UpdateView): model = t_pay template_name = 'payroll/transaction/update.html' fields = [ 'day_absent', 'amt_absent', ] <div id='input-item' class="col-1"> {{ form.day_absent }} {{ form.day_absent.errors}} </div> <div id='item' class="col-2"> {{ object.amt_absent }} </div> -
How to send socket messages via Django views when socket server and views.py are split into two files?
Env: Python 3.6, and Django 2.1 I have created a Django website and a socket server, and files are organized like this: web ... user (a Django app) __init__.py views.py ... server.py Actually I want to build a umbrella rental system by using django, and server connects to umbrella shelf via multi-thread socket (sending some messages). Like I press the borrow button, and views.py can call the server test_function and send some messages to the connected umbrella shelf. I can import server variables or functions in views.py, but I cannot get the right answer while server.py is running. So I want to ask you if you could give me some advice. Thanks a lot! By the way, I tried to import the global variable clients directly in views.py, but still got []. server.py defines a multi-thread server, which is basically as below: clients = [] class StuckThread(threading.Thread): def __init__(self, **kwargs): self.name = kwargs.get('name', '') def run(self): while True: # do something def func1(self): # do something def test_function(thread_name): # if the function is called by `views.py`, then `clients = []` and return 'nothing', but if I call this function in `server.py`, then I can get a wanted result, which is … -
Scan QR codes in a Django app with phone devices
I want to write an app in Django that scans a QR code using a mobile phone . Is it possible or I would have to write it in something like lonic ? -
NoReverseMatch at /index/ 'tab11' is not a valid function
I have used 1*1 tab11.html is in my app called story/templates/story/tab11.html if i use path('index/tab11.html/' ,views.tab11,name='tab11'), it works when views.tab11 contains only one line that is return render(request,tab11.html) please help me solve the problem such that my url-index/tab11 gets me the ouptut the url file is:path('index/tab11/', views.tab11, name='tab11') but i am getting NoReverseMatch at index.Reverse for 'tab11' not found. 'tab11' is not a valid view function or pattern name. my traceback is: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/index/ Django Version: 2.1.7 Python Version: 3.5.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'story', 'pages', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template D:\Yashvi_Django\Imagualization_copy\story\templates\story\create_9.html, error at line 80 Reverse for 'tab11' not found. 'tab11' is not a valid view function or pattern name. 70 : <div class="container"> 71 : 72 : </div> 73 : <h2 align="center">Select the Cell Layout for your Story/poem:</h2> 74 : 75 : <table align="center"> 76 : <!-- Row 1--> 77 : <tr> 78 : 79 : <td > 80 : <div class="divclass" id="div1" ><h2 id="tab1"><a href= {% url 'tab11' %} >1*1</a></h2></div> 81 : </td> 82 : <td > 83 : <div class="divclass" id="div2"><h2 id="tab21"><a href="tab21.html">2*1</a></h2></div> … -
Save form with foreignkey
i tried a few things out i have found here and around the Internet but i stuck. i try to save a form that one of the fields is a foreignKey. the problem is i want to have a charField to type in so if the group name is not already in the database, then to create it and save the form. my model from django.db import models from django.utils import timezone import datetime # Create your models here. class Ideas_Group(models.Model): category_text = models.CharField(max_length=30, unique=True) # votes = models.IntegerField(default=0) def __str__(self): return self.category_text class Idea(models.Model): idea_title = models.CharField(max_length=30) idea_text = models.CharField(max_length=200) idea_repo = models.URLField(max_length=80, blank=True, null=True) idea_owner = models.CharField(max_length=30, blank=True, null=True) idea_status = models.CharField(max_length=30, blank=True, null=True) pub_date = models.DateTimeField('date published', auto_now_add=True) group = models.ForeignKey(Ideas_Group, on_delete=models.CASCADE) def __str__(self): return "%s by %s => %s" % (self.idea_title, self.idea_owner, self.idea_text) def was_published_recently(self): now = timezone.now() return now >= self.pub_date >= now - datetime.timedelta(days=1) and the form.py class IdeasForm(forms.ModelForm): idea_title = forms.CharField(widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder':"do you have a name for your idea", 'aria-describedby':"basic-addon1",})) idea_text = forms.CharField(widget=forms.Textarea(attrs={ 'class':'form-control', 'placeholder':"what s the idea man", 'aria-describedby':"basic-addon1", 'rows':"10"}), max_length=200,) group = forms.CharField(widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder':"Category", 'aria-describedby':"basic-addon1",})) group_new = forms.CharField(widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder':"Category", 'aria-describedby':"basic-addon1",})) idea_repo = forms.URLField(widget=forms.URLInput(attrs={ 'class':'form-control', 'placeholder':"repo", 'aria-describedby':"basic-addon1",}), required=False) #def … -
how to rectify this error in polls.urls.py
i'm creating a poll app in my Django project named secondtry.i mapped my app.url to my views.py.i also updated my project.url.what does the below error mean django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django show error in form that comes from another function
I am trying to post a ModelForm, but after the is_valid() function, I run another validation coming from another function. What I want to do is, if the result of the other function is false, the form should raise an error, above the form as in the case "your password cannot be the same". Since the function runs during the process, I cannot use a clean method in model. Thanks in advance! function def somefunction(): . . print ("NOT WORKING") return False views.py def index(request): form = SomeForm(request.POST) if request.method == "POST": if form.is_valid(): if somefunction() == True: form.save() return HttpResponseRedirect("/contact/") else: form else: form return render(request, "home.html", {'form': form}) -
How can I add template view and the slug defining into one view?
So I am working on some Django but kinda new to it. I have this piece of code: from django.shortcuts import render, render_to_response, get_object_or_404 from .models import Article from django.views.generic import TemplateView def view_post(request, slug): return render_to_response('news/article.html', {'post': get_object_or_404(Article, slug=slug)}) class ArticleView(TemplateView): template_name = "news/article.html" def get(self, request): article = Article.objects.all() return render(request, self.template_name ,{'article': article }) How can I write this into one view so I can use it in my urls.py? Right now this is my urls.py: from django.conf.urls import url, include from .views import view_post urlpatterns = [ url(r'^blog/view/(?P<slug>[^\.]+)', view_post , name='view_blog_post'), ] How can I add them together? Because I also want the variables to be available in my template. -
How to send and consume json messages using confluent-kafka in Python
I am fairly new to Python and getting started with Kafka. So I have setup a Kafka broker and I am trying to communicate with it using confluent-kafka. I have been able to produce and consume simple messages using it, however, I have some django objects which I need to serialize and send it ti kafka. Previously I was using kafka-python, on which I was able to send and consume json messages, however I was having some weird issues it it. #Producer.py def send_message(topic,message) : try : try : p.produce(topic,message,callback=delivery_callback) except BufferError as b : sys.stderr.write('%% Local producer queue is full (%d messages awaiting delivery): try again\n' %len(p)) # Serve delivery callback queue. # NOTE: Since produce() is an asynchronous API this poll() call # will most likely not serve the delivery callback for the # last produce()d message. p.poll(0) # Wait until all messages have been delivered sys.stderr.write('%% Waiting for %d deliveries\n' % len(p)) p.flush() except Exception as e : import traceback print(traceback.format_exc()) #Consumer.py conf = {'bootstrap.servers': "localhost:9092", 'group.id': 'test', 'session.timeout.ms': 6000, 'auto.offset.reset': 'earliest'} c = Consumer(conf) c.subscribe(["mykafka"]) try: while True: msg = c.poll(timeout=1.0) if msg is None: continue if msg.error(): raise KafkaException(msg.error()) else: sys.stderr.write('%% %s [%d] at offset … -
How to mutually validate 2 fields in a form by validators in DJANGO?
I have 2 PositiveSmallIntegerField In 1 form and I need mutually validate them without reloading a page. For example 2nd field should always have greater number then first (1978>1950) . Django says that I have to use clean() method in forms but it is not appropriate in my case. This uses cleaned_data and leads to a page reloading. Is it possible to mutually validate fields just in the form itself by validators or something without reloading of a page. Thanks in advance! -
How to add custom form template in django admin
This code is working properly.But i want some form to write the subject and message in order to reply instead of defining subject message in the reply function. How can i add reply form for the reply acction in django admin page admin.py class ContactAdmin(admin.ModelAdmin): list_display = ['full_name','email','comment','time'] list_filter = ['time'] search_fields = ['name','comment'] readonly_fields = ['full_name','email','comment','time'] ordering = ['time'] actions = ['reply'] def reply(self,request,queryset): for reciever in queryset: send_mail('subject','message',settings.EMAIL_HOST_USER,[reciever.email],fail_silently=False) messages.success(request,'Your message has been replied successfully.') -
How to use .each() inside for loop with list?
I have a list I am trying to iterate over to change each div into a song of its own. The list I have is simplified by JSON because the data comes from a Django queryset. My problem is that I can't figure out how to continue to the next object without having it repeat the same one within the loop. I have tried setting variables outisde to stop it or go to the next song without success. The Json as data variable: [{"song":{"file":"music/the_unlighteds_2.mp3"}},{"song":{"file":"music/the_unlighted_6_32.mp3"}}] Script code: <script> $("h1[id]").each(function(){ var next_song = ""; var data = [{{ chap_song|safe }}] console.log(data); for (var i in data) { var next_song = JSON.stringify(data[i].song.file); } console.log(next_song); if(this.id==='scroll-to')$(this).html("<audio controls autoplay> <source src=https://theunlighted.io/media/"+next_song.replace(/\"/g, "")+ " type=\"audio/wav\"></audio>"); }); </script> -
Unit of measure for DATA_UPLOAD_MAX_MEMORY_SIZE
I'm interested in what unit of measure is represented by the 'DATA_UPLOAD_MAX_MEMORY_SIZE' variable in django settings. Is it bytes? Thanks! -
Running Django test tries to import module that was deleted
I have a Django project that I am trying to test. It had an app named 'people' that I have replaced with another app 'participant'. I have changed all of the settings needed, but why I runpython manage.py test, it won't run the tests because it can't import people, because I deleted it. Is there something I can delete or reset to remove all of the memory of previous test runs? Everything else works fine. -
how to get slug of current url in current template
In Django template, How to get the slug of the URL I am on in the template so that I can pass it to the template tag. Example I am on: foo.com/slugname then in the template, I am expecting {% function|slugname%} where 'function' is my template tag. -
Why is my authorization header not working here?
I keep sending the authorization header required by the program to be able to do actions on the view is not working. The view returns: { "detail": "Authentication credentials were not provided." } Here's a screenshot of how the header looks on postman. Here's how it looks on curl: curl http://127.0.0.1:8000/v1/locations/ -H 'Authorization: Token 7864d01cbacae0c1cb3c27d19c02f5cfe1570789' And here's the python code on the view class CreateAPIView(CreateModelMixin, GenericAPIView): """ Concrete view for creating a model instance. """ authentication_classes = (CustomTokenAuthentication,) permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class ListAPIView(ListModelMixin, GenericAPIView): """ Concrete view for listing a queryset. """ authentication_classes = (CustomTokenAuthentication,) permission_classes = (IsAuthenticated,) pagination_class = PaginationResponse def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) class ListCreateView(CreateAPIView, ListAPIView): pass If I comment out the two "permision_classes" lines it works without a problem. Thank you for your help in advance :) -
How to use toggle switch with django boolean field?
I have an work_experience model which contains "is_working" field which is true when a user is still working at a company. On front end I'm using a toggle switch and I want to change the boolean field value "is_working" on click. What should be the logic to use toggle in django? Toggle switch HTML <div style="display:inline-block"> <label>Currently working here?</label> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> Model class Work_Experience(models.Model): job_title = models.CharField(max_length=100, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) description = models.CharField(max_length=300, null=True, blank=True) exp_start_date = models.DateField(null=True, blank=True) exp_end_date = models.DateField(null=True, blank=True) is_working = models.BooleanField(default=False) -
Bleach breaks output of WYSIWYG editor
I've successfully installed django-summernote. The widget works as does the output to my template. This editor requires that the 'safe' template tag be used for output to the templates. {{ blogbody|safe}} As I don't trust my users, using 'safe' in this manner concerns me. My understanding is that using 'safe' could allow people to run malicious code on my site. Based on recommendations I've seen, I tried implementing bleach (https://pypi.org/project/bleach/). import bleach def blog_post_create: #a bunch of code if form.is_valid(): instance = form.save(commit=False) body = bleach.clean(instance.body) instance.body = body instance.save() This causes the output to the template to break. Rather than getting: This text is in bold I get: pThis text is in bold/p How can this issue be resolved? Am I wrong to assume that marking output as 'safe' is dangerous if I have random users on my site creating blog posts? Thanks so much! -
Cythonizing a django project
I have a Django application that will be distributed soon on a client server and I don't want to provide access to my source code. Someone suggested to me the use of Cython in order to compile my project into .so modules that will prevent the reverse engineering of my source code. I tried setting up the setup.py files and running a compilation and I was able to obtain the .so files, but the problem is that every time I was hit by the problem of " undefined symbol: _Py_ZeroStruct " after deleting the .py files from the project, leaving the new .so files and running my Django project. The Setup.py is written as follow : from distutils.core import setup from Cython.Build import cythonize setup(ext_modules= cythonize( ['appFolder/*.py', 'MainProjectFolder/*.py'] ) ) So I am asking you guys if there anyone who tried compiling his project with Cython and how did he wrote the setup.py in order to be able to run Django project successfully. -
I have an Internal Server Error when I try to access in my Django site
I'm trying to push my portfolio in production with a server ubuntu 18.10 using apache2 The problem : I only access of the admin page and the home page of my site but when I try to acess in blog or projects like this www.mysite.com/blog or www.mysite.com/projects an "internal server error" displays tree of my site bellow ___rp-portfolio | |___blog | |___media | |___personal_portfolio | | | |___wsgi.py, settings.py ... | | |___projects | |__static | |___venv | |___db.sqite3 | |___manage.py the .conf of the apache server bellow Alias /static /home/username/rp-portfolio/static <Directory /home/username/rp-portfolio/static> Require all granted </Directory> Alias /media /home/username/rp-portfolio/media <Directory /home/username/rp-portfolio/media> Require all granted </Directory> <Directory /home/username/rp-portfolio/personal_portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/username/rp-portfolio/personal_portfolio/wsgi.py WSGIDaemonProcess django_app python-path=/home/username/rp-portfolio python-home=/home/username/rp-portfolio/venv WSGIProcessGroup django_app urls.py of the site from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), #THIS PAGE WORKS path('projects/', include("projects.urls")), path('', include("blog.urls")), path('ckeditor/', include('ckeditor_uploader.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py (blog) from django.urls import path from . import views urlpatterns = [ path("", views.home, name="home"), #THIS PAGE WORKS path("blog/", views.blog_index, name="blog_index"), path("blog/<int:pk>/", views.blog_detail, name="blog_detail"), path("blog/<category>/", views.blog_category, name="blog_category"), ] THANK YOU FOR HELP !! -
Command not found for start new project
I am starting out with Django on my Mac, I installed Django2 and installed PyCharm But when I try to run command from terminal to create a new project on desktop: django-admin.py startproject name or django-admin startproject name then I get "command not found" Pycharm shows my env at /Users/admin/PycharmProjects/untitled/venv Please help Thank you -
Form not posting all checked input checkboxes
I am trying to post all checked input checkboxes. The input field is generated by django's for loop as shown below. From what I have found so far, the below should be working. I believe the issue may be in the fact that the input fields are generated through the forloop, if so, how can I get around this? For each value add to list and post with js? index.html {% for q in list %} {% if forloop.last %} <form method="POST" name="selectedchecks"> {% csrf_token %} <div class="qblock"> <label class="pure-material-checkbox"> <input class="selectedchecks" type="checkbox" name="choices[]" value="{{ q }}"> <span> <p>{{ q }}</p> </span> </label> </div> </form> {% endif %} {% endfor %} views.py if request.method == 'POST': selected_list = request.POST.getlist('choices[]') What happens is that only the first value of {{ q }} is returned if the first checkbox is selected, if any other checkbox apart from the first is selected, nothing is returned (empty list). Selecting all checkboxes also only returns the first value. It should POST all selected checkbox values. Any help is appreciated!