Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium WebDriverException: Message: address not available, when running Django test on jenkins server
I have running docker an AWS EC2 instance. Using docker-compose, I have jenkins running in one container. I have a jenkins pipeline which checks out my repo ( which is a Djano application, with a docker file ). My pipeline then builds the docker image using the Docker file. This is build on the host docker daemon as I have mapped these volumes in my docker-compose file volumes: - /var/run/docker.sock : /var/run/docker.sock The image is built successfully, and I can run commands in this image from my jenkins pipeline using img = docker.build(....) img.inside{ sh '.....' } But when I try to run my Django tests using img.inside{ sh 'python manage.py test' } Tests which inherit from TestCase run successfully. But I have tests which are subsets of StaticLiverServerTestCase, they use selenium. I get an error when trying to initialize my Webdriver instance: browser = WebDriver() raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: address not available. These tests run successfully on the exact same setup on my local machine docker-compose run web python manage.py test My guess is that it could be something wrong with AWS security groups and port access. The LiveServerTestCase might by trying to use a port which … -
How to:customise the django Usercreationform Errors
I make a login and registration system with Usercreationform but whenever the user enters some wrong data it appears as normal black text under the field which had an error which doesn't really catch the users attention. How can I edit the html in the error message to make the error red or something like that. -
Media files 'Not Found - the requested resource was not found on this server' however, the media files are there, and they are where they should be
I've just transferred a POSTGRESQL database to my server (for the first time) -which took a while to figure out. Finally I have the thing backed up to where it should be, and my online Django project is logged into the database, the templates are loading and same for the static css. However, none of the images are working. I get a 'Not Found - the requested resource was not found on this server' problem. I've gone into my static/media file to see if the media transferred across, and sure enough, the files are there in the exact place I expect them to be, but Django (or the server?) cannot display them online? Is this a permissions issue? Do I need to set some permissions on my server side to allow the media folder to serve the media to the web requests? -
Django: update form for the extended user model
I have an extended user model in Django 2 and I want to create an update form for it. I have used one-to-one relation between the django.contrib.auth.models.User and my custom Model. Extended user model is: class Employer(models.Model): employer_id = models.AutoField(primary_key=True) address = models.CharField(max_length=400) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) profile_pic = models.ImageField(upload_to='uploads/profile/%Y/%m/%d/', blank=True) @receiver(post_save, sender=User) def save_user_employer(sender, instance, created, **kwargs): if not created: try: instance.employer.save() except Employer.DoesNotExist: pass and my form class is: class EmployerForm(UserCreationForm): address = forms.CharField(max_length=400) profile_pic = forms.ImageField(required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'profile_pic') And in my view class: class EditEmployerView(UpdateView): template_name = 'registration/employer.html' form_class = EmployerForm() success_url = 'dashboard' def get_object(self, query_set=None): return self.request.user In the template, I render the form automatically useing widget-tweaks: {% for field in form.visible_fields %} {% render_field field class="form-control" placeholder=field.label %} {% endfor%} The problem is, in the template form, only the fields of User are filled with the data and fields of Employer are empty. How can make the form to have filled with existing data of both User and Employer class? -
Free online versus paid online
Forgive me this is a totally noob question but i recently started study code.. I read Python was a good place ro start. Still no idea what i want to do, maybe web apps... My questions are a) are online courses worth the buck... I saw this one looks cheap enough https://deals.androidauthority.com/sales/dev-ops-with-cloud-computing-bundle??? Question b) ls there a major difference of what i can achiev with MS Azure pipelines etc and Google cloud platform and console.. Tbh I'm finding MS Azure's on line tutorials and samp. Code a lot easier and helpful.. Any suggestions much appreciated ••• noobie JasonM -
How to upload multiple image file in a custom folder in Django?
I was working on a project where a user can upload multiple images. everything is work fine but Now I want to create a new folder for every user with the custom name with date time just because people cannot overwrite there own image. Like my every file is upload inside assets/uploads/ but I want to create a new folder for each user by there user id and upload there image inside that folder with date time rename. |->assets| | |->uploads | |->1 (folder created by user id) | |->2 (folder created by user id) here is my model.py code class Uqdetail(models.Model): uq_main_id = models.IntegerField(blank=True, null=True) company_id = models.IntegerField(blank=True, null=True) item_name = models.CharField(max_length=255, blank=True, null=True) item_slug = models.CharField(max_length=255, blank=True, null=True) item_image = models.FileField(upload_to='uploads/') # ##### item_image = models.FileField(upload_to='uploads/'+UrgentQueryUserFolder+'/') (I try this by getting error) quantity = models.IntegerField(blank=True, null=True) unit = models.CharField(max_length=45, blank=True, null=True) moq = models.FloatField(blank=True, null=True) lead_time = models.IntegerField(blank=True, null=True) payment = models.CharField(max_length=255, blank=True, null=True) created_by = models.IntegerField(blank=True, null=True, default=0) modified_by = models.IntegerField(blank=True, null=True, default=0) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) deleted = models.IntegerField(blank=True, null=True) I was trying to write a function inside my model to get a current user id for creating user folder by passing that id … -
Web3py AttributeError: 'HTTPProvider' object has no attribute 'manager'
I am trying to use web3 in a Django based web application in a task which is run using celery and kafka. However while trying to use web3.eth module, I am getting the following error : /blockchain_transaction_service.py", line 43, in create_signed_transaction nonce = w3.eth.getTransactionCount(from_address) File "/home/paras/.local/lib/python3.6/site-packages/web3/eth.py", line 234, in getTransactionCount return self.web3.manager.request_blocking( AttributeError: 'HTTPProvider' object has no attribute 'manager' At first I was getting an error that HTTPProvider has no attribute eth, so I followed the cue from this answer, to resolve this error, however I stumbled upon this one. The strange thing is that if I run this without celery it works fine. Below is how my code snippet looks : from web3 import HTTPProvider, Web3, exceptions from web3.eth import Eth from .constants import * from .enums import * from .models import * from .SendOTP import send_gaspod_alert_mail import logging import ast import os import requests import json logger = logging.getLogger(__name__) #Initialize web3 w3 = Web3(HTTPProvider(INFURA_MAIN_NET_ETH_URL)) # Global for exception message in Ethereum transactions OUT_OF_GAS_ERROR_CODE = -3200 OUT_OF_GAS_ERROR_CODE_ETH = -32000 OUT_OF_GAS_MESSAGE = "insufficient funds for gas * price + value" def create_signed_transaction(to_address,from_address,amount,private_key,gas) : data = {} try : if to_address is None or from_address is None or gas is None … -
How to distribute a list of a model into rows and colunms depending on the screen size in django?
I want to break-up a list of a model into rows and colunms which I am iteriating over using a forloop. I have tried {% if forloop.counter|divisibleby:4 %} <div class="row m-3"> <div class="col-12"> <div class="row mt-3"> {% for Collection in object_list %} {% if forloop.counter|divisibleby:4 %} <div class="row mt-3"> {% endif %} <div class="col-6 col-sm-3"> <div class="dark"> <a> <div style="background-image:url({{ Collection.img }})" class="Collection"> </div> <h3 class="title-banner text-center">{{ Collection.Name }}</h3> </a> </div> </div> {% if forloop.counter|divisibleby:4 %} </div> {% endif %} {% endfor %} </div> </div> </div> My poblem is like How to display 2 thumbnails of span6 per row in Bootstrap with Django?. But that solution doesnt suit me because it doesnt allow me to change the group-by variable from the html file. I need to be able to change it because there are only two colums on mobile devices and 4 on computers. Can somebody edit that answer(first one) and post it here so I can change that variable from the html file depending on the screen. -
Django: How to access m2m relationship and use it to create a filepath. Or: how to save a model's relationships first and then the rest
So, assume I have the following (simplified) Django model: class Document(models.Model): def get_file_path(self, filename): extension = filename.split('.')[-1] product_string = ', '.join(p.__str__() for p in self.related_products.all()) return 'documents/{}/{}.{}'.format(product_string, self.document_id, extension) document_id = models.CharField(max_length=9) related_products = models.ManyToManyField(to=Product, related_name='documents') file = models.FileField(upload_to=get_file_path) As you can see I want my filepath based on the contents of the m2m (related_products) relationship. This doesn't work though, and throws the following error: needs to have a value for field "id" before this many-to-many relationship can be used. Which of course makes sense. But, I don't know how to solve it. I either need access to the m2m relationship information before it's saved. Or, I need to save the model and its relationships first without saving the file, and only then save the file specifically. Also, if it matter; this only has to work in the Django Admin. Any help would be appreciated. Thanks! :) -
Dropping pandas dataframe columns
I am trying to drop columns from a dataframe but not working. columns_to_retain = 'name, sex, age' # a string of columns # which will not be dropped # from the dataframe x_cols = columns_to_retain.split(',') new_df = df.drop(columns = not x_cols) The new_df should retain the data and columns name, sex and age. -
Superuser default status active
i have a custom user model. where defaulst is_active=False class User(AbstractUser) is_active=False I want to make an exception where superuser is always active -
how to navigate to other pages by clicking on navbar
how to fix the page not found error when trying to navigate to other pages in django. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/maps.html Using the URLconf defined in wordcount.urls, Django tried these URL patterns, in this order: [name='home'] info/ [name='info'] countries/ [name='countries'] aircomp/ [name='aircomp'] maps/ [name='maps'] The current path, maps.html, didn't match any of these. </li> <li class="nav-item"> <a class="nav-link" href="maps.html">POLLUTION TRACKING</a> </li> -
I am going to live my Project of django on Heroku so when I got a error below is described
So I got error of coomand 'cfe' not found did you mean: command 'xfe' from deb xfe command 'cme' from deb cme . . . Try sudo apt install pip3 install cfe Collecting cfe Downloading https://files.pythonhosted.org/packages/f1/81/dd1edc bb7957a1785dc5f3f31a658eec95a78b30c33b436534ae3e0bc58c/cfe-0.0.15- py3-none-any.whl Installing collected packages: cfe Successfully installed cfe-0.0.15 cfe --upgrade Command 'cfe' not found, did you mean: command 'cfv' from deb cfv command 'cfed' from deb crimson command 'cme' from deb cme command 'xfe' from deb xfe command 'ffe' from deb ffe command 'cfte' from deb fte command 'cfa' from deb python-cf command 'cde' from deb cde Try: sudo apt install <deb name> -
how to creating a like button for all posts with django and jquery?
i want to create a like button for my django website with ajax. I have already created a like button but that button accepts multiple likes from a single user. Now i want create a button which can take one like per user. -
How to set the value of a field in a django model equal to the return of a function
I am trying to make the "available" field equal to the return of a function that uses the "ethAddress" field as a paramater to return the amount of ether in that addresses account. function to get amount of eth in an address def getAddressAmount(address): balance = web3.eth.getBalance(address) return web3.fromWei(balance, "ether") My models.py file from django.db import models from django.urls import reverse from web3apps.getData import getAddressAmount class Advertisement(models.Model): ethAddress = models.CharField(max_length=42, default='') available = getAddressAmount(ethAddress) def get_absolute_url(self): return reverse("advertisement-update", kwargs={"id": self.id}) def __str__(self): return self.ad -
Creating both models and forms from json specification
I would like to automate the creation of a django application (essentially a web page with a simple form). I want to specify the fields/model in a json file and use it as an input to create the model in the database and the forms. My first attempt would be trying to match the django-rest with the forms create by this tool https://json-editor.github.io/json-editor/. Will it work? Is there a better option? -
Device authentication in python/django
I have a Device model in django and I would like to be able to authenticate it. When Sending a request to a login URL with the device_key and udid should return a token, which identifies the Device model, and can be used for further requests. class Device(models.Model): device_key = models.CharField(max_length=100) udid = models.CharField(max_length=100, unique=True) Note: Devices are NOT Users. I already use the User model for different purposes. •Raw passwords never stored on device •SSL Certificate between client and web-app • Steps to authentication: 1.Client device contacts server with json data containing query (username in password) Post data included: •“query” (contains json serialized data) -> [‘username’: (content), ‘password’: (content) 2.Server returns whether or not auth. was successful in JSON format (as JsonResponse) Response included: [ ‘success’: (Boolean), ‘key’: (if successful), ] -
getting error while creating exception DoesNotExist
I have created custom user model using AbstractBaseUser.i have created authentication backends and serializers,in that i have made exception like student.DoesNotExist. but i am getting error "class 'Student' has no 'DoesNotExist' member" and second error is when i'm importing jwt with "import jwt"it says unable to import. i have installed everything.. import jwt from django.conf import settings from rest_framework import authentication, exceptions from rest_framework.authtoken.models import Token from django.core.exceptions import ObjectDoesNotExist def _authenticate_credentials(self, request, token): try: payload = jwt.decode(token, settings.SECRET_KEY) except: msg = 'Invalid authentication. Could not decode token.' raise exceptions.AuthenticationFailed(msg) try: user = Student.objects.get(pk=payload['id']) except Student.DoesNotExist: msg = 'No user matching this token was found.' raise exceptions.AuthenticationFailed(msg) if not user.is_active: msg = 'This user has been deactivated.' raise exceptions.AuthenticationFailed(msg) return (user, token) -
saving two fk in forms through views
I have a system where the user can comment on the company page more with the views I created it does not save the form I need it to take the id of the company profile page and the id or name of the user when you do it when you save the form Story: The user enters the profile of the company X, makes a comment and type an evaluation number for company, when you save this form, I need you to have the company id that is an FK and the name or id of the UserSystem which is a fk too models.py class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) comapany = models.CharField(max_length=50, blank=False) class UserSystema(models.Model): name = models.CharField(max_length=50, blank=False) lastname = models.CharField(max_length=50, blank=False) class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ForeignKey(Usuario, on_delete=models.CASCADE) comments = models.CharField(max_length=255, blank=True) number = models.CharField(max_length=255, choices=NOTA_CHOICES, blank=True) views.py def Comments(request): if request.method == 'POST': form = CommentsForm() form.instance.user = request.user form.instance.name = request.user if form.is_valid(): form = form.save() return redirect('system_profile') else: form = CommentsForm() return render(request, 'profile/comments.html', {'form': form}) -
From a django template, how to display images stored as BinaryField model field?
In my django project I am scraping data with a python script. I temporarily store all the fields in a pandas dataframe before iterating over it to save all the info in a django model. The only way I was able to get this to work was saving the png in the model as models.BinaryField. I use an html template to display the model's fields in a report, but the image comes up as "memory at <>" instead of displaying the image. How can I display the image? report.html <!doctype html> <html> <head> {% load staticfiles %} <meta charset="utf-8"> <title>Sales Report</title> </head> <body> {% for sp in seller_price %} Seller Name: {{ sp.seller_id }} Image: {{ sp.violation_snapshot }} {% endfor %} </body> </html> -
"No changes detected in app 'learning_logs' " I'm following Python Crash Course and ran into this. Unsure
I'm following the Python Crash course to make a website using Django. I'm on page 405 where I'm supposed to modify the database so it can store information related to the model Topic. I just added ''learning_logs',' to installed_apps. Following this, I ran the command, python manage.py makemigrations learning_logs. The result was, 'No changes detected in app 'learning_logs''. I'm not sure why this happened and searches in google pull up stuff from 2017 that doesn't seem to really solve my dilemma. Something I noticed, is that in the book, the picture for installed_apps uses a tuple, but mine uses a regular list []. This difference makes me think that the book is now dated and the guide is no longer valid. -
Sending emails on Django using SMTP and Gmail
I have the following problem with gmail and smtp, i allowed access to less secure apps on my gmail account and i'm able to send emails on my local computer, however when i try to send emails on the remote server that's hosting my application i keep getting SMTPAuthenticationError. I'm not sure what else do i need to do in order for this to work both locally and on the remote server. Anybody have any ideas? I'm using Django 1.11.15 and Python 2.7. These are the settings i have on my application: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_PORT = 587 EMAIL_HOST_USER = "myemail@gmail.com" EMAIL_HOST_PASSWORD = "mypassword" -
Is it possible to set the max_value constraint on a form to be a value from a property on a parent table?
I'm creating a crypto-currency application. In my app a user can have many transactions and a transaction can consist of many sales. I have a form for entering sales and I'm trying to put the max_value constraint equal to a property (coins_remaining) in the transaction table. Is it possible to do this? If so how would I go about it? Sale Form Below class SaleForm(forms.ModelForm): amount_sold = forms.IntegerField(min_value=0.1, label='Enter number of coins sold ', error_messages={'min_value': 'You must enter some coins '} ) total_price_sold = forms.DecimalField() date_sold = forms.DateField( label='Enter Date of Sale ', help_text='Please use calendar by clicking arrow on the right ', widget=forms.TextInput( attrs={'type': 'date'} ) ) note = forms.CharField(label='Write a note below ', widget=forms.TextInput(attrs={'placeholder': 'Keep a Note? '})) class Meta: model = Sale fields = ('date_sold', 'amount_sold', 'total_price_sold', 'note') Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) @property def coins_remaining(self): return self.amount - sum(self.sales.all().values_list('amount_sold', flat=True)) Sale model below class Sale(models.Model): amount_sold … -
installing WHMCS on a Django website gives error page not found
am trying to install whmcs on my django website in a directory www.mysite.com/billing but after installing it and going to the urlmysite.com/billing returns 404 page not found. Is there a way to add the billing URL inside urls.py and install it to work successfully. help . -
How to resize and rename an image at the time that I am uploading it?
I am trying to resize (to create a valid thumbnail) and rename a file when I am uploading it in a view in Django. I saw library PIL and I am using it but with no results. views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.core.files.storage import FileSystemStorage from django.urls import reverse from PIL import Image @login_required def zoom(request): uploaded_url = {} if request.method == 'POST' and request.FILES.getlist('document', False): myfiles = request.FILES.getlist('document') for myfile in myfiles: fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) uploaded_url[filename] = uploaded_file_url imagen = ((Image.open(myfile)).resize((191,176))).save("thumb.png") return render(request, "visores/acercamiento.html", { 'uploaded_url' : uploaded_url, }) acercamiento.html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <h4>Búsqueda general</h4> <input type="file" name="document" accept="image/*" id="b"> <button type="submit" id="subir">Subir imagen</button> </form> {% if uploaded_url %} {% for name, url in uploaded_url.items %} {% load static %} <div id="bai"> <a class="magnifier-thumb-wrapper demo" href="{{ url }}"> <img id="thumb2" src='http://127.0.0.1:8000/media/thumb.png'> </a> </div> {% endfor %} {% endif %} Expected results: /media/P1565.png /media/thumb.png Actual result: /media/P1565.png