Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I display calendar event on the calendar in Django-Bootstrap-Calendar?
Please help me, I'm having django-bootstrap-calendar, already added the calendar event to the Admin where the superuser can Add, Edit, Delete event(s). However, whenever an event is created, it doesn't display on the Calendar. Admin This is how I configured the Admin class CalendarEventAdmin(admin.ModelAdmin): list_display = ["title", "url", "css_class", "start", "end"] list_filler = ["title"] admin.site.register(CalendarEvent, CalendarEventAdmin) The calendar was loaded with: {% load bootstrap_calendar %} {% bootstrap_calendar_css %} <!-- {% bootstrap_controls 'optional-css-classes' %} --> {% bootstrap_calendar 'optional-css-classes' %} {% bootstrap_calendar_js language="template" %} {% bootstrap_calendar_init language="template" %} -
How can I get "Your cart is empty" while I have placed some orders
I am creating an online shopping and after selecting the products for my order and want to place the order, the payment by the credit card interface is displaying without the fields of the Card number, the Cvv and the expiration date of the card as it is showing in figure 3. In addition, the celery worker seems to be failing when I click on the place order button and it is displaying the following information: E:\ShippingApp>celery -A ShippingApp worker -l info -P eventlet -------------- celery@DESKTOP-S0OA06L v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Windows-10-10.0.17134-SP0 2019-02-24 00:48:41 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: ShippingApp:0x160dcec38d0 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 4 (eventlet) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . orders.tasks.order_created [2019-02-24 00:48:41,250: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2019-02-24 00:48:41,265: INFO/MainProcess] mingle: searching for neighbors [2019-02-24 00:48:42,286: INFO/MainProcess] mingle: all alone [2019-02-24 00:48:42,348: INFO/MainProcess] pidbox: Connected to amqp://guest:**@127.0.0.1:5672//. [2019-02-24 00:48:42,348: WARNING/MainProcess] c:\program files\python37\lib\site-packages\celery\fixups\django.py:200: UserWarning: Using settings.DEBUG leads to a memory … -
Not Found: /media/ 404 77 Django production - ASGI Digital Ocean
I've tried everything but my media folder profile pic images still aren't appearing. They look like this on the webpage. I'm in production for my Django 2.1 app, using Digital Ocean running a ASGI server (as I'm using channels). My media folder is located in my root folder (same level as manage.py). The error being given is xx.xxx.xxx.xx:xxxxx - - [23/Feb/2019:17:23:49] "GET /media/profile_pics/avril.jpg" 404 77 But that is the correct path and the image is located there. my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'appname/static'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Django DRF REST Put method not updating anything
In Django PUT request when I am updating value of location and hours per week, the PUT request returns exact same values and did not update anything. Below is my code, url url( r'^api/availability', views.AvailabilityAPIView.as_view(),name='api_availability' ) models class Availability(models.Model): # Skill model which contains trainer's skill details user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) locations = models.CharField(max_length=2000) hours_per_week = models.IntegerField(default=0) def __str__(self): return self.locations + "|" + str(self.hours_per_week) serializer class AvailabilitySerializer(serializers.ModelSerializer): class Meta: model = Availability fields = ['user', 'locations', 'hours_per_week'] views class AvailabilityAPIView(APIView): authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication) def get(self, request): availability = Availability.objects.all() serializer = AvailabilitySerializer(availability, many=True) return Response(serializer.data) def put(self, request): serializer = AvailabilitySerializer(request.user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Please help to understand what I am doing wrong. Do I need to pass PK from url and update the specific one? -
django comments for logged in users is giving error that name field is required
I am trying to add commenting system to my django application. for that i am using django comments(https://django-contrib-comments.readthedocs.io) along with django threaded comments(https://github.com/HonzaKral/django-threadedcomments). i want to allow commenting ionly for users that are authenticated. as shown in this example. https://django-contrib-comments.readthedocs.io/en/latest/quickstart.html#providing-a-comment-form-for-authenticated-users {% if user.is_authenticated %} {% get_comment_form for object as form %} <form action="{% comment_form_target %}" method="POST"> {% csrf_token %} {{ form.comment }} {{ form.honeypot }} {{ form.content_type }} {{ form.object_pk }} {{ form.timestamp }} {{ form.security_hash }} <input type="hidden" name="next" value="{% url 'object_detail_view' object.id %}" /> <input type="submit" value="Add comment" id="id_submit" /> </form> {% else %} <p>Please <a href="{% url 'auth_login' %}">log in</a> to leave a comment.</p> {% endif %} but on submitting i get error that field name is required. but i suppose as mentioned in the linked article providing name is not required. how can i fix this error -
How to enable CORS in Reactjs?
I use this fetchData config in React.js: fetchData = () => { fetch("http://localhost:8000/batch_predict", { method: "POST", headers: { 'Accept': 'application/json, text/plain, */*', //'Content-Type': 'application/json' "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" // otherwise $_POST is empty }, , body: JSON.stringify({ holdingTime: this.state.holdingTime, csvData: this.state.csvData }) }) .then((resp) => { return resp.json() }) .then((data) => { this.updateDelay(data.prediction) }) .catch((error) => { console.log(error, "catch the hoop") }) }; It sends well the data, however I get CORS error. If I set headers as follows, I do not get CORS error, but the data is set wrongly: headers: { "Content-Type": "application/json; charset=utf-8", } Therefore I want to maintain the first option, but how can I enable CORS in this case? In Django backend settings.py I added all the CORS related lines: ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] -
Got The included URLconf does not appear to have any patterns in it
Okay, so I have looked at other answers to this question, but I still can't figure out what's wrong. Generally there are two urls.py - one in my account folder, and another one in my bookmarks folder which are in the root folder - bookmarks. When I try to create a superuser, I get this: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'account.urls' from '/Users/aleksanderjess/Documents/PacktPub/Django/bookmarks/account/urls.py'>' 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. I have absolutely no clue why. The imports look legit and all. Here are two urls.py account/urls.py from django.contrib.auth import views from . import views urls = [ path('login/', views.user_login, name='login'), ] and then there's the one in bookmarks, which looks like this 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), path('account/', include('account.urls')), ] Could you all help me out please? I am afraid I don't have any idea how to fix this. -
Unexpected routing behavior in Celery V4, upgrading from Celery V3 class based tasks
I'm updating my celery workers from celery v3 to celery v4, and all my tasks are Class Based Tasks. I have manually registered the tasks, since celery v4 won't automatically register class based tasks anymore. The problem is in task routing, I have the following Task: class RegisterTask(Task): routing_key = 'app_server.register' def run(**params): whatever ... I'm running two celery workers, one on the default queue, and the other on the register queue, like below: # Default Worker celery -A app_server worker --loglevel=info --concurrency=1 # Register Worker celery -A app_server worker -Q app_server_register --loglevel=info --concurrency=1 and here's my queues definition: CELERY_TASK_DEFAULT_QUEUE = 'app_server_default' CELERY_TASK_DEFAULT_ROUTING_KEY = 'app_server.default' CELERY_TASK_QUEUES = ( Queue('app_server_default', routing_key='app_server.default'), Queue('app_server_register', routing_key='app_server.register') ) The unexpected behavior is the difference I see when I call the task using Celery V3 and Celery V4. # Celery V3 RegisterTask().delay(**params) # task is consumed by the register worker! # Celery V4 RegisterTask().delay(**params) # task is consumed by the default worker! And I want the task to be consumed by the register worker (celery v3 behavior), hence why I hardcoded the routing_key attribute in the class based task. [I'm also using redis as the broker, if it's any important] Any Ideas on this issue? Thanks! -
Django - Difference between admin save_model() and post_save signal
For my application I need to do extra operations when a model is saved via form. In practice, I need to add a value in another model if certain conditions are present in the form. To do this I have two options, but I want to understand the pros and cons of both. Use the post_save signal Overwrite the save_model method in admin.py, since it is said in the documentation that "Overriding this method allows doing pre- or post-save operations." I currently use the latter in this way def save_model(self, request, obj, form, change): #some pre save operations.... #this call the save model method super(MyModelAdmin, self).save_model(request, obj, form, change) #some post save operations... and it works But what I want to understand is: For what I must do, what are the differences between the two approaches and what is the most correct. Is the save_model method related to the use of the admin interface? What happens if I use another frontend different from Django's admin? In general, what is the difference between doing pre and post save operations overwriting save_model and using signals? -
InvalidDimensions Error. How can I gain access to the Dataset to format it before the tablib error through django-import-export
I'm using django-import-exportand receiving the following error when trying to upload a csv file: InvalidDimensions encountered while trying to read file I know that this is a tablib error, and due to the fact that I have an empty line between each row in my csv, as well as blank lines at the end of file. I want to gain access to the dataset before the import to format it properly. I've tried overriding the import_obj, before_import and before_import_row methods, but that doesn't seem to work. None of the other methods seems to work either. admin.py class UpdateResource(resources.ModelResource): def before_import_row(self, row, **kwargs): print(row) I've just been trying to find the correct method to use before the error. I've had no luck gaining access to the tablib.Dataset resource yet. Any help would be great. -
Count number of posts from a ListView
I would like to count the number of "todo" in my ListView views.py class DashboardListView(LoginRequiredMixin,ListView): model = Links template_name = 'dashboard/home.html' context_object_name ='links_list' paginate_by = 15 def get_queryset(self): return self.model.objects.filter(author=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dashboard_list']= Dashboard.objects.filter(author=self.request.user)[:15] context['todo_list']= Todo.objects.filter(author=self.request.user).order_by('-pk')[:15] context['PasswordUsername_list']= PasswordUsername.objects.filter(author=self.request.user) return context And render it with {{c_count}} in my template but was unable to do so. Thanks -
django allauth adapter signup: save() prohibited to prevent data loss due to unsaved related object 'user'
I'm using Django and Allauth. I need the user to be able to signup with additional field, so I created a custom user call Profile, a custom SignupForm and an Adapter, but when I submit I get the error "save() prohibited to prevent data loss due to unsaved related object 'user'". custom form class CustomSignupForm(SignupForm): first_name = forms.CharField( max_length=200, label='Nome*', widget=forms.TextInput(attrs={'placeholder': 'Il tuo nome'}), required=True ) last_name = forms.CharField( max_length=200, label='Cognome*', widget=forms.TextInput(attrs={'placeholder': 'Il tuo cognome'}), required=True ) etc... def signup(self, request, user): user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.address = self.cleaned_data['address'] user.cap = self.cleaned_data['cap'] user.city = self.cleaned_data['city'] user.province = self.cleaned_data['province'] user.state = self.cleaned_data['state'] user.pi = self.cleaned_data['pi'] user.cf = self.cleaned_data['cf'] user.save() adapter class AccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): data = form.cleaned_data user.email = data['email'] user.first_name = data['first_name'] user.last_name = data['last_name'] user.address = data.get('address') user.cap = data['cap'] user.city = data['city'] user.province = data['province'] user.state = data['state'] user.pi = data['pi'] user.cf = data['cf'] if 'password1' in data: user.set_password(data['password1']) else: user.set_unusable_password() self.populate_username(request, user) if commit: user.save() return user custom user model (Profile) class Profile(AbstractUser): artist_name = models.CharField(max_length=200, blank=True, null=True) address = models.CharField(max_length=200, null=True) cap = models.PositiveIntegerField(null=True) city = models.CharField(max_length=200, null=True) province = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) pi … -
Django Uploaded Image Won't Display - Other Answers Not Helping
I've searched other threads and tried to apply answers but I cannot get my image to display in a Django page. Here's all of my relevant code: Settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'main/media') URLs: urlpatterns = [ path('', views.homepage, name='homepage'), path('register', views.register, name='register'), path('logout', views.logout_request, name='logout'), path('login', views.login_request, name='login'), path('<single_slug>', views.single_slug, name='single_slug'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Model: class TutorialCategory(models.Model): tutorial_category = models.CharField(max_length=200) category_summary = models.CharField(max_length=200) category_slug = models.CharField(max_length=200) category_image = models.ImageField(upload_to='images', blank=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.tutorial_category Views: def homepage(request): return render(request=request, template_name='main/categories.html', context={'categories': TutorialCategory.objects.all}) HTML Display: {% block content %} <div class="row"> {% for cat in categories %} <div class="col s12 m6 l4"> <a href="{{cat.category_slug}}" style="color:#000"> <div class="card hoverable"> <div class="card-content"> <div class="card-title"><strong>{{cat.tutorial_category}}</strong></div> <img src="{{ cat.category_image.image.url }}" width="200" alt=""> <p>{{cat.category_summary}}</p> </div> </div> </a> </div> {% endfor %} </div> {% endblock %} Any help is appreciated. I'm new to Django and have been watching many videos to learn over the last several days. Have many things working great but cannot get this image to display. Thanks. -
Django wrong url routing in production but correct in development
Our website is deployed with Django + Daphne + Nginx. When testing locally the url routing is correct, but in production mode the url routing is wrong. For example, the first page after opening the website is the homepage. The function homepage is written in /appname/views.py. And the url routed to should be /chats. And when testing locally, I am routed to 127.0.0.1/chats. But in production mode, I am directed to mywebsite.com/appname.views.homepage and of course in the browser it shows "the requested resource was not found on server". In the function the sentence used to redirect the page is redirect("appname.views.homepage"). From the wrong routed url I think the request is successfully passed to the right function, but the redirect part fails. It might be a biased observation but it seems like redirect("appname/views/somefunction") will fail and render(request, "appname/somehtml.html") will succeed. I believe the logic in views.py should be correct because the url routing when tested locally is all correct. Anyone know what might be happening here? If any other information is needed, please let me know! Packages used: Django 1.11.20 Daphne 1.3.0 Channels 1.1.8 asgi-redis 1.4.3 asgiref 1.1.2 Nginx configuration server { listen 80; server_name mywebsite.com; charset utf-8; client_max_body_size 20M; location … -
can we use django and dart to make app by flutter?
i have learned django and . now i am trying to make android and ios native app by using only one app, so i am searching for that platform and . 'i i have learned django found flutter using is better than react native...' so anyone can help me... google python: for i in range(13): print(i) Blockquote -
Passing Form POST values from one view to another without inclusion of URL
I'm building up a project that asks a user for a username and password to another site. My thoughts are that the data will be stored in sessions. I have no need to store the users name and password in the database. Anyway, when I prompt the user for their name and pass with a form... urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('', views.enteruser, name='enteruser'), path('success/', views.success, name='success'), path('<str:username>/', views.home, name='home'), ] views.py def enteruser(request): if request.method == 'POST': form = EnterUserForm(request.POST) username = request.POST['username'] password = request.POST['password'] if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] request.session['username'] = username request.session['password'] = password form.save() return redirect('main:home', username=username, password=password) else: if request.session.session_key: username = request.session['username'] password = request.session['password'] return redirect('main:home', username=username, password=password) else: form = EnterUserForm() return render(request, 'main/enteruser.html', {'form': form}) forms.py class EnterUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = DuolingoUsers fields = ['username', 'password'] labels = { 'username': 'Enter Duolingo Username:', 'password': 'Enter Duolingo Password:', } models.py class DuolingoUsers(models.Model): username = models.CharField(max_length=100, unique=True) last_update = models.DateField(blank=True, null=True) last_inquiry = models.DateField(auto_now=True) ... how can I pass it into the follow up view main:home without exposing the data in the URL? -
NameError: name 'posts' is not defined
In url.py the line path('posts/', posts.view.post_title) gives the error NameError: name 'posts' is not defined this is url.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('post/', posts.views.post_title) ] this is views.py from django.shortcuts import render from django.http import HttpResponse def post_title(response): return HttpResponse("<h1> HEllo </h1>") how to resolve this problem Im new to django and learning -
Django Mailer cron jobs
I am new to Django And I am building an e commerce website. I am sending emails and I am using Django mailer. Setting up the mailer is easy. But I am totally new to cron jobs. Emails are sending successfully . If I run the command on shell: python manage.py send_mail >> cron_mail.log 2>&1 How can I use this in my code so it can run after specific interval. This cron job concept is totally new to me. And is there any thing I have to change when use it in production. Thanks in advance. -
Django - unable to load static files?
Very new to Django I am trying to follow along a tutorial by sentdex over on youtube. Django version 1.9 Chose this version as that is being used in the tutorial. I can't seem to figure out how to get the css file to load. The location of the css file /media/xxx/django tutorial/mysite/personal/static/personal/css I assume the BASE_URL is referencing till: /media/xxx/djangotutroial/mysite This is the location of the manage.py. Or am I wrong? The css file is reference in header.html: {% load staticfiles %} <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/> I read through a lot of the answers and if I understand correctly I have to change settings.py in mysite folder. This is what I have at the moment: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'personal'), ] I have tried a lot of combinations in the os.path.join I still can't get the file to load. Thank for your help. -
Pytest use main database for fetching data
I want to get data from main database and run through pytest. For example, class Book(Model): name = CharField() pages = IntegerField() standard_str = CharField() @property def as_str(self): return '{} ({})'.format(self.name, self.pages) And run in pytest something like for o in Book.objects.exclude(standard_str=''): assert o.as_str == o.standard_str The question is how to use main database, so that nothing is changed inside it. The data is only fetched. Thank you. -
Unable to install Django with pipenv because of pytz package failure
This has caused problems for me when developing with django, the simplest case to reproduce this error follows. I'm using Anaconda 4.6.4 running Python 3.6.5, pip version 19.0.3, and pipenv version 2018.11.26. I've updated all the packages, even tried to use previous versions of several packages. When I use: pipenv shell I get a new virtual environment, then I try: pipenv install django I then get the following error message: Installing django… Adding django to Pipfile's [packages]… Installation Succeeded Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Success! Updated Pipfile.lock (85c883)! Installing dependencies from Pipfile.lock (85c883)… An error occurred while installing pytz==2018.9 --hash= ! Will try again. ================================ 2/2 - 00:00:01 Installing initially failed dependencies… [pipenv.exceptions.InstallError]: File "c:\programdata\anaconda3\lib\site-packages\pipenv\core.py", line 1992, in do_install [pipenv.exceptions.InstallError]: skip_lock=skip_lock, [pipenv.exceptions.InstallError]: File "c:\programdata\anaconda3\lib\site-packages\pipenv\core.py", line 1253, in do_init [pipenv.exceptions.InstallError]: pypi_mirror=pypi_mirror, [pipenv.exceptions.InstallError]: File "c:\programdata\anaconda3\lib\site-packages\pipenv\core.py", line 859, in do_install_dependencies [pipenv.exceptions.InstallError]: retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs [pipenv.exceptions.InstallError]: File "c:\programdata\anaconda3\lib\site-packages\pipenv\core.py", line 763, in batch_install [pipenv.exceptions.InstallError]: _cleanup_procs(procs, not blocking, failed_deps_queue, retry=retry) [pipenv.exceptions.InstallError]: File "c:\programdata\anaconda3\lib\site-packages\pipenv\core.py", line 681, in _cleanup_procs [pipenv.exceptions.InstallError]: raise exceptions.InstallError(c.dep.name, extra=err_lines) [pipenv.exceptions.InstallError]: [] [pipenv.exceptions.InstallError]: ['Usage: pip [options]', '', 'Invalid requirement: pytz==2018.9 --hash=\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'pip: error: Arguments to --hash must be a hash name followed by a value, like --hash=sha256:abcde...'] ERROR: … -
Pass value from django view to same template
I am new to Django. I am trying to create a website with two input textboxes. When the submit button clicked, I need to update the results from django view to the same template without reloading the webpage. Here is my code so far: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <H1>Welcome to Test</H1> <div class="input-group" > Input Text:<br> <textarea class="form-control" rows="20" cols="70" name="InputText" placeholder="Enter your Input Text here" form="myForm"> </textarea> <span class="input-group-addon"><br></span> Input TextFSM Template:<br> <textarea class="form-control" rows="20" cols="70" name="InputTemplate" placeholder="Enter your template here" form="myForm"> </textarea> <form action="" method="post" id="myForm"> {% csrf_token %} <input type="submit" value="Submit"> </form> </div> <div id="resultid"> <p>Result:</p> {{result}} </div> </body> </html> views.py class HomePageView(TemplateView): template_name = "index.html" def get(self, request, **kwargs): form = ParserForm() return render(request, self.template_name, {"form": form}) def post(self, request, **kwargs): form = ParserForm(request.POST) if form.is_valid(): inputtext = form['InputText'].value() template = form['InputTemplate'].value() # Process the data and get the result print(result) return render(request, self.template_name, {'result': result}) How to pass the result to index.html from view but the text entered in the textboxes should be persistent. -
Django: Ajax's 'eval() arg 1 must be a string, bytes or code object'
I started using Ajax in my Django project. I've used it once without any problem, to check if a variable already exists in my DB (non-post method) and it worked. But now I'm trying to make a post method with ajax. Ajax part code in js: $.ajax({ url: '/ajax/validate_config/', type: 'POST', data: { "form": form, "class": class, "var_valid": var_valid, "update_fields": update_fields, }, dataType: 'json', }); These vars I'm sending I get before the ajax with jQuery, I print them and I see they are OK. Then I have my Django view: def validate_config(request): form = request.GET.get('form', None) class = request.GET.get('clase', None) var_valid = request.GET.get('var_valid', None) update_fields = request.GET.get('campos_update', None) data = { 'form': eval(form), 'class': eval(class), 'var_valid': var_valid, 'update_fields': update_fields , } print(data['update_fields ']) if request.is_ajax(): print('This is an Ajax request! ') form = data['form'](request.POST) #Other stuff I'm handling with post method but it has no sense to #put it here since the code is not working in **data = {}** The problem: When I wasn't sending a POST method, I printed the data={} dictionary vars in my view and I saw they were being sent properly (form and class). Then when I started handling with the post method below … -
Serving files with Django in deployment - Is it ever ok?
I am running an application which also allows users with certain permissions to download PDFs. The general rule is that Django should not be used for serving files. Instead this should be done by using a dedicated server after django has checked the user permissions, using x_sendfile (see Serving large files ( with high loads ) in Django). However, there has been some suggestion that mod_xsendfile might be deprecated or in some cases the hosting environment is such that some people can't get mod_xsendfile installed. I was just wondering if it would it is even necessary if the applicatin is only serving a few people (say a team of 20) and the files are about 3mb. How much traffic is too much? How big a file is too big? How long is a piece of string? -
Try using 'django.db.backends.XXX', where XXX is one of:
I was setting Django up to use PostgresQL and for some reason, it won't connect it keep giving me this error: Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' here's the code for it in setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DBNAME', 'USER': 'postgres', 'PASSWORD': 'DBPW', 'HOST': 'localhost' } } I had the exact same code in a different project and it works perfectly fine!