Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image upload field works in django admin but not working in template
Hi i created a generic form to insert data everything is working fine but image could not upload in template form but when i upload image in admin it works perfectly and image display on template page. Here is my code: views.py: class ArticleCreate(CreateView): model = article fields = ['title', 'cat', 'img', 'disc', 'tags'] models.py: class article(models.Model): title = models.CharField(max_length=250) disc = models.TextField(verbose_name="Discription") cat = models.ForeignKey(category, verbose_name="Category") tags = models.ManyToManyField(Tag, blank=True) img = models.ImageField(blank=True, verbose_name='Image') Settings.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Template page: {% for list in data %} {{ list.title }} {% if list.img %} {{ list.img.url }} {% endif %} {% endfor %} What can i do to upload image with generic form ? -
Empty static prefix not permitted
I´m working with a tutorial on udemy. I´m at the part about setting up static files . https://www.udemy.com/probar-django-construir-una-aplicacion-web-en-python/learn/v4/overview that´s the link. on video 22 it shows how to configure static files. I configured everything as in the tutorial. this is a little further than just typing code from docs, colins, upper case 'POST'. Again, my code is exactly as in the tutorial. any comment about how to read the error message and only look at the useful stuff with be of good help as well. the video is in Spanish but, the pages and the code are in English. can anybody tell me from looking at the error message or taking a look at the tutorial to see what could be wrong. Unhandled exception in thread started by Traceback (most recent call last): File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\core\management\base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\core\management\base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Users\migel\Desktop\pd110\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = … -
How to strip(not remove) specified tags from a html string using Python?
The Proper way to strip(not remove) specified tags from an HTML string using Python. def strip_tags(html, tags=[]): .... pass #return the html string by stripping the tags from the list The questions explain all, I am to write a python function that takes HTML string as input, and list of tags to be stripped, (mimicking Django template's removetags functionality as it's deprecated ) What's the simplified way of doing this? The below approaches didn't for for me for the specified reasons Using regular expressions (for obvious reasons) Clean() method by Bleach library. Surprisingly such a robust library is useless for this requirement, as it follows whitelist-first approach, while the problem is blacklist-first. Bleach will only be useful to 'keep' certain tags but not for removing certain (unless you are ready to maintain a huge list of all possible ALLOWED_TAGS) lxml.html.Cleaner() combined with remove_tags or kill_tags This is somewhat closer to what I was looking for, but it goes ahead and does(removes) more than what it is supposed to, And there is no way to control the behaviour at the finest, like requesting the Cleaner() to keep the evil <script> tag. BeautifulSoup. This has a method called clear() to remove the … -
Allauth request.user is AnonymousUser in APIView, but is_authenticated in View
I performed this test: class IsAuthenticatedView(APIView): def get(self, request): print(request.user) return Response({ "is_authenticated": "true" if request.user.is_authenticated else "false" }, 200) and class IsAuthenticatedView(View): def get(self, request): print(request.user) return Response({ "is_authenticated": "true" if request.user.is_authenticated else "false" }, 200) The second one fails to load properly because of an AssertionError. However, the request.user changes among these two, where the APIView prints an AnonymousUser, the second prints the actual user logged in. I'm using the Facebook login authentication. -
Templates do not shows up the image
The img tag do not shows up. The mem.mem_img is /uploads/images/team2.png, and in my template: <div> <img src="{{ mem.mem_img }}"> </div> In the browser the image do not shows up. In the browser debugger: How can I shows the image? -
Payment Information From Javascript To Django Views
I integrating a payment processor for my django app and now if payment was successful, I have a call back function written in javascript inside of the HTML and that gives me the transaction reference id. I want to send that reference id to my django views for final verification. Please help me out here because i have tried almost all related solutions here on stackoverflow none seems to solve my exact problem. The only thing i can do is to console.log() the reference id. Here is my code inside html <script> function payWithPaystack(){ var handler = PaystackPop.setup({ key: 'pk_test_somekey', email: 'customer@email.com', plan: "PLN_testcode", metadata: { custom_fields: [ { display_name: "Mobile Number", variable_name: "mobile_number", value: "+2348012345678" } ] }, // if transaction was successful callback: function(response){ var ref_ = response.reference console.log(ref_) }, onClose: function(){ alert('window closed'); } }); handler.openIframe(); } </script> django views.py def payment(request): # here a variable will be capture the ref_ return render(request, template, context={}) -
How change html template of ImageField in edit form?
I use Django 1.11 in my project. In my edit form I have ImageField. Django by default render html which you can see below. How change html of ImageField in edit form correctly? I tried next code but Django raise error TemplateDoesNotExist. Django dont see template_file in my custom widget? How to fix this problem? By the way initial_text and input_text works well. Also I tried template_with_initial but unfortunately it didnt help me. I would be grateful for any help! Django render this html by default: Currently: <a href="/media/images/2017/08/23/picture.jpg">images/2017/08/23/picture.jpg</a> Change: <input name="image" id="id_image" type="file"> widgets.py: from django.forms.widgets import ClearableFileInput class CustomClearableFileInput(ClearableFileInput): initial_text = 'Current image' input_text = 'Change' clear_checkbox_label = 'Clear Image' template_name = 'custom_clearable_file_input.html' <-- DONT WORK custom_clearable_file_input.html: {% if widget.is_initial %} <span>{{ widget.initial_text }}</span>: <a href="{{ widget.value.url }}">{{ widget.value }}</a> {% if not widget.required %} <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"/> <label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label> {% endif %} <br/> <span>{{ widget.input_text }}</span>: {% endif %} <input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}/> ERROR: Traceback (most recent call last): File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, … -
Why does Django set a shorter maximum length of foreign keys to auth.User.username?
I have a model with a foreign key that references the username field of auth.User. The original field has a maximum length of 150. But Django generates a foreign key with a maximum length of 30. In my app's models.py: class Profile(models.Model): user = models.ForeignKey('auth.User', to_field='username') In django.contrib.auth.models: username = models.CharField( _('username'), max_length=150, Generated SQL: CREATE TABLE "myapp_profile" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" varchar(30) NOT NULL REFERENCES "auth_user" ("username") ); This only happens when referencing auth.User.username. If I reference a long field in my own model, the foreign key is generated fine. Why is that? How can I overcome it? Using Django 1.11.4 and Python 3.6.2. I tried PostgreSQL and SQLite and the problem occurs on both. -
Django Channels problems with Apache
I've been trying to learn Django Channels/Daphne/Redis and implement this with an Apache ProxyPass. I've been reading the Django Channels docs and following steps in this tutorial: https://blog.mangoforbreakfast.com/2017/02/12/django-channels-with-vagrant-apache-and-supervisor/ I've also looked at countless questions on this forum, this one for example: Django Channels Worker not responding to websocket.connect The problem is that when visiting the url, only the http_consumer is called. However, if I open up a browser console on that page, I can open up a socket like this: socket = new WebSocket("ws://" + window.location.host + "/ws/"); socket.onmessage = function(e) {alert(e.data);} socket.onopen = function() {socket.send("hello world");} if (socket.readyState == WebSocket.OPEN) socket.onopen(); I can see under the network tab in the developer tools that there is an active websocket. If I try to visit domain.com/ws/ , I get a 500 error from Apache. No protocol handler was valid for the URL /ws/. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule. All I can find on this error is related to either not having trailing slashes in the Apache ProxyPass url, or not having proxy_wstunnel or proxy_http modules enabled. I have the modules enabled and Apache conf is … -
Empty Chatterbot Conversation table in Django Admin
In Django admin, the chatterbot conversion table is empty after training has been performed using python manage.py train This populates the statement and response tables with the training data based on the yml file, which is fine. However, during testing, the statements posted to the chatbot and the response ought to go to the conversation table. However, this is not the case and such conversation is added to statement and response table used for the training. This seems to affect the efficiency of the bots. -
How to draw a circle chart with form & astronomy data using python or javascript for django?
I want to draw a circle chart that shown planets & zodiacs on that chart like below image for django. The circle have a form data with Datetime, UTC, & Latitude/Longitude's field that already setup in my models & already filled in my database. The calculation for planet/zodiac position already setup by using Pyephem library. When user submit that form then draw the planets position (dynamically) over the zodiacs position (statically) bases on above data. When some planets make a geometry angle like show on green line which's make 60° angle then draw a line on that chart. What's python library or javascript library that I can use? -
Django makemigrations error when there are 3 custom model in a models.py
I got the following error when I tried to run makemigrations. ERRORS: remoshin_manager_sys.RemoshinDoctor.groups: (fields.E304) Reverse accessor for 'RemoshinDoctor.groups' clashes with reverse accessor for 'RemoshinManager.groups'. HINT: Add or change a related_name argument to the definition for 'RemoshinDoctor.groups' or 'RemoshinManager.groups'. remoshin_manager_sys.RemoshinDoctor.groups: (fields.E304) Reverse accessor for 'RemoshinDoctor.groups' clashes with reverse accessor for 'RemoshinUser.groups'. HINT: Add or change a related_name argument to the definition for 'RemoshinDoctor.groups' or 'RemoshinUser.groups'. remoshin_manager_sys.RemoshinDoctor.user_permissions: (fields.E304) Reverse accessor for 'RemoshinDoctor.user_permissions' clashes with reverse accessor for 'RemoshinManager.user_permissions'. HINT: Add or change a related_name argument to the definition for 'RemoshinDoctor.user_permissions' or 'RemoshinManager.user_permissions'. remoshin_manager_sys.RemoshinDoctor.user_permissions: (fields.E304) Reverse accessor for 'RemoshinDoctor.user_permissions' clashes with reverse accessor for 'RemoshinUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'RemoshinDoctor.user_permissions' or 'RemoshinUser.user_permissions'. remoshin_manager_sys.RemoshinManager.groups: (fields.E304) Reverse accessor for 'RemoshinManager.groups' clashes with reverse accessor for 'RemoshinDoctor.groups'. HINT: Add or change a related_name argument to the definition for 'RemoshinManager.groups' or 'RemoshinDoctor.groups'. remoshin_manager_sys.RemoshinManager.groups: (fields.E304) Reverse accessor for 'RemoshinManager.groups' clashes with reverse accessor for 'RemoshinUser.groups'. HINT: Add or change a related_name argument to the definition for 'RemoshinManager.groups' or 'RemoshinUser.groups'. remoshin_manager_sys.RemoshinManager.user_permissions: (fields.E304) Reverse accessor for 'RemoshinManager.user_permissions' clashes with reverse accessor for 'RemoshinDoctor.user_permissions'. HINT: Add or change a related_name argument to the definition for 'RemoshinManager.user_permissions' or 'RemoshinDoctor.user_permissions'. remoshin_manager_sys.RemoshinManager.user_permissions: (fields.E304) Reverse accessor for 'RemoshinManager.user_permissions' … -
Internal Server Error while setup FB Webhook
i have digitalocean server, i follow instructions on :https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok when i came 4. part, i write @method_decorator(csrf_exempt), my server says "Internal Server Error". What is the problem you think, is this about nginx.conf? When i remove this code, everything works well but Messenger api or Webhook not works. I write some words but no returns from my page. -
Uploading Django form with xhr, appending a field
I'm trying to submit a django form with 3 fields, two of which will be selected by the user and the third is a file field that will be passed as a audio/wav blob from the browser. Here's the form in the template: <form id='update_audio' enctype="multipart/form-data" method="post"> {% csrf_token %} {{form.title}} {{form.numobj}} <input class="btn btn-primary" type="submit" value="Save"> </form> I didnt include {{form.sound}}, which is the filefield I want to append because I try to append it to a formdata instance in the request: var form = document.getElementById('update_audio'); form.onsubmit = function(event) { event.preventDefault(); var formData = new FormData(form); formData.append('sound', blob); var xhr = new XMLHttpRequest(); // Add any event handlers here... xhr.open('POST', form.getAttribute('action'), true); xhr.send(formData); return false; // To avoid actual submission of the form } Got the above code from here under "progressive enhancement". Right now, when I try and submit the form, I am getting a "net::ERR_INCOMPLETE_CHUNKED_ENCODING" in the console. Any Ideas on whats going wrong? -
Full Stack Setup with Python
In the years past, I've always used Angular 1.x for my front end which was as simple as including a single JS file at the time. Now with the rise of TypeScript in Angular, React, and others, there's now a need for a dedicated NPM build serves which compiles the source into vanilla JavaScript before serving the front-end as an independent project. Please correct me if my understanding of this is in anyway flawed. At the moment I use Django for all of my backend applications, particularly a REST framework that will enable the frontend to function as a SPA. I've taken a liking to Vue.js as my frontend weapon of choice. My question is (and please forgive me if it seems a bit too broad) how do I setup my project and configure it properly so that I'm not running two servers for both the frontend and backend? Again, back in the days of Angular 1.x and vanilla JavaScript all I had to do was include a minified angular.js in my static files folder in the backend and the same goes for the standalone version of Vue. Now I'm just so confused what is what and how to properly … -
How to pass hidden variable to a form in django so it could be validated?
I have a registration form that goes through all the usual stuff, but with one bot prevention thing. I made a model SecurityQuestion, that consists of two charfields, Question and Answer. During registration one of them is randomly picked and is supposed to pass an answer to the form so it can be validated there. However, for the reason I'm yet to figure out, it doesn't seem to be passing the answer to the form So let's start with the code profile/forms.py # FORM: Register an account class UserRegistrationFirstForm(forms.ModelForm): username = forms.CharField(max_length=20) password = forms.CharField(widget=forms.PasswordInput) password_confirm = forms.CharField(widget=forms.PasswordInput) email = forms.EmailField() email_confirm = forms.EmailField() answer = forms.CharField(max_length=50, required=True) hidden_answer = forms.CharField(widget=forms.HiddenInput) class Meta: model = User fields = [ 'username', 'email', 'email_confirm', 'password', 'password_confirm', 'answer', ] def clean_answer(self): user_answer = self.cleaned_data.get("answer").lower() formated_hidden_answer = self.cleaned_data.get("hidden_answer").lower() if formated_hidden_answer != formated_user_answer: raise forms.ValidationError("Incorect answer to security question!") return answer As you can see, there are two fields, answer and hidden_answer. answer is where users types in their answers, and hidden_answer is supposed to be populated when initializing form and passing init. profiles/views.py # VIEW: Register an account def custom_register(request): if request.user.is_authenticated(): return redirect(reverse('profile', host='profiles')) # Grab a random registration security Q&A qa_count = … -
NodeNotFoundError in Django
Every time I try to run the server or migrate I get this error in the command line: django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0009_user_following dependencies reference nonexistent parent node (u'account', u'0002_contact') I did make a following system but i can't find were it is. I also tried deleting my some of my django projects but I still get this error. Please help me. -
Connect to a remote socket.io server from Django server
I am trying to build a real-time Django application. Because of the way my hosting service works, I am unable to start a Websocket server in parallel of my Django server. I managed to have user-to-user interactions by creating an express server on a separate NodeJS website with socket.io, and having clients on the Django server also connect to the remote socket.io server. However, I'dlike to have my Django server directly send events to users. To do this, I would like to create a connection between the Django server and the NodeJS server. Something like that in python: socket = io("http://socket.io.server") socket.emit('eventForUsers') Is there anyway for me to achieve this? The only information I found seemed to require me to run a parallel server from my Django app, which I can't do because my host doesn't allow me to run long-term processes. -
Point website at IP or CNAME under other domain directory with Django and Shopify
I am looking for if someone can point me to right direction. Let's say we have a domain and we building Django website. www.example.com We can create pages like www.example.com/press/ www.example.com/videos/ www.contact.com/contact/ Then we would create let's say Shopify e-commerce example.shopify.com I know with Shopify you have to create an account and they own the files. Is there a way if we in Django Application / Website set urls.py www.example.com/store/ And in DNS of the example.com would do some settings that it would load the Shopify site? I am not talking about redirects, I am talking about full URLs. Let's say www.example.com/store/ - would load Shopify homepage www.example.com/store/collections/... - collections at Shopify site Other directories would be URLs of the Shopify site... Would like to know if this is even possible. -
Django adding namespace to urls gives error Reverse for 'login' not found. 'login' is not a valid view function or pattern name
Im trying to add this url to my app's urlpatterns (i.e. MyProject/MyApp/urls.py): url(r'^login/$', auth_views.LoginView.as_view(), name='login') I have this snippet in one of my templates: <a href="{% url 'login' %}">Login</a> Normally, clicking on the link takes you to the login page successfully. However, when I try to add a namespace to my urls (app_name = my_namespace) and change the reverse to <a href="{% url 'my_namespace:login' %}">Login</a> it fails when I click on the link and I get the error Reverse for 'login' not found. 'login' is not a valid view function or pattern name. While all the other urls I reverse work with the namespace, it is just the login reverse that fails. Any idea why? -
Custom function to query database across Django views
In 'myapp' I have a model 'Profile', which shares a OnetoOneField relationship with my custom User model. In many of my views, I need to check if the user has a profile set up. So I have created a module 'profilecheck' which contains this function: def has_profile(): try: profile = Profile.objects.get(user=request.user) return profile except: return False In my views.py, I have the following: from myapp.utils.profilecheck import has_profile from myapp.models import Profile def viewprofile(request): if has_profile(): context = { 'profile': has_profile() } return render(request, 'profile.html', context) else: return render(request, 'setup_profile.html', {}) When called in the view, has_profile() always returns False. Any ideas why? -
Update / Save model date value directly from template?
I am still quite inexperienced in Django and I was wondering if it would be at all possible to update/save today's date in my database directly from the template? I have a Django-filter filterView (listView) that shows the list of people that are in my department which I currently have in my database. And I would like to update a datetime value (when the people have last been visited) to today's date by clicking on a <\a> link that shows in the list. That way I don't have to setup an update view just to update when I've last visited the coworkers. Is something like this even possible? I did try to implement a function in my models.py with the @property tag but when I refresh the webpage, or visit the page it automatically updates it without having to click on the link. Edit: Here is the code: # models.py @property def update_visit_date(self): self.last_visit = timezone.make_aware(datetime.datetime.today()) super(Directory, self).save() return reverse('directory_list') # snippet from my template directory_list.html {% for contact in items %} <tr> <td>{{ contact.first_name }}</td> <td>{{ contact.last_name }}</td> <th><a href="{{ contact.get_absolute_url }}">{{ contact.email_address }}</a></th> <td>{{ contact.phone_number_1 }}</td> <td>{{ contact.get_department_display }}</td> <td>{{ contact.room_number }}</td> {% if contact.is_past_due == 'no_visit_performed' %} … -
Django Integrity error for integer fields
I have an integer field defined in models.py. If the value is not entered for it via Admin form then i want it to be stored as NULL. employees = models.IntegerField(null=True, blank=True, default=None) I always get IntegrityError NOT NULL constraint failed whenever i try to submit via Admin form for that table. I have made sure that i run migrations using the following commands: python3.5 manage.py makemigrations python3.5 manage.py migrate Django version: 1.11.4 -
Using Jquery/Ajax to get value of a field in a Django model
How do I check the value of a field on my model and display a message upon it's change without refreshing the page? For example, I have a website where a customer can signal they are looking for a service and someone trying to provide the service can 'claim' them (similar to uber). The customer clicks a checkbox on my site signaling they are looking for a service (setting their active field to True), they are then redirected to a page that says "thank you, you will be alerted when someone claims you." Now that their activefield is set to True they are displayed in a list to service providers who can claim them (upon this claim, the customer's active field is set back to False). How can I be checking in the background of the customer's page (the one that says "thank you, you will be alerted when someone claims you.") for this change to the active field and then display an alert saying "you have been claimed"? -
Django and Ajax, submitting form does not create new object
I'm trying to create a new 'Sounds' object using the following ajax: var data = new FormData(); data.append('title', 'test_1'); data.append('numobj', '{{instance.numobj}}'); data.append('sound', blob); $.ajax({ url: "{% url 'posts:post_create' %}", type: 'POST', data: data, cache: false, processData: false, contentType: false, success: function(data) { alert('success'); } }); There are 3 field in the form: class PostForm(forms.ModelForm): class Meta: model = Sounds fields = [ 'title', 'numobj', 'sound', ] And here's the view that submits the form: def post_create(request): form= PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/') context= { 'form': form, } return render(request, 'post_form.html',context,) Whenever I submit the ajax, it gives me the success alert, but no new object is created. I'm thinking this may be due to the way the fields are appended to the FormData instance. Problem is, I'm not getting any errors to debug with. Any clues?