Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch JSON data using last filter in Django html template?
I want to get JSON data using last filter in my html template, but only getting key and not value. When I use: # template.html {{ daily_data|last }} I get: {'date': '2021-09-03T00:00:00.000Z', 'marketCap': 2550604613800.0, 'enterpriseVal': 2638345613800.0, 'peRatio': 29.8568111455, 'pbRatio': 40.0575834365, 'trailingPEG1Y': 0.2940443522 When I use: #template.html {% for data in daily_data|last %} {{ data }} {% endfor %} I get: date marketCap enterpriseVal peRatio pbRatio trailingPEG1Y How do I get only the values of marketCap, peRatio and so on? -
SQLite backend does not support timezone-aware times even if USE_TZ = True
I am now developping a small django projects which needs to work with aware datetime.time objects. When the user registers, he has to fill a time input. This data is then transformed to an aware time object in my views.py file just like that: ... if form.cleaned_data['reviews_time']: form.cleaned_data['reviews_time'] = form.cleaned_data['reviews_time'].replace(tzinfo=get_current_timezone()) else: form.cleaned_data['reviews_time'] = time(hour=0,minute=0,tzinfo=get_current_timezone()) *save the created user account* ... The problem is that when I submitt the form, I get the following error : SQLite backend does not support timezone-aware times. Even if I have USE_TZ enabled. I would like to know why this error happens and how to fix it. If anyone could help me I would be very grateful (and feel free to ask for extra code/explanations)enter code here -
request django API using https doesn't work
When I want to request an API using https it doesn't work and I don't know why.. Example : `http://myIp:8888/getValue` --> it works `https://myIp:8888/getValue` --> it doesn't work There is my dockerfile : FROM python:3.7-buster ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ ENV PYTHONUNBUFFERED 1 ENV LANG C.UTF-8 ENV DEBIAN_FRONTEND=noninteractive ENV PORT=8888 RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ python3-setuptools \ python3-pip \ python3-dev \ python3-venv \ git \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* EXPOSE 8888 CMD gunicorn Documents_management_back.wsgi:application --bind 0.0.0.0:$PORT And my docker-compose version: "3.9" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" Someone understand why I can't request using https ? Thanks a lot ! -
How to load image in django server from react build folder?
I have developed a website using react as frontend and django as backend, i have completed the project and made npm run build and i have added the index.html into the django templates DIR and static files which are inside the build folder But logo, favicon.ico and some other images which is inside the public and build folder are not visible in django page which localhost:8000, these logo's are visible in react page which is in localhost:3000 Project Structure: Project |__backend |__settings.py |__urls.py |__base --app |__views.py |__models.py |__build -- reactjs npm run build |__assets - folder which has images |__static -- css and scss folder |__manifest.json |__favicon.ico |__index.html |__public |__src |__static -- django static folder settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static', BASE_DIR / 'build/static', os.path.join(BASE_DIR, 'build/assets'), ] MEDIA_ROOT = 'static/images' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')) ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Errors in terminal: Not Found: /assets/img/icon-img/prev.png [04/Sep/2021 14:06:11] "GET /assets/img/icon-img/prev.png HTTP/1.1" 404 2833 Not Found: /assets/img/logo/logo.png [04/Sep/2021 14:06:05] "GET /assets/img/logo/logo.png HTTP/1.1" 404 2821 Not Found: /service-worker.js [04/Sep/2021 14:05:28] "GET /service-worker.js HTTP/1.1" 404 2800 Not Found: /manifest.json [04/Sep/2021 14:03:50] "GET /manifest.json HTTP/1.1" 404 2788 -
__init__() got an unexpected keyword argument 'required' on in Django unittesting
I got an assertion and a type Error while writing Django's unit test for my application, can anyone please check and help me solving this. Both invalid and valid tests are running fine, only thing differs is the output when form.is_invalid() is called. Error1: Traceback (most recent call last): File "D:\open-source\localflavourtest\test_np\tests.py", line 104, in test_NepalPostalCodeFieldTest self.assertFieldOutput(NepalDetailsTestForm, valid, invalid) File "C:\Users\Asus\Envs\test\lib\site-packages\django\test\testcases.py", line 753, in assertFieldOutput optional = fieldclass(*field_args, **{**field_kwargs, 'required': False}) TypeError: __init__() got an unexpected keyword argument 'required' Error 2 FAIL: test_NepalPostalCodeFieldTest (test_np.tests.NepalCodeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\open-source\localflavourtest\test_np\tests.py", line 113, in test_NepalPostalCodeFieldTest self.assertEqual(form.errors['postal_code'], error_format) AssertionError: ['Ensure this value has at most 5 characters [51 chars]XXX'] != ['Enter a postal code in the format XXXXX'] This is my code I have marked, the line where I am getting these errors, class NepalPostalCodeValidator(RegexValidator): default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXX'), } def __init__(self,*args, **kwargs): super().__init__(re.compile(r'^\d{5}$'), *args,**kwargs) class PostalCodeFormField(RegexField): default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXX'), } def __init__(self,max_length = 5, **kwargs): super().__init__(r'^\d{5}$', max_length = max_length, **kwargs) class PostalCodeField(models.CharField): description = _("Postal Code") def __init__(self, *args, **kwargs): kwargs['max_length'] = 5 super().__init__(*args, **kwargs) self.validators.append(NepalPostalCodeValidator()) def formfield(self, **kwargs): defaults = {'form_class': PostalCodeFormField} … -
django-prometheus missing metrics after restart
I have django-prometheus installed in my app.it exports metrics for me but i have a problem: when server restarts it miss all the metrics and metrics are loosed.is any solution for this? -
TypeError at /register 'CustomUser' object is not subscriptable
I am trying to register a new user and getting this error. I tried other similar issues and solutions but not getting headway. full traceback Internal Server Error: /register Traceback (most recent call last): File "/home/sharhan/DEV/PYTHON/DEVELOPMENT/allauth-tutorial/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/sharhan/DEV/PYTHON/DEVELOPMENT/allauth-tutorial/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sharhan/DEV/PYTHON/DEVELOPMENT/allauth-tutorial/authentication/views.py", line 38, in register_view CustomUser.objects.get(email__iexact=email)[0] TypeError: 'CustomUser' object is not subscriptable register_view in views.py def register_view(request): if request.user.is_authenticated: return redirect('home') else: form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST or None) if form.is_valid(): form.save() user_name = form.cleaned_data['username'] messages.info(request, 'Account created for ' + user_name) return redirect('login') else: form = CustomUserCreationForm(request.POST) else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) models.py class CustomUser(AbstractUser): # add additional fields in here country = models.CharField(max_length=200, null=True, blank=True) age = models.IntegerField(default=False, null=True, blank=True) status = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.email forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ['username', 'email', 'country', 'age', 'status', 'password1', 'password2'] The second is that I'm also trying to implement functionality which I don't know where to start. If a new user uses the same email again to register, it should throw an error. It should be unique and … -
Uploading a file via Angular (using FormData) to django-rest-framework
I have rummaged thru every possible StackOverflow question and blog post online, and I'm still facing issues. I'm trying to upload a file to a django-rest-framework endpoint using Angular 12. This is the frontend code: uploadCameraImage(id: CameraInterface["id"], image: File): Observable<CameraInterface> { const formData: FormData = new FormData(); formData.append("image", image); const httpOptions = { headers: new HttpHeaders({ "Content-Type": "multipart/form-data", "Content-Disposition": `attachment; filename=${image.name}` }) }; return this.http.put<CameraInterface>(`${this.configUrl}/camera/${id}/image/`, formData, httpOptions); } These are the relevang django-rest-framework parts: # This is the main base serializer used for other operations class EquipmentItemSerializer(serializers.Serializer): class Meta: fields = [ 'created_by', 'created', 'updated', 'brand', 'name', 'image', ] read_only_fields = ['image'] abstract = True # This is the base serializer only used for the image upload class EquipmentItemImageSerializer(serializers.Serializer): class Meta: fields = ['image'] abstract = True # This is the main serializer used for all other operations (create/delete...) class CameraSerializer(EquipmentItemSerializer, serializers.ModelSerializer): class Meta: model = Camera fields = '__all__' # This is the serializer used for the image upload in the @action below class CameraImageSerializer(EquipmentItemImageSerializer, serializers.ModelSerializer): class Meta: model = Camera fields = EquipmentItemImageSerializer.Meta.fields # This is the base view set class EquipmentItemViewSet(viewsets.ModelViewSet): renderer_classes = [BrowsableAPIRenderer, CamelCaseJSONRenderer] permission_classes = [IsEquipmentModeratorOrReadOnly] http_method_names = ['get', 'post', 'head', 'put', 'patch'] def get_queryset(self): … -
MailQueue in django!!can we set sender's name instead of the sender's email address in MailerMessage?
This is my code, Can we set sender's name instead of sender's email address using Mailqueue?Anyone help me! -
Django User matching query does not exist on foreign-key relation
I am trying to create a system in django by which user will login through phone number. Used AbstractBaseUser to use the number as user id. Now I am trying to create a foreign key relation of every transaction with the number. While I try to push a transaction it says "User matching query does not exist". I am getting where I made mistake. User model: class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField("Phone number", max_length=100, unique=True, error_messages={ 'unique': ("number_existsssss"), }) name = models.TextField("Name") time_stamp = models.DateTimeField("Time-Date", auto_now=True) request_type = models.CharField(max_length=100, default="check" is_staff = models.BooleanField(verbose_name=('staff status'), default=False) is_active = models.BooleanField(verbose_name=('active'), default=True) Transaction Model: class TransactionModel(models.Model): trxID = models.CharField(max_length=15, null=True, unique=True) User = models.ForeignKey(to=User, to_field="phone_number", related_name='transaction', on_delete=models.DO_NOTHING, default=1) time = models.DateTimeField(auto_now=True, null=True) amount = models.CharField(max_length=5, null=True) pay_method = models.CharField(max_length=10, null=True) amountReceivedFrom = models.CharField(max_length=26, null=True) transactionStatus = models.CharField(max_length=15, null=True, default='False') I think I made some mistake on foreign key relation. the error shows: raise self.model.DoesNotExist( user_signup.models.User.DoesNotExist: User matching query does not exist. [04/Sep/2021 18:44:22] "POST /add-cash/b-kash HTTP/1.1" 500 20728 -
How to update a different models instance based on a PATCH request of a different model in django rest framework?
I have two models, one Master model which stores information coming from batch and trial models. Now what I need is when I perform a PATCH request on the batch I want the Master entries for that batch to be updated as well. But the catch is that I have overridden the save method in a way that whenever I call the save method, all info goes on to the Master model, same goes for trial as well. How can I achieve this? -
Word count in a row
3 larg email messag render slowli 3 profil manag xml pars error 4 click sidebar tab set focu sidebar Suppose this is my txt file dataset in a short form. I want to count every word in a row and replace that word into that word count no. But i can't. In python how to do that code. -
django add parents to field valurs
I have a Product model that has a ManyToMany to Category. Category has a ForeignKey to itself named parent. I want to add all parents of selected category to category field. example for category: digital appliance->None __ Mobile->digital appliance __ Samsung->Mobile and... when choose Samsung for category of a product, I want to add Mobile and digital appliance to category it's my models, the save method doesn't do anything Class Product: class Product(models.Model): STATUS_CHOICES = ( ('s', 'show'), ('h', 'hide'), ) title = models.CharField(max_length=150) slug = models.SlugField(max_length=170, unique=True) category = models.ManyToManyField(Category) thumbnail = models.ImageField(upload_to='images/products', default='images/no-image-available.png') image_list = ImageSpecField(source='thumbnail', processors=[ResizeToFill(400, 200)], format='JPEG',options={'quality': 75}) image_detail = ImageSpecField(source='thumbnail', processors=[ResizeToFill(1000, 500)], format='JPEG',options={'quality': 100}) description = models.TextField() inventory = models.IntegerField() features = models.ManyToManyField(Feature) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='s') def __str__(self): return self.title class Meta: verbose_name = "product" verbose_name_plural = "products" def save(self, *args, **kwargs): for cat in self.category.all(): if cat.parent: self.category.add(cat.parent) return super(Product, self).save(*args, **kwargs) objects = ProductManager() Category and CategoryManager: class CategoryManager(models.Manager): def no_parent(self): return self.filter(parent=None) def get_parent(self, parent): return self.filter(parent=parent) class Category(models.Model): parent = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.SET_NULL,related_name='children') title = models.CharField(max_length=40) slug = models.SlugField() status = models.BooleanField(default=True) -
How to change the Django admin filter to use a dropdown instead of list that can also be searched?
Before you mark this as Duplicate, I have read the solutions to this question. In Django Admin I have lots of values. The team that works on that data, currently can use CTRL+F to atleast find the required field. To fix the UI I have the Dropdown rendering option available in the solution of the question tagged above. But, as I said I need it to be searchable. -
Why would someone set primary_key=True on an One to one reationship (OneToOneField)?
I was watching a video on django-orm and the instructor stated that: We should set primary_key=True to prevent a Model from having duplicate rows in a OneToOne relationship (Ex: Prevent a user from having multiple profiles). I know this statement is wrong! AFAIK, an OneToOne field is just a ForeignKey with unique parameter set to True. But I got curious and looked-up the Django documentation, Sure enough they are using primary=True in their example. class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) So, why would someone set primary_key=True on an OneToOne relation? My guess is that it's just reasonable to have that field as a primary key and there is no technical background behind it. -
In Django project method authenticate returns None
I have a problem with authenticate() method. It always returns None. I checked all my arguments and they are not empty. In models i have USERNAME_FIELD = 'username', in settings i have AUTH_USER_MODEL = 'account.User'. I really cant understand why it's not working. Help please models.py class User(AbstractBaseUser): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='id') email = models.EmailField() username = models.CharField(max_length=25, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) education = models.CharField(max_length=100, blank=True) date_of_birth = models.DateField(blank=True, null=True) name = models.CharField(max_length=25, blank=True) last_name = models.CharField(max_length=25, blank=True) objects = UserManager() USERNAME_FIELD = 'username' views.py class UserLoginView(ObtainAuthToken): serializer_class = UserLoginSerializer serializers.py class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) def validate_username(self, username): if not User.objects.filter(username=username).exists(): raise serializers.ValidationError('User wasn\'t found') print(User.objects.get(username=username).password) return username def validate(self, data): # authentications request = self.context.get('request') username = data.get('username') # test_name password = data.get('password') # newpassword11 if username and password: user = authenticate(username=username, password=password, request=request) print(user) if not user: raise serializers.ValidationError('Invalid password') else: raise serializers.ValidationError('You have to type you\'re mail and password') data['user'] = user return data -
How to access Heroku config variables inside Django settings
I am trying to push my code on Heroku, I have hidden my secret key using environ package but now Heroku is not able to access it since I have ignore my .env files using gitignore, I have read about config vars in Heroku but I am having trouble understanding how do I make Django access those values import os import environ # from .secret import key env = environ.Env() environ.Env.read_env() SECRET_KEY = env('KEY',default=env('SECRET_KEY')) -
How can I order only some specific objects randomly in django?
I have a model with is_random_sortable boolean field and position integer field, I want to sort queryset randomly when is_random_sortable is true, otherwise, I want to order by position field. Imagine I have an object with is_random_sortable=False and position=3. I want to have sorted results like this: (numbers are positions) [15, 6, 9, 3, 11, 7, 10,...] object with position 3 always is on index 3 of the list. And other objects with is_random_sortable=True are sorted randomly. -
Safe way to validate file extension in serializer Django
I created an application where I can store images of products. In the database I store just directions to images which are held in designated folder. In my serializer I need to validate the files names and check if the extensions are photo extensions. I wrote something like this below, is it the best way to checking it? Is there maybe more safe method? ALLOWED_IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "gif"] class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = [...] class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = [..., 'images'] def create(self, validated_data): ... for file in self.context['request'].FILES.getlist('images'): validate_extension(file.name) ... return item def validate_extension(filename): extension = os.path.splitext(filename)[1].replace(".", "") if extension.lower() not in ALLOWED_IMAGE_EXTENSIONS: raise serializers.ValidationError( (f'Invalid uploaded file type: {filename}'), code='invalid', ) -
How to remove loading logo in elastic search?
I add my project an elastic-search <iframe>. When page reloads there are a logo and a loading elastic sentence appears. How can I remove it? -
Django REST Framework, Serializers: Additional data?
Good day, I would like to ask, if there's a possibility to gain additional data inside my serializers? These are my models... models.py class Chair(models.Model): name = models.CharField(max_length=100, null=False, blank=False, unique=True) bookable = models.BooleanField(default=False) user_created = models.CharField(max_length=100) date_created = models.DateField(auto_now_add=True) class Booking(models.Model): chair = models.ForeignKey(Chair, on_delete=models.CASCADE) day = models.DateField() user_name = models.CharField(max_length=100) user_created = models.CharField(max_length=100) date_created = models.DateField(auto_now_add=True) and these my serializers... serializers.py class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = '__all__' class ChairSerializer(serializers.ModelSerializer): class Meta: model = Chair fields = '__all__' When making a request inside js like this... views.py @api_view(['GET']) def bookings_by_date(request, pk): bookings = Booking.objects.filter(day=pk) serializer = BookingSerializer(bookings, many=True) return Response(serializer.data) script.js let url = '...here's my url for Booking...'; fetch(url) .then((resp) => resp.json()) .then(function(data) { // do something here }); ...I would like to get not only the id of the Chair (models.Foreignkey), but also it's name. My first thought was doing something like this... class ChairSerializer(serializers.ModelSerializer): class Meta: model = Chair fields = [ ... 'chair', 'chair__name', ... ] ...but this doesn't seem to work! Does anyone know a solution for my problem? Thanks for all your help and have a great weekend! -
Should i continue learning django i reached intermediate and go with docker and kubernetes or should i start learning react (i am beginner)
What should i learn Learning django with more than a year and made several projects in django. should I continuing django and dig deep into it or should i start learning react as it is emerging. to meet standard -
Django SMTP Send Email Configuration
I already setup the email. It was working perfectly but after sometime it is not working and sending the mail. I don't know where the problem was created. Can someone help me out with this?? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypass' this is my email function code: def my_email(): order = Order.objects.filter(createdAt__gt=Now()-timedelta(minutes=1)) p = str(settings.BASE_DIR) with open(p + '/templates/email.html') as f: order_message = f.read() for o in order: print(o._id) email = EmailMultiAlternatives(subject='Thank you', body=order_message, from_email='laksura.com.bd@gmail.com', to=['sohanur.shanto@northsouth.edu'] ) html_template = get_template('email.html').render() html_template = render_to_string('email.html', {'name': o.user, 'order_id': o._id, 'total': o.totalPrice, 'created': o.createdAt}) email.attach_alternative(html_template, "text/html") email.send() I am getting this error new_conn_created = self.open() File "C:\Python39\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Python39\lib\smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "C:\Python39\lib\smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python39\lib\smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "C:\Python39\lib\socket.py", line 843, in create_connection raise err File "C:\Python39\lib\socket.py", line 831, in create_connection sock.connect(sa) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has … -
Python passing dynamic value to decorator arguments
Is there a way to pass a dynamic value on the decorator's argument from the function that decorates? For example, @cached_property_with_ttl(ttl=authenticate['expires_in']) def authenticate(self): response = requests.post( self.token_url, data={ "client_id": self.__client_id, "client_secret": self.__client_secret, "audience": self.audience, "grant_type": self.grant_type, }, ) return response.json() I want to get the JSON response from the authenticate() function and pass the "expires_in" from the JSON as a value to the decorator's ttl argument which decorates the authenticate function. -
postgis.control is not found on github actions
In my github actions yml, it can't find postgis.control. But, if find /usr -name postgis.control did, it can find postgis.control. I don't know why test can't find postgis.control.. Any idea? name: Django CI on: push jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7] services: postgres: image: postgres:12 ports: - 5432:5432 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ghostlabs_localhost options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: psycopg2 prerequisites run: | sudo apt-get update && sudo apt remove -y postgis* postgresql* && sudo apt-get install -y libpq-dev gdal-bin postgresql-12 postgresql-12-postgis-3 postgresql-12-postgis-3-scripts postgresql-contrib-12 echo "-----" find /usr -name postgis.control - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements/localhost.txt - name: Run Tests run: | python manage.py migrate && python manage.py test Log shows ----- /usr/share/postgresql/12/extension/postgis.control But, test has Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.7.11/x64/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedFile: could not open extension control file "/usr/share/postgresql/12/extension/postgis.control": No such file or directory