Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django into AWS Elastic Beanstalk; ImportError: Couldn't import Django
I'm trying to deploy my Django project into AWS Elastic Beanstalk but ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?. container_command 01_migrate in .ebextensions/02_python.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. this error happens when I tried to do eb deploy and cannot be fixed. Maybe I'm wrong with PYTHONPATH but I couldn't understand how to fix it. My project structure is like this. .ebextensions |-01_packages.config |-02_python.config .elasticbeanstalk |-config.yml manage.py blog |__init__.py |-settings |-urls.py |-wsgi.py main |-media |-static |-templates |-models.py |-views.py |-urls.py requirements.txt and 02_python.config is like this container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: true 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "blog.settings" PYTHONPATH: "/opt/python/current/app/blog:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: blog/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "/static/" I've already tried ./blog but it also doesn't work. I'm sure my project is in virtual environment and all requirements are already imported. How am I wrong with this and How can I fix this error? -
Dynamic upload_to not working properly
I am trying to loop through my hard drive using python and storing the files in the database respectfully. My dynamic upload_to is working when uploading a file but when I try to save the file from the algorithm I wrote to loop through the hard drive, it does not work(upload_to). Any help please? I will add the code below: models.py def upload_path(instance, filename): return os.path.join('file', instance.folder, filename) class File(models.Model): #Defintion to set upload_to path file_title = models.CharField(max_length=255) file_type = models.CharField(max_length=255) folder = models.CharField(max_length=255) document = models.FileField(upload_to=upload_path) uploaded_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.file_title def delete(self): delete_path = os.path.join('file', self.document.path) os.remove(delete_path) return super(File,self).delete() views.py (snippet) - algorithm which loops through hard drive and saves to database for sfile in os.listdir(secondary_directory): if os.path.isfile(secondary_directory + sfile): #Extract File Information filename, filetype = os.path.splitext(sfile) folder = cfile if not exists(filename, 'file'): #Work with file info x = File() x.file_title = filename x.file_type = filetype x.folder = folder x.document = sfile x.save() -
queryset update with multiple variables duplicate
I am having an issue that I have database updated with the same value as for both id's even though they are different as per my example below: Lets assume that I entered as input for id 1 -- P_350 =" try_1" id 2 -- P_350 = "try_2" when I click submit then it become both id's the same "try_2" value. What you suggest to overcome this situation. Should I need to use variable input name including the id in front of the input name ? Or any easier method ? I have the below view.py for my database updates: ids = request.POST.getlist("id") qs = fp.objects.filter(id__in=ids) P_350 = request.POST["P_350"] P_450 = request.POST["P_450"] updates = {} if len(P_350) > 1: updates['P_350'] = P_350 if len(P_450) > 1: updates['P_450'] = P_450 if updates: qs.update(**updates) Here is my html file input section: <td style="display:none;"> <input name="id" type="text" value={{ field.id }} > </td> <td width="650"> {{ field.FP_Item }} </td> {% if field.P_350|length == 0 %} <td style="display:none;"> {% else %} <td> {% endif %} <input name="P_350" type="text" value={{ field.P_350 }} > </td> {% if field.P_450|length == 0 %} <td style="display:none;"> {% else %} <td> {% endif %} <input name="P_450" type="text" value={{ field.P_450 }} > … -
How to get variables from a url
SO in using paypalrestsdk i have gone to paypal, submitted an order and the redirect url is: http://localhost:8000/confirm_order?paymentId=XYZ&token=123&PayerID=ABC How do i dynamically obtain these values from the url?? -
Steps to add model level permission in Django
I have my legacy database.I created models using inspectdb.I am able to see my tables in admin page . I created 4 users and i want to implement role-based permission for each model. I just show you with example what i did in model to add permissions like edit, view, delete. Example:- class BusinessIntegrationSourceCategory(models.Model): date_added = models.DateTimeField(blank=True, null=True) date_modified = models.DateTimeField(blank=True, null=True) source_category = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'business_integration_source_category' permissions = ( ("view_category", "view category"), ("add_category", "Add category"), ("delete_category", "Delete category"), ) Now where i can add the next steps to add role based permissions. -
Make links clickable in my Django TextField
I have a Textfield like so: class Comment(models.Model): ... comment_text = models.TextField(max_length=650, blank=True, null=True) When someone posts a link in the TextField, e.g. www.stackoverflow.com, I want it to be clickable (nested in an <a> tag). Is there any way to do this with code and not using a text editor? -
Django: Validator returns False but form.is_valid() == True
I've created a custom validator which checks, if the upper number in RangeField is lower than some number. The problem is that I can see in debug mode that the Validator.compare returns False but Django raises DataError Value "21474834555" is out of range for type integer LINE 1: ...NULL, "cena" = NULL, "poznamka" = '', "rozloha" = '[ -214748... I can't figure out why it raises this error when it should raise ValidationError before this. I know that the number is out of range, that's why I've created the Validator. VIEW class DopytUpdateView(LoginRequiredMaklerAccessMixin, UpdateView): model = Dopyt form_class = DopytForm template_name = 'dopyty/dopyt.html' FORM class DopytForm(forms.ModelForm): class Meta: model = Dopyt fields = [...'rozloha',...] VALIDATOR class RangeCompleteMaxValueValidator(MaxValueValidator): def compare(self, a, b): upper_ok = (a.upper > b) if a.upper else True lower_ok = (a.lower > b) if a.lower else True return upper_ok and lower_ok MODEL class Dopyt(TimeStampedModel): ... rozloha = IntegerRangeField(null=True, blank=True, verbose_name='Rozloha [m2]', validators=[RangeCompleteMinValueValidator(-2147483648), RangeCompleteMaxValueValidator(2147483647)]) Do you know why it behaves this way? -
How to get all the directories where Django 2.0 will look for templates?
I want to retrieve the list of all the possible directories where Django will search for template files. I would like to make an iterable list of those directories I tried the following : def get_template_directories(): template_directories = [] for template in settings.TEMPLATES: for directory in template['DIRS']: template_directories.append(directory) return template_directories But, I want all the directories where Django looks for template, including templates in INSTALLED_APPS -
Django: celery task does not execute with .delay()
I'm using code examples from the 'Django 2 by Example' book to build my e-commerce shop. The view works as it should, but the task never gets executed. There are no errors. Page is freezing on "Waiting for localhost...". What I'm doing wrong in the code? views.py import ... from .tasks import order_created def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) if cart.promo_code: order.promo_code = cart.promo_code order.discount = cart.promo_code.discount order.save() for item in cart: OrderItem.objects.create(order=order, book=item['book'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() print("clean cart") # set the order in the session request.session['order_id'] = order.id print("id - check") # launch asynchronous task order_created.delay(order.id) # here I stuck print("clean cart") # redirect for payment return redirect(reverse('payment:process')) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) tasks.py from celery import task from django.core.mail import send_mail from .models import Order @task def order_created(order_id): """ Task to send an e-mail notification when an order is successfully created. """ order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {},\n\nYou have successfully placed an order.\ Your order id is {}.'.format(order.first_name, order.id) mail_sent = send_mail(subject, message, 'archeski.dk@gmail.com', [order.email]) return mail_sent I'm using celery==4.2.0 Django==2.0.7 … -
How to integrate Stripe payments gateway with Django Oscar?
I am trying to integrate the Stripe payment gateway to Django oscar for an e-commerce site which sells physical goods like groceries online.I use python 3.6.3, Django 2.0, Django-oscar 1.6, stripe 1.82.2. Method 1: So I followed this link in django-oscar groups: https://groups.google.com/forum/#!searchin/django-oscar/handle_payment$20override%7Csort:date/django-oscar/Cr8sBI0GBu0/PHRdXX2uFQAJ I have signed up for a stripe account and used my publishable key and test key to configure stripe.The problem is, when I try to pay using the button provided with label "Pay with Card",it collects my card information and then when I click the button, it shows "Some money will be debited from the card" like in this image: Image of Preview page Then after I click the place order button,it shows me this: Image of confirmation page Though I have paid using my card. I guess oscar doesn't seem to know that the payment has been done through stripe already?But I'm not sure how to solve this. Method 2: I tried to use dj-stripe,found here: https://github.com/dj-stripe/dj-stripe But I read the whole documentation on https://dj-stripe.readthedocs.io/en/stable-1.0/ , it seems like I can use it only for products that need subscriptions, mine don't require subscribing and the docs for dj-stripe aren't fully complete. I tried with the official … -
Django 404 error ('Page not found') after runserver
My project is named 'pages', and when I runserver I get this error. Anybody have any clue how to fix this error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in pages_project.urls, Django tried these URL patterns, in this order: admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. My settings.py file looks like this: """ Django settings for pages_project project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*u)%-zmf=2g-c*3z2-&=n=asty5v36n62^90_u*-#83!wb=)eq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', # new ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Django REST framework tests
Risking this question to be too generic... What would be the advised use case types to unit test in a regular implementation of a REST API using the djangorestframework plugin? -
How to display logs using Django
I have a web application running using Django. I want to display the backend activities as logs on the frontend. How do I post such notifications on frontend using Django? Any help is appreciated. -
Django - Show shell output command while process is running
I'm building a django-based web application that needs to run a shell command. For example: I need to show a live output of ping command. With some structures below: Django view: <div class="output-panel"> <span class="live-output">OUTPUT HERE</span> </div> <button onclick="runCommand()">Run Command</button> Javascript: function runCommand() { $.ajax({ type: 'POST', url: '/api/runCommand', success: function(data) { $(".live-output").html(data); } }); } Django function (/api/runCommand url goes to api.runCommand): import subprocess def runCommand(request): cmd = "ping google.com" process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: nextline = process.stdout.readline() if nextline == '' and process.poll() is not None: break sys.stdout.write(nextline) sys.stdout.flush() Is there any way to send the sys.stdout back to my view everytime it generates a new output line ? (Not when the process DONE, but ALONGSIDE with the running process). -
How to restrict NGINX to give media files if user is not authenticated
in the urls i have this url that leads to the serve_protected_file on each time someone is trying to access a media file url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:], views.serve_protected_file, {'document_root': settings.MEDIA_ROOT}) the serve_protected_file looks like this def serve_protected_file(request, path, document_root=None, show_indexes=False): if request.user.is_authenticated: return serve(request, path, document_root, show_indexes) raise Http404() but when i deploy then the files are served with the nginx and it gives me the file trough the url which looks like that https://staging.mywebsite.com/media/img/531126758844.jpg how to restrict it everything in my media folder is private and external access to a file should be restricted unless user is authenticated -
Django: pictures not loading in HTML templates
When I add a random picture inside an HTML it doesn't load at all. Here is how I set up my Django Project: Inside of index.html: {% load static %} <img src='{% static "img/logo2.png" %}'> inside of Production, base and local.py I have this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static/') Thank you in advance if you can help me. -
Ajax not working with Django after some time
I have a Django 2.0 application hosted on VPS and is run by running command in SSH terminal /root/.local/bin/pipenv run /home/user/.local/share/virtualenvs/example.com-IuTkL8w_/bin/gunicorn myapp.wsgi:application --timeout 300 --workers 1 --log-level=DEBUG & Till few hours of running the application server using above command, Ajax requests works fine but after few hours it constantly fails. There are many processes running behind that Ajax request but could not figure out where the request is breaking, since logs displays in console until SSH is live after running the above command. And there is no mean to check for console log after terminating SSH and logging again. Killing all running process and restarting serving using above command again starts working fine for few hours. 1. What could be the reason for this ghost issue? 2. Is there some way to view console log in between anytime after SSH login? 3. If not, how can I set the server to restart automatically periodically (since, it is working again after restarting the server)? -
Can'not save data in SQL table using raw queries in django
import pyodbc con = pyodbc.connect(DRIVER="{SQL Server}",server="...",database="...") cur = con.cursor() db_cmd = "INSERT INTO T_TB(Name,Email,Password)VALUES('324','234','23434')" res = cur.execute(db_cmd) -
I use django and mysql, but the time is wrong when I use DateTimeField
I have two models A and B, B is a foreign key in A and B has a DateTimeField. In a function in A, I get a time: time_temp=timezone.now() then after some code, I use it like: self.B.time=time_temp, then I save it like self.B.save(), but the time in mysql in B always wrong, a little later then time_temp, I don't know why, I need your help -
django Category -id value
here is my code : <div class = 'category_Choose'> <input type='text' name = 'category_id' value="???"> </div> i want value to be the category wich i pressed example : if i choose category Anime i want this field value to be Anime class Category(models.Model): title = models.CharField(max_length=150) category_post = models.ForeignKey('Post', on_delete=models.CASCADE) body = models.TextField() photo = models.ImageField(upload_to='static/images/', default = 'static/images/single_image.png') url = models.CharField(max_length=150) def __str__(self): return self.title here is my model as well how should i do this ? -
Testing enhancements in my website
I am a contributor to an Opensource website for which tests are already written to check whether it's working as expected. Now, when anyone adds another feature in the website involving changes in approximately 15 files(we are using django) and submits a PR, should we ask him/her to write the tests in the same PR or should it be done in another PR? Thanks -
python Django ORM group and order a queryset
In my django project i have to implement a groupped query with ORM and order results for a specific field. I do this: a = tt.objects.filter(thread_status = 'DEAD').select_related().distinct('thread_stag').order_by('-id')[0:20] but the response is an error: ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions How can i do distinct and order_by in same query on different columns? thanks in advance -
Django Rest Framework - get foreignkey id from value when inserting
I can not get a clear answer after two days of searching for what must probably be one of the most common things to do with a DRF: I have the following model: class ProcessedStockAmounts(models.Model): prodName = models.ForeignKey(Productlist, on_delete=models.CASCADE, blank=False, unique=False) amount = models.CharField(unique=False, max_length=255) time = models.ForeignKey(StockTakingTimes, on_delete=models.CASCADE, blank=False, unique=False, default=1) def __str__(self): return str(self.prodName) And I am returning a JSON object via my API that looks like this: [{'prodName': 'SV1', 'amount': '1111111', 'time' : 1}] When I insert my prodName with a value it has no problem, but obviously my user will not know the prodName ID and only the prod name. So when I try to insert the above I get the following error: ValueError: Cannot assign "'SV1'": "ProcessedStockAmounts.prodName" must be a "Productlist" instance. This was the closest I got to an answer and when I do the following it actually inserts: p = ProcessedStockAmounts(amount='33', prodName = Productlist.objects.get(productid = 'SV1'), time = StockTakingTimes.objects.get(times='06:00')) p.save() but giving data this way is obviously defeating the purpose. My serializer looks like the following: class TestSerializer(serializers.ModelSerializer): # time = serializers.SlugRelatedField(read_only=True, slug_field='time') prodName = serializers.CharField() # prodName = serializers.SlugRelatedField(read_only=True, slug_field='prodName') class Meta: model = ProcessedStockAmounts fields = ('prodName','amount','time') With my view: class … -
How to overwrite password_reset HTML templates
What I'm trying to do is overwrite the default HTML templates that django uses for password_reset, password_reset_done, password_reset_confirm,and password_reset_complete. When I added a custom template to the first URL (password_reset) it actually worked perfectly. I could type the email that's associated with the user and proceed with the reset process, but when I tried to add a custom template for the password_reset_done view, the password_reset view no longer works and I get the following error: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Here's my urls.py: from django.conf.urls import url # imports for views at a gloabl level (aka other django apps) from . import views from django.contrib.auth.views import ( login, logout, password_reset, password_reset_done, password_reset_confirm, password_reset_complete ) urlpatterns = [ url(r'^$', views.home), url(r'^login/$', login, {'template_name': 'accounts/login.html'}), url(r'^logout/$', logout, {'template_name': 'accounts/logout.html'}), url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.view_profile, name='view_profile'), url(r'^profile/edit$', views.edit_profile, name='edit_profile'), url(r'^change-password$', views.change_password, name='change_password'), url(r'^reset-password$', password_reset, {'template_name': 'accounts/reset_password.html'}), url(r'^reset-password/done/$', password_reset_done, {'template_name': 'accounts/password_reset_done.html'}), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm, {'template_name': 'accounts/password_reset_confirm.html'}), url(r'^reset-password/complete/$', password_reset_complete, {'template_name': 'accounts/password_reset_complete.html'}) ] NOTE: If I replace password_reset_done and all the others after with their proper name='password_reset_done, name='password_reset_confirm', name='password_reset_complete' parameters everything functions properly, but then I'm stuck with the default templates. here's the urls.py when it functions: … -
Returning objects using JSONRESPONSE
I'm trying to return an object using Jsonresponse, Sorry im newb This is my script: setInterval(function() { $.ajax({ url: '/check_notification/', type: "POST", dataType: 'json', success: function (data) {} }); }, 2000); in my django views.py: def check_notification(request): user = request.user profile = Person.objects.get(profile=user) notification = NotificationRecipient.objects.filter(profile=profile) return JsonResponse(model_to_dict(notification))