Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a model attribute based on another attribute?
I have a very simple Item model, when I create a new istance, let's say through the admin dashboard, I want my slug to be generated automatically based on the title attribute, for ex: if the title is "my item title" the slug should be "my-item-title". class Item(models.Model): title = models.CharField(max_length=100) @property def slug(self): slug = str(self.title).replace(' ', '-') return slug def get_absolute_url(self): return reverse('core:item_detail', kwargs={'slug': self.slug}) But slug is not a column in the db, so I cannot get an Item istance using the slug value, I have to query using the title attribute. # my view def detail_view(request, slug): item = get_object_or_404(Item, title=str(slug).replace('-', ' ')) context = {'item': item} return render(request, 'detail.html', context) # my urls path path('product/<slug>', detail_view, name='item_detail') My question is: is there a way to automatically generate a slug attribute based on title so I can query the db using slug? -
issue with passwords with special character (#) using read_default_file
I'm relatively new to Django and am looking to read my MySQL connection info from a file using the read_default_file process. I test this on Windows and it seems to work perfectly. I move to my linux pre-prod server and i get an issue access issue. Through countless hours of testing, i find that the issue seems to be with my password contains a special character # and it seems that this process is translating that to mean the start of a comment. I have no control over the password and need to be able to handle this character. on a side note, if i load the details directly into my django app (settings.py) then i have no issue and all is fine, but if i try to offload them into my conenction file, this situation arises. I have looked but cannot seem to find a way to escape the PW to handle this character (and arguably others). What am i missing and is there a way to handle passwords with special characters like my situation? Cheers! -
Django: ValueError: Prefetch querysets cannot use raw(), values(), and values_list()
I am trying to run prefetch as below and gives me error: Prefetch querysets cannot use raw(), values(), and values_list(). queryset = SymbolList.objects.prefetch_related( Prefetch('stock_dailypricehistory_symbol',queryset = DailyPriceHistory.objects.filter(id__in=[1,2,3,4]).values('close','volume'))).all() DailyPriceHistory model has lot of columns, i only want close and volume Here id__in=[1,2,3,4] is just shown for example, it can go upto 10000+ ids at a time. -
How to work with an existing sql server database
I am starting my practices as a programmer, but I have a problem and that is that in the company where I am they gave me a test database that has 60 thousand data, I read the documentation where it says how to obtain the tables, I can do it, but at the moment of obtaining them these tables come with integer data in their foreign keys, is there any way to user the tables with the django orm, this my models: from django.db import models class TipoNovedad(models.Model): id_tnov = models.AutoField(db_column='Id_TNov', primary_key=True) # Field name made lowercase. nom_nov = models.CharField(db_column='Nom_Nov', max_length=100) # Field name made lowercase. desc_nov = models.CharField(db_column='Desc_Nov', max_length=250) # Field name made lowercase. manejo_tiempo = models.CharField(db_column='Manejo_Tiempo', max_length=20) # Field name made lowercase. dias = models.CharField(db_column='Dias', max_length=20, blank=True, null=True) # Field name made lowercase. estado = models.BooleanField(db_column='Estado') # Field name made lowercase. class Meta: db_table = 'Tipo_Novedad' class Novedades(models.Model): id_nov = models.AutoField(db_column='Id_Nov', primary_key=True) # Field name made lowercase. # is in the foreign key of the novelty model id_tnov = models.IntegerField(db_column='Id_TNov') # Field name made lowercase. n_identificacion = models.CharField(db_column='N_Identificacion', max_length=20) # Field name made lowercase. fec_registro = models.DateTimeField(db_column='Fec_Registro') # Field name made lowercase. fec_inicio = models.DateField(db_column='Fec_Inicio', blank=True, null=True) # … -
How to create charts in django
How to create a line chart that gives daily updates in django and js. i want to know the theory of creating a daily analysis line chart in django. That show the data of whole week, and it's max value each day. Like in any graph. -
Django -- Can I pass everything from several tables in one object?
I'm working on a website that will have different types of posts. I want to create a model for each. So I would have a table of Blog Posts, a table of Review Posts, a table of Vlog Posts, etc. On the home page, I want to pass in all of these, sorted by date an arbitrary date field. I'm aware that I can pass them in as several objects, each sorted from their own table, but that doesn't help me determine if a blog post is newer than a vlog post. Is there a way that I could say something like the following: allPosts = "SELECT * FROM BlogPosts, VlogPosts, ReviewPosts ORDER BY Date", then pass this from the view into the template? Or is there a way that I can create a table that contains all of these posts using Foreign Keys? The idea is that I want to display the newest post in a certain area, then display the rest in order. Thanks -
How to create FIle object from base64 to sent it Django
On client i have code url = 'http://127.0.0.1:8000/api/create_post/' headers = {'Authorization': 'Token c63ee5854eb60618b8940829d2f64295d6201a96'} image_string = None with open("21485.jpg", "rb") as image_file: image_string = base64.b64encode(image_file.read()) data ={ 'text':'new_post_python', 'image':image_string } requests.post(url, json=data,headers=headers) and i want to create some post with api on server i have code class CreatePostView(APIView): permission_classes = (IsAuthenticated,) def post(self,request,format=None): Post.objects.create( text=data.get('text'), author=request.user, image=..., ) return Response({'created': True}) Where from .models image = models.ImageField(upload_to='posts/', blank=True, null=True) How can i built image from base64 string on server side ? -
How to filter locations by custom area in django?
I’m to allow user to draw his custom area on frontend (flutter) and pass it to backend (django +postgis) which must return list of PointFields thats are lies inside the curve. So, in which format should I pass the curve to the backen and how do I properly filter the places queryset? -
Django media files are not showing up after IIS deployment
I am trying to deploy a webpage. My project is written in Django and I am trying to deploy it on Microsoft server using IIS. I have made static files to work successfully, however I could not do the same with media files. Can you please help? This is my IIS: This is file I used to configure static files, which I located under static folder: I tried to do the same thing with media config file in the media root folder, however it does not work: any help please? Thank you! -
Including a certain url in urls.py makes the wrong view function execute
My main application is called lpbsmain, and I have another app called dashboard. lpbsmain/urls.py includes path('main/', include('dashboard.urls')) in the urlpatterns variable. dashboard/urls.py looks like... from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ #path('', views.dashboard, name='dashboard'), path('<str:useremail>/', views.dashboard, name='main'), path('base_dash/', views.base_dashboard, name='baseDash') ] dashboard/views.py has two view functions, dashboard() and base_dashboard() import requests, json from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth import logout def base_dashboard(request): print("base dashboard view func print statement") return render(request, "base-main-dashboard.html") @login_required(login_url='/login') def dashboard(request, useremail): if request.user.is_authenticated: # removed code in this conditional because it's not relevant return render(request, "index.html", {'Past30Dates':json.dumps(past_30_dates), 'Past30Values':json.dumps(past_30_values), 'Past60Dates':json.dumps(past_60_dates), 'Past60Values':json.dumps(past_60_values), 'fullEmail':useremail, 'shortenedEmail':shortenedEmail}) else: redirect("login") The problem: So if you try to go to the url /main/base_dash, my intent is to see base-main-dashboard.html. Instead, I actually see index.html. From adding print statements, I see that whenever I go to the url /main/base_dash/, the view function dashboard(useremail) is actually being executed, not base_dashboard(). Normally, dashboard(useremail) gets executed from the url main/<useremail> as expected. But now it's also executing at that url and main/base_dash. The only way this stops is if I remove path('<str:useremail>/', views.dashboard, name='main'), from dashboard/urls.py. Then, if … -
at-rule or selector expectedcss(css-ruleorselectorexpected) on CSS code in Django on style tags[VS CODE]
<style> .button{ -moz-box-shadow: 0px 10px 14px -7px #276873; -webkit-box-shadow: 0px 10px 14px -7px #276873; box-shadow: 0px 10px 14px -7px #276873; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #599bb3), color-stop(1, #408c99) ); background:-moz-linear-gradient( center top, #599bb3 5%, #408c99 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#599bb3', endColorstr='#408c99'); background-color:#599bb3; -webkit-border-top-left-radius:8px; -moz-border-radius-topleft:8px; border-top-left-radius:8px; -webkit-border-top-right-radius:8px; -moz-border-radius-topright:8px; border-top-right-radius:8px; -webkit-border-bottom-right-radius:8px; -moz-border-radius-bottomright:8px; border-bottom-right-radius:8px; -webkit-border-bottom-left-radius:8px; -moz-border-radius-bottomleft:8px; border-bottom-left-radius:8px; text-indent:0; display:inline-block; color:#ffffff; font-family:arial; font-size:15px; }</style> Tried including "html.validate.styles": true in my settings.json file but error still shows.I copied this code from a css generator online and edited the class name as shown. My <a> link looks like this <a class="button">href='{% url 'login' %}'</a> -
Filter query set using Django rest serializer
I have two serialiser and one of them is used in another. class CommentSerializers(ModelSerializer): class Meta: model = Comment fields = ['id','text', 'author','approved' , 'created_date'] read_only_fields = ['author' ,'approved' ,'created_date'] and then class PostSerializers(ModelSerializer): likes_count = serializers.SerializerMethodField(read_only=True) comments = CommentSerializers(source='comment_set', many=True, read_only=True) post_media = PostMediaSerializers(source='postmedia_set', many=True, required=False) class Meta: model = Post fields = [ 'id', 'text', 'likes_count', 'likes_count', 'post_media', 'author', 'approved', 'comments','created_date', ] read_only_fields = ['author', 'approved', 'comments','created_date',] As you see I get comments on a post and I nest it there so that every post comes with its comments. The challenge is getting is that I only wanted to show users approved posts. How can I filter the comments_set? -
NoReverseMatch at /Raccourcisseur/
Reverse for 'redirection' with arguments '('',)' not found. 1 pattern(s) tried['Raccourcisseur/Lien/(?P[^/]+)/$'] [About errors][1] #urls.py# from django.urls import path from . import views urlpatterns = [ path('', views.liste,name='liste'), path('nouveau/',views.afficher,name='afficher'), path('Lien/<str:code>/',views.redirection,name='redirection'), ] #urls.py(global)# from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('Raccourcisseur/',include('mini_url.urls')), ] #views.py# from django.shortcuts import render,redirect,get_object_or_404 from .models import MiniURL from .forms import MiniURLForm def afficher(request): if request.method == "POST": form = MiniURLForm(request.POST) if form.is_valid(): form.save() return redirect(liste) else: form = MiniURLForm() return render(request,'mini_url/index.html',{'form':form}) def liste(request): minis = MiniURL.objects.order_by('-acces') return render(request, 'mini_url/liste.html', locals()) def redirection(request,code): """ Redirection vers l'URL enregistrée """ mini = get_object_or_404(MiniURL, code=code) mini.acces += 1 mini.save() return redirect(mini.url, permanent=True) #index.html# {% extends 'mini_url/base.html' %} {% block title %} RaccourcisseurUrl {% endblock%} {% block body %} <h1>Raccourcir une URL </h1> <form method="post" action="{% url 'afficher' %}"> {% csrf_token %} {{form.as_p}} <input type="submit"/> </form> {% endblock %} #liste.html# {% extends 'mini_url/base.html' %} {% block title %} Page RaccourcisseurUrl {% endblock%} {% block body %} <h1>Le raccourcisseur d'URL spécial </h1> <p></p><a href="{% url 'afficher' %}">Raccourcir une url </a></p> <p>Liste des URLs raccourcies : </p> <ul> {% for mini in minis %} <li>{{ mini.url }} via <a href="http://{{ request.get_host }}{% url 'redirection' mini.code %}"> {{ request.get_host … -
Adding django celery beat using persistent scheduler
I am running a Django app that is not using django-celery-beats. At the moment I have setup a worker which starts the beats persistent scheduler. I've created the below in tasks.py: @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(3.0, test.s('hello'), name='add every 3') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg) I can't see that this is working. Is there any other config I need to add. I can't use the database scheduler in my requirement so I cant use the celery beats package. Any guidance or instructions are appreciated. -
PrimaryKeyRelatedField or Nested Relationships in Django REST
My issue is I want to get this: output "counter": 1, "reference": { "ref": "a", "name": "apple", "description": "a fruit" }, "stock": 10, serializers.py with PrimaryKeyRelatedField class StockSerializer(serializers.ModelSerializer): counter = serializers.PrimaryKeyRelatedField(queryset=Counter.objects.all()) reference = serializers.PrimaryKeyRelatedField(queryset=Reference.objects.all()) class Meta: model = Stock fields = ['counter', 'reference', 'stock'] serializers.py with Nested Relationships class ReferenceSerializer(serializers.ModelSerializer): class Meta: model = Reference fields = ['ref', 'name', 'description'] class StockSerializer(serializers.ModelSerializer): counter = serializers.PrimaryKeyRelatedField(queryset=Counter.objects.all()) reference = ReferenceSerializer() class Meta: model = Stock depth = 2 fields = ['counter', 'reference', 'stock'] If I use PrimaryKeyRelatedField I have only the id but if I use Nested Relationships I have to fill all fields but it already exists I want to select among a list -
Django duplicates URLS
I'm new to Django. In my project, when I want to proceed the next page, it generates a duplicate URL. Here is my homepage URL: http://127.0.0.1:8000/ If I want to view a specific customer's profile, I expect the URL should be like this: http://127.0.0.1:8000/customer/1/ But I'm getting this: http://127.0.0.1:8000/customer/customer/1/ I would be grateful if anybody could help me, I'm a noob. Here is my urls.py: from . import views urlpatterns = [ path('', views.home, name = 'home'), path('products/', views.products, name = 'product'), path('customer/<str:pk>/', views.customer, name= 'customer'), path('create_order/<str:pk>/', views.createOrder, name = 'create_order'), path('update_order/<str:pk>/', views.updateOrder, name = 'update_order'), path('delete_order/<str:pk>/', views.deleteOrder, name = 'delete_order'), ] My views.py: from django.http import HttpResponse from django.forms import inlineformset_factory from django.urls import reverse from .models import * from .forms import OrderForm def home(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders, 'customers':customers, 'total_orders':total_orders,'delivered':delivered, 'pending':pending} return render(request, 'accounts/dashboard.html', context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html', {'products':products}) def customer(request, pk): customers = Customer.objects.all() customer = Customer.objects.get(id=pk) orders = customer.order_set.all() orders_count = orders.count context = {'customer':customer, 'orders':orders, 'orders_count': orders_count} return render(request, 'accounts/customer.html', context) def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10) customer = … -
Django admin page OperationalError at /admin/products/product/add/
I'm getting the following error when I make changes in the admin page: OperationalError at /admin/products/product/add/ In the admin page there is and product column, where I can add new products. I am able to access the admin page but after adding product's name, price, stock, image, whenever I click on save button it is giving me this error. Please make any suggestions on this, I am new in django. I am adding the codes: models.py from django.db import models from django.db.models.fields import CharField class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() admin.py from django.contrib import admin from .models import Product admin.site.register(Product) I have done migrations several times but it is still showing this error.:-( -
docker-compose up doesn't find the other container hosts
For an unknown reason, I ran into a docker error when I tried to run a docker-compose up on my project this morning. My web container isn't able to connect to the db host and nc still returning web_1 | nc: bad address 'db' There is the relevant part of my docker-compose definition : version: '3.2' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER= - POSTGRES_PASSWORD= - POSTGRES_DB= mailhog: # mailhog declaration volumes: postgres_data: I've suspected the network to be broken and it actually is. This is what I get when I inspect the docker network relative to this project : (docker network inspect my_docker_network) [ { "Name": "my_docker_network", "Id": "f09c148d9f3253d999e276c8b1061314e5d3e1f305f6124666e2e32a8e0d9efd", "Created": "2020-11-18T13:30:29.710456682-05:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.19.0.0/16", "Gateway": "172.19.0.1" } ] }, "Internal": false, "Attachable": true, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": {}, // <=== This is empty ! "Options": {}, "Labels": { "com.docker.compose.network": "default", "com.docker.compose.project": "my-project" } } ] Versions : Docker : 18.09.1, build 4c52b90 Docker-compose : 1.21.0, build … -
Password hashing error in Django 3.1.4 - hashers.py
Today when I started my Django project I got error: 'str' object has no attribute 'decode' After research I figured out that it is problem in hashers.py file in django.contrib.auth library. Somehow it stopped working I am not sure if it is after Django update or anything else. This error appears when app is registering new User or when i try to Login existing User. My code to login user looks like this: from django.contrib.auth import authenticate user = authenticate(username=email, password=password) code to register user like this: user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], phone=validated_data.get('phone', None) ) also here is my User Model class: class User(AbstractUser): email = models.EmailField(_('email'), unique=True) username = models.CharField(_('username'), max_length=255, blank=True) phone = PhoneField(_('phone'), blank=True) status = models.IntegerField(_('status'), default=11) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: # db_table = 'label_user' verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, … -
Connecting Django web interfaces with Python
I am trying to connect a button on my web interface to a program running behind Python. I feel it sounds weird so I'm just going to give a scenario for better visualisation of the problem. When a submit button is clicked on the web application, it will call a function running behind a python program on the back end to process the submitted information (encryption/converting the data into another format) then store it in a database or file server. How do I code it on Django as well as in Python? -
Django and AWS S3: Storing and securing private files
I have a Django app that will invoke an API call (a Python function) to create a folder with a private S3 bucket. To invoke the function, a user will have to be logged in first. The S3 bucket will look like this: s3://somebucket/user1 s3://somebucket/user2 and so on API call: https://somedomain.com/createfolder/user1 I don't want to allow user2 to call the API by substituting the user1 string with his username. Assuming I can secure this API call, my Python function will then just go ahead and create a folder with the username given to it. user1 will also have the ability to download only his/her files. users can log in to my app via OAuth2 or username/password. The questions: a. How do I secure my API so that user2 cannot commit actions on user1? b. Similarly, how do I create pre-signed URLs pointing to user1's file (a specific file, which could be a zipped form of a folder? My research: I have heard of JWT and pre-signed URLs, but I'm having difficulties in understanding how to practically implement them in Django. -
Why we add templates path in DIRS in django?
I am confused here to find the proper answer why we add templates in DIRS in settings.py like below: TEMPLATES =[ .... 'DIRS': [os.path.join(BASE_DIR,'templates')], .... ] I have checked that if I don't add templates in DIRS then the tempates and leave it empty then templates is also working. Can anyone please explain what's the difference? Many Thanks -
Run Python service and calculation code in different venv
I need to run Django service on Python 3.8 and some calculation code on Python 3.5 inside a Docker container. How to achieve that? I am thinking: Install miniconda of Python 3.8 to path /usr/miniconda Install anaconda of Python 3.5 to path /usr/anaconda Start Django service with /usr/miniconda/bin/python For each incoming request, use os.system("/usr/anaconda/bin/python calculation.py") to calculate My questions are: I need pip install packages for each code / module. For example, Django, djangorestframework for Django service, numpy and pandas for calculation.py. How to install them separately in different venv in one Docker container. I can use Python 3.8 as the base, and Python 3.5 as the venv. Will the os.system("/usr/anaconda/bin/python calculation.py") execute calculation.py in the Python 3.5 with the venv. In another word, will it be executed in the context of all packages needed, no more no less? How to pass the parameters needed by the calculation.py and get the result back? Thanks! -
Reading only x amount of bytes from a binary file
def streamView(request): # zip_path = './pages/data.zip' zip_path = './pages/data/test.txt' start_index = 0 end_index = 50 with open(zip_path, 'rb', 50) as fin: fin.seek(start_index) data = fin.read(end_index - start_index) response = HttpResponse(fin, content_type="application/zip") response["Content-Disposition"] = f"attachment; filename={zip_path}" return response So I'm using the above code to read just the first 50 bits of a file and return them. However, this just returns the entire file to the user. Ideally, I would like to send start and end parameters to this function, and then just read between those two points, and send that data. How can I acheive this? -
Django | search for same values in specific table field & add/subtract depending on another field
I'm just a bit lost right now programming my first Django app. I want to create something like a portfolio overview for stock market investments. So every time I add an order to my app overview statistics etc. change. Right now I have my order table, that contains all the orders that are made. Orders should have all the information that are needed for further analyses. This the the model: class Order(models.Model): name = models.CharField(max_length=100) ko_identifier = models.BooleanField() order_price = models.FloatField() quantity = models.FloatField() order_value = models.FloatField() order_fees = models.DecimalField(decimal_places=2,max_digits=5,default=0.0, null=True) order_commission = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) stock_exchange_fees = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) courtage_fee = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) own_fees = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) transaction_fee = models.DecimalField(decimal_places=2,max_digits=5,default=0.0) transaction_fee_sum = models.FloatField() order_date = models.DateTimeField('order date') #order_date = models.DateTimeField(auto_add_now=true) order_wkn = models.CharField(max_length=6) order_isin = models.CharField(max_length=12) order_direction = models.ForeignKey(OrderDirection, null=True, on_delete= models.SET_NULL) order_place = models.ForeignKey(OrderPlace, null=True, on_delete= models.SET_NULL) and here you find a simplyfied import file: later of course the table will contain hundreds / thousands of entries. where I have difficulties: I need to create at least two views on this table Current Portfolio finished "trades" so somethink like this for the current portfolio: and somethink like this for sold positions: so how: can I loop through the table and display all the …