Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework filter specific columns in csv file base on values
I have a csv file, and I want to filter base on the input value. Age Name Gender Grade 10 Mark male 90 6 James male 85 10 Carl male 93 8 Lucky male 89 10 Ice female 90 Here's my code: @api_view(['GET']) def filter(request): field_value = ['James','Ice'] with open("/path_to_file/grade.csv", 'r') as csvfile: file = csv.reader(csvfile) for row in file : if row[1] == field_value: out = json.dumps(row, ensure_ascii=False) obj = json.loads(out) Name = obj.get('Name') Gender = obj.get('Gender') grade = obj.get('Grade') And the return output should be like this: But I got and error AttributeError: 'list' object has no attribute 'get' Name Gender Grade James male 85 Ice female 90 -
Django + gunicorn timming out on AWS Auto Scaling
I have added my gunicorn + django config to systemd, and when I access "http://EC2_Public_IP:8000" the browser shows the expected result, which is an OpenApi screen. Here is the django.service file: [Unit] Description=Unit for starting a basic Django app [Service] User=ubuntu Restart=on-failure WorkingDirectory=/home/ubuntu/projectName ExecStart=/home/ubuntu/env/bin/gunicorn projectName.wsgi -b 0.0.0.0:8000 [Install] WantedBy=multi-user.target Here is the systemctl status django log: ● django.service - Unit for starting a basic Django app Loaded: loaded (/etc/systemd/system/django.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-07-14 00:07:00 UTC; 27min ago Main PID: 865 (gunicorn) Tasks: 2 (limit: 1134) CGroup: /system.slice/django.service ├─865 /home/ubuntu/env/bin/python /home/ubuntu/env/bin/gunicorn lastmile.wsgi -b 0.0.0.0:8000 └─968 /home/ubuntu/env/bin/python /home/ubuntu/env/bin/gunicorn lastmile.wsgi -b 0.0.0.0:8000 Jul 14 00:07:00 ip-xxxxxx systemd[1]: Started Unit for starting a basic Django app. Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [865] [INFO] Starting gunicorn 20.1.0 Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [865] [INFO] Listening at: http://0.0.0.0:8000 (865) Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [865] [INFO] Using worker: sync Jul 14 00:07:02 ip-xxxxxx gunicorn[865]: [2022-07-14 00:07:02 +0000] [968] [INFO] Booting worker with pid: 968 I tested restarting the EC2 instance e trying to connect to "http://EC2_Public_IP:8000", and it works fine too I also added the EC2 that I used to create … -
Data Scraping using proxy
How can I scrape the data using node js (puppeteer package ) using proxy .I need some useful resources related to it and which is more suitable python or js for scraping data using proxy -
Django Forms - Multi-Step Save Progress Along the Way
Just looking for a bit of a push in the right direction. I'm creating a multi-step user sign up to receive a personalized assessment. But I'm having trouble trying to wrap my head around the multi-step progress within Django and a SQL point of view. These are my steps, each to be a separate form: Sign Up (Make an Account) Complete Profile Information Create an application Complete required questions within application - This may need to be broken down even further. I've figured out redirections from each form, but my biggest concern is saving which step they're up to. E.g. What if they close the browser at end of step 2, how do I have a way to prompt them to come and complete step 3 onwards. To make it clear, I'm not looking for saving the state within the browser. Needs to be saved within the database to support access from other devices, for example. To add onto it, what if I was to allow them to make multiple applications (steps 3 and 4), but only allowing one to be open at a time. E.g. One gets rejected but we allow them to reapply. Just looking for some tips/suggestions … -
Expected behavior of "in" filter in Django-Filter with Graphene
Suppose I have models in Django like so model Foo: bar = ManyToMany(Bar) model Bar: baz = String and some object foo of type Foo, like so: foo.bar = [Bar(baz='fizz'), Bar(baz='buzz')] (so basically, some Foo object with more than 1 distinct related Bar) and then if I create a schema with the following filter field foo_bar__baz: ['in'] and I do a query with fooBarBazIn: ['fizz', 'buzz'], the same foo object is returned twice (whereas if I did only fooBarBazIn: ['fizz'], the object foo would only be returned once). This behavior extends to n related fields and m arguments in the filter; if an object matches k<m of these arguments, it will be returned k times in the resulting query (up to a maximum of n times) - whereas I would expect the same object to only be returned once. Is this behavior intentional? -
How to save the context of an api and use it to create an order history
I am using the transbank api to simulate the purchase of a product through an app of a bank, and I need to save the data generated at the end of the purchase to show them in a purchase history of the user, and I do not know how to do that, thanks in advance. Here is the code of: successful payment @csrf_exempt def pago_exitoso(request, id): if request.method == "GET": token = request.GET.get("token_ws") print("commit for token_ws: {}".format(token)) commercecode = "597055555532" apikey = "579B532A7440BB0C9079DED94D31EA1615BACEB56610332264630D42D0A36B1C" tx = Transaction(options=WebpayOptions(commerce_code=commercecode, api_key=apikey, integration_type="TEST")) response = tx.commit(token=token) print("response: {}".format(response)) user = User.objects.get(username=response['session_id']) perfil = PerfilUsuario.objects.get(user=user) form = PerfilUsuarioForm() producto = Producto.objects.get(id=id) context = { "buy_order": response['buy_order'], "session_id": response['session_id'], "amount": response['amount'], "response": response, "token_ws": token, "first_name": user.first_name, "last_name": user.last_name, "email": user.email, "rut": perfil.rut, "direccion": perfil.direccion, "response_code": response['response_code'], "producto": producto } return render(request, "core/pago_exitoso.html", context) else: return redirect(index) ---- And here is the code : Start payment @csrf_exempt def iniciar_pago(request, id): print("Webpay Plus Transaction.create") buy_order = str(random.randrange(1000000, 99999999)) session_id = request.user.username amount = Producto.objects.get(id=id).precio return_url = 'http://127.0.0.1:8000/pago_exitoso/'+ id # response = Transaction.create(buy_order, session_id, amount, return_url) commercecode = "597055555532" apikey = "579B532A7440BB0C9079DED94D31EA1615BACEB56610332264630D42D0A36B1C" tx = Transaction(options=WebpayOptions(commerce_code=commercecode, api_key=apikey, integration_type="TEST")) response = tx.create(buy_order, session_id, amount, return_url ) print(response['token']) perfil = PerfilUsuario.objects.get(user=request.user) form … -
Python-Pandas How create new column, using a subquery in the same table and get all rows related in one row
SAP pep pep_union 4530020120 1001-17AD400-1.05.03 1001-17AD400-1.05.03/1001-17AD400-2.04 4530020120 1001-17AD400-2.04 1001-17AD400-1.05.03/1001-17AD400-2.04 4530020130 1001-17AD400-5.05 1001-17AD400-5.05 4530020110 1001-17AD400-5 1001-17AD400-5/1001-17AD400-5.05/345 4530020110 1001-17AD400-5.05 1001-17AD400-5/1001-17AD400-5.05/345 4530020110 345 1001-17AD400-5/1001-17AD400-5.05/345 4530020145 not match how can get this result in the same table create new column with all rows related with column "sap" separated by "/" in SQL is something like this SELECT sap, pep, pep_union=isnull(STUFF ( ( SELECT DISTINCT '/' + CAST([pep] AS VARCHAR(MAX) ) FROM [sap_reales] t2 WHERE t2.[sap] = t1.[sap] FOR XML PATH('') ),1,1,'' ),'not match') FROM sap_reales t1 -
django Error Cannot use None as a query value
I'm following a basic search tutorial in https://learndjango.com/tutorials/django-search-tutorial but without the admin. it's throwing an error Cannot use None as a query value but when I go to python shell it's fetching me the studid and studlastname I want >>>from clearance.models import Student >>>query=Student.objects.using('srgb').get(studid__icontains='2012-5037') >>><QuerySet [<Student: Student object (2012-5037)>]> >>>query.studid '2012-2555' >>>query.studlastname 'Michael' views.py class SearchResultsView(ListView): model = Student template_name = 'clearance/search.html' def get_queryset(self): query = self.request.GET.get("q") object_list = Student.objects.using('srgb').get( Q(studid__icontains=query) | Q(studlastname__icontains=query) ) return object_list search.html <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> <h1>Search Results</h1> <ul> {% for result in object_list %} <li> {{ result.studid }} </li> {% endfor %} </ul> -
"Server Error 500" Debug = False - Django
When I want to change Debug to False, I am facing this error : Server Error 505 Who knows why? By the way I deployed it in Heroku. File tree: ─mainfolder ├─.idea ├─all ├─my-project ├─__pycache__ ├─__init.py__ ├─asgi.py ├─settings.py (Above) ├─urls.py ├─wsgi.py ├─env ├─static ├─templates ├─user ├─.gitignore ├─Procfile ├─manage.py ├─requirements.txt Settings.py : import os import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get('DEBUG_VALUE')=='True') ALLOWED_HOSTS = ['mydomain.com','www.mydomain.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "user", "all", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my-project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'my-project.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Cant filter my employers in django project
So, i have a django website, where i have companys with "pages".~ I need to add some employers to that page, but before i add them, i need to check if there is a page created, and then if there is some employers already in that company and i want my result to be "dynamic", so here is how i tried to achieve this: Thats my employer module: class Employer(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=30) funcion = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(default="default.png") facebook = models.CharField(max_length=100, null=True, blank=True) instagram = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name My company model wich is the "father" class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(max_length=30, blank=True, null=True, unique=True) image = models.ImageField(default="default.png") created = models.DateTimeField(auto_now_add=True) about = models.TextField(max_length=800, blank=True, null=True) phone = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=100) email = models.EmailField(blank=True, null=True) slug = models.SlugField(null=False) logo = models.ImageField(default="default.png") welcome = models.CharField(blank=True, null=True, default="Welcome", max_length=200) def __str__(self): return self.company and here is my view, where im getting errors because i dont know how to achieve what i want @login_required def listing_employer(request): try: company = Company.objects.get(user=request.user) except company.DoesNotExist: company = None employers = Employer.objects.filter(company=company) context = { "employers": employers, "company": company, } return render … -
Django Query using Foreign Key
I'm starting to work with queries in django and I'm trying to replicate the results of a join in sql. I have a two models that represent a parent (WaiverAdult) and a child (WaiverMinor). I would like to return the parent and child in the query set, so I can group them in a formatted template, like so: John Dad Tommy Son Amber Daughter Jen Jones Stevie Jones Mike Jones MODELS: class WaiverAdult(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True) class WaiverMinor(models.Model): first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) parent = models.ForeignKey(WaiverAdult, on_delete=models.CASCADE) VIEW: class WaiverListView(ListView): template_name = 'waiver/waiver_list.html' model = WaiverAdult context_object_name = "waiver_list" queryset = WaiverAdult.objects.order_by('created') What is the proper way to write this query? Thank you in advance. I truly appreciate the guidance. -
How to return a value from data base to a function in Django Python?
I'm working in a Python project using Django framework e I'm having some troubles such as: first we have a page to receive a integer value and we submit this value, after we'll have a new page that contains N integer field, where N is the input value from the first page. Below I show models.py: class Numero(models.Model): n=models.IntegerField() def back(self): return self.n class Peso(models.Model): peso=models.IntegerField() def __str__(self): return self.peso class Preco(models.Model): preco=models.IntegerField() def __str__(self): return self.preco views.py é: def index(request): template=loader.get_template('app/index.html') n=0 if request.method=='POST': n = Objetos(request.POST) context={'n': n} return render(request, 'app/index.html', context) def valores(request): template = loader.get_template('app/valores.html') peso=0 preco=0 peso_unitario=[] preco_unitario=[] **N=int(n_objetos)** for i in range(N): if request.method=='POST': peso=Peso_Unitario(request.POST) preco = Preco_Unitario(request.POST) if i == 0: peso_unitario = peso preco_unitario = preco else: peso_unitario.append(peso) preco_unitario.append(preco) context={'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario} return render(request, 'app/valores.html', context) In N=int(n_objetos) **N=int(n_objetos)** is the drouble because I wanna return the value received before. index.html: <form action="/app/valores/" method="POST"> {% csrf_token %} <label for="n_objetos">n_objetos:</label> <input id="n_objetos" type="number" value=""/><br> <label for="peso_maximo">peso_maximo</label> <input id="peso_maximo" type="number" value=""/><br> <input type="submit"> </form> <a href="/app/valores/"></a> valores.html: <form action="% url 'app:Resultados' %" method="POST"> {% csrf_token %} <label for="peso_u">peso_u</label>; <input id="peso_u" type="number" value=""/><br>; <label for="preco_u">preco_u</label>; <input id="preco_u" type="number" value=""/><br>; <input type="submit">; </form> <a href="% … -
when executing docker-compose, Service 'web' failed to build
I get this message in the terminal when I run docker-compose, everything looks good as far as my novice eyes can tell. $ docker-compose up Building web [+] Building 9.3s (8/9) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.8 0.7s => [1/5] FROM docker.io/library/python:3.8@sha256:883e00aeb53d4cecb6842f2e10078a6bc8faf5dbb3d8b2a77cb1a232d81bf7ca 0.0s => [internal] load build context 0.0s => => transferring context: 4.06kB 0.0s => CACHED [2/5] WORKDIR /gekkopedia 0.0s => CACHED [3/5] COPY Pipfile Pipfile.lock /gekkopedia/ 0.0s => ERROR [4/5] RUN pip install pipenv && pip install --system 8.5s ------ > [4/5] RUN pip install pipenv && pip install --system: #8 1.827 Collecting pipenv #8 2.014 Downloading pipenv-2022.7.4-py2.py3-none-any.whl (3.7 MB) #8 3.354 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.7/3.7 MB 2.8 MB/s eta 0:00:00 #8 3.380 Requirement already satisfied: setuptools>=36.2.1 in /usr/local/lib/python3.8/site-packages (from pipenv) (57.5.0) #8 3.426 Collecting certifi #8 3.446 Downloading certifi-2022.6.15-py3-none-any.whl (160 kB) #8 3.488 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 160.2/160.2 KB 3.8 MB/s eta 0:00:00 #8 3.643 Collecting virtualenv #8 3.667 Downloading virtualenv-20.15.1-py2.py3-none-any.whl (10.1 MB) #8 5.486 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.1/10.1 MB 5.6 MB/s eta 0:00:00 #8 5.497 Requirement already satisfied: pip>=22.0.4 in /usr/local/lib/python3.8/site-packages (from pipenv) (22.0.4) #8 5.538 Collecting virtualenv-clone>=0.2.5 … -
Mobile double tap issue
I was developing a website using django. Everything is responsive the way I wanted it to be, but when I change to mobile mode, the dropdown menus needed double tap to send me to the link I wanted. single tap is acting as a hover evenif I don't have hover effect. Here is my code. html code: <ul class="custom-menu"> <li><a href="{% url 'account' %}">{% "Account" %}</a></li> <li><a href="{% url 'orders' %}"></i> {% "Orders " %}</a></li> <li><a href="{% url 'logout' %}"> {% "Logout" %}</a></li> </ul> css code: .custom-menu { position: absolute; padding: 15px; background: #FFF; -webkit-box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.175); z-index: 100; top: 100%; min-width: 200px; opacity: 0; visibility: hidden; -webkit-transition: 0.3s all; transition: 0.3s all; } .dropdown.open>.custom-menu { opacity: 1; visibility: visible; } It works on desktop but it needs double tap on mobile. I have tried using @media (pointer: fine) {}, but it makes the dropdown always visible. Thankyou in advance for your help! -
How to repair ipnyb files?
I accidentally delete jupyter file in VScode and I recover it using a disk drill but now I can not open it. even the code is changed into characters. Please help me out. picture of a file after recovery -
Is it possible to access an SQL database migrated using Django with a JavaScript ORM instead of raw SQL for a microservice architecture?
Suppose that I have an app where the models have been created using Django ORM and Django acts like an API for authentication and gives control to the relation model User using its ORM. At the same time, we want to use Express JS to continuously update a field in one the User model for some feature that requires performance. Is it possible to use a JavaScript ORM with Express JS to update such field? If yes, then how? -
Why does custom delete function didn't work?
I am working on DRF (Django) API I have a simple ModelViewSet. Delete request is working good for this: class BuildingObjectViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = BuildingObjectSerializer queryset = BuildingObject.objects.all() I want to customize delete function. But this delete code works too long time > 1 minute What is the reason of too long time of request? class BuildingObjectViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = BuildingObjectSerializer queryset = BuildingObject.objects.all() def destroy(self, request, *args, **kwargs): instance = self.get_object() deleted_id = instance.pk self.perform_destroy(instance) response = { "message": "BuildingObject has been deleted.", "building_object_id": deleted_id } return Response(response, status=status.HTTP_204_NO_CONTENT) models.py class BuildingObject(models.Model): name = models.CharField(max_length=32) address = models.CharField(max_length=200) urls.py path( "building_objects/<int:pk>/", BuildingObjectViewSet.as_view({ "delete": "destroy", "get": "retrieve", "patch": "partial_update", }), name="building_objects_detail" ), -
Django Cant creat file on desktop after hosting
I have hosted my app i have a problem with the access to desktop my django app can not creat the certain directory this problem appear only when i hosted the app befor that in the local server the file was created also in the python-anywhere i cant not find any file -
Django reset password email not sent
I'm using default django for reset my user password. Strange thing is i can send email in my code, i receive them. BUT only for the reset password from django i never receive email ... My django version is Django==3.1.2 Django settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER ='****@gmail.com' EMAIL_HOST_PASSWORD = '*****' My django URL : path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), The HTML : <form class="form"> {% csrf_token %} {{ form.as_p }} <div class="form-group"> <button type="submit" class="btn btn-pill btn-outline-white font-weight-bold opacity-90 px-15 py-3 m-2">Reset</button> </div> </form> When i click on reset button the URL of the page changed to : http://localhost:8000/password_reset/?csrfmiddlewaretoken=MY_TOKEN&email=*******%40hotmail.com And server send : I can send email using django shell, it's working. I also tried to check if user has is_active True and if user has usable password: [(u.email, u.is_active, u.has_usable_password()) for u in get_user_model().objects.all()] I got : [('******', True, True), ('****', True, True), ('****', True, True), ('*****', True, True)] -
Django Python: Image Upload is not working not working
I am working on a Social Media Website, the base code is from an Open Source Project on GitHub. On the base project you can only post text. I was looking around the Internet and found a instruction to implement img upload. But it doesn't work, because i get a lot of error codes. Error Code: AttributeError: module 'django.forms' has no attribute 'Post' my Code: forms.py from django import forms from django.forms import fields from .models import Post, Comment class Post(forms.Post): class Meta: model = Post fields = ['name', 'Main_Img'] posts.py """ Home page with all posts """ def first(request): context = { 'posts':Post.objects.all() } return render(request, 'blog/first.html', context) """ Posts of following user profiles """ @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.user.post_set.all() posts.append(p_posts) my_posts = profile.profile_posts() posts.append(my_posts) if len(posts)>0: qs = sorted(chain(*posts), reverse=True, key=lambda obj:obj.date_posted) paginator = Paginator(qs, 50) page = request.GET.get('page') try: posts_list = paginator.page(page) except PageNotAnInteger: posts_list = paginator.page(1) except EmptyPage: posts_list = paginator.page(paginator.num_pages) return render(request,'blog/feeds.html',{'profile':profile,'posts':posts_list}) urls.py urlpatterns = [...] if settings.DEBUG: urlpatterns += static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py """ Post model … -
How to import a random model from DB in Django
I am trying to teach myself Django and in doing so I am trying to recreate the popular Wordle game. To start I created a Model named 'Words' which contains 5 letter words. I am trying to generate one of those random words into my views.py where I can then have the user start attempting to guess the word. This is my first time asking a question in stack overflow so I will try and display what I have so far the best I can. Currently in my: Views.py from django.shortcuts import render from .models import Words def home(request): word = random.choice(Words) context = {'word', word} return render(request,'home.html', context) ----- I understand word = random.choice(Words) is not possible, What is the best way to do this? Models.py from django.db import models class Words(models.Model): word = models.CharField(max_length=5) def __str__(self): return self.word -
When to use Lazy translation in Django
When are lazy translated string objects required in Django? From the documentation they say option values like verbose_name and help_text are required to be lazy translated. What about other options like related_name and through? What is the purpose of lazy translating the options verbose_name and help_text? What is the significance of lazy translation for fields being class-level attributes? These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering. This is essential when calls to these functions are located in code paths that are executed at module load time. This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes. For that reason, make sure to use lazy translations in the following cases: class Course(models.Model): def __str__(self): return self.title title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') subscribers = models.ManyToManyField(User, through='Subscription') class MyThing(models.Model): kind = models.ForeignKey( ThingKind, on_delete=models.CASCADE, related_name='kinds', verbose_name=_('kind'), ) -
Problem importing data using django-import-export error NOT NULL constraint failed:
I have set up the django-import-export application in my project and have been trying to import data from an Excel spreadsheet but no luck in getting it to work. I deleted my migration files and data base and generated them again to see if that helped but still the same error. models.py: from django.db import models # Create your models here. class logTimes(models.Model): fast_finished = models.BooleanField(default=False) start_date_time = models.DateTimeField('start fast') end_date_time = models.DateTimeField('end fast') 0001_initial.py: # Generated by Django 4.0.4 on 2022-07-13 22:14 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='logTimes', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fast_finished', models.BooleanField(default=False)), ('start_date_time', models.DateTimeField(verbose_name='start fast')), ('end_date_time', models.DateTimeField(verbose_name='end fast')), ], ), ] admin.py: from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .models import logTimes @admin.register(logTimes) class logTimesAdmin(ImportExportModelAdmin): pass Line 1 and 2 from my spreadsheet: The error message in the admin site when attempting import: Line number: 1 - NOT NULL constraint failed: startandstoptimes_logtimes.start_date_time True, 05/08/2018 17:15:00, 06/08/2018 13:30:00, None Traceback (most recent call last): File "C:\Users\rlead\anaconda3\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\rlead\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: startandstoptimes_logtimes.start_date_time The above … -
Multiple models and one serializer
I have one main model called Profile and three with relation OneToOne to the main model(ProfileFacebook, ProfileGoogle, ProfileTwitter). I would like to create ProfileSerializer, and depending of the request it will give the correct data from specific model and table. class Profile(models.Model): active = models.BooleanField(blank=True, null=True) address = models.CharField(max_length=32, null=True, blank=True) status = models.CharField(max_length=255, blank=True) category = models.CharField(max_length=255, blank=True) preferences = models.CharField(max_length=255, blank=True) class ProfileFacebook(models.Model): profile = models.OneToOneField(Profile, related_name='profile_facebook', on_delete=models.CASCADE) account_uid = models.CharField(max_length=50, blank=True) secret = models.CharField(max_length=50, blank=True) passphrase = models.CharField(max_length=50, blank=True) class ProfileGoogle(models.Model): profile = models.OneToOneField(Profile, related_name='profile_google', on_delete=models.CASCADE) account_uid = models.CharField(max_length=50, blank=True) secret = models.CharField(max_length=50, blank=True) passphrase = models.CharField(max_length=50, blank=True) class ProfileTwitter(models.Model): profile = models.OneToOneField(Profile, related_name='profile_twitter', on_delete=models.CASCADE) account_uid = models.CharField(max_length=50, blank=True) secret = models.CharField(max_length=50, blank=True) passphrase = models.CharField(max_length=50, blank=True) class ProfileSerializer(serializers.ModelSerializer): class Meta(BaseMeta): class Meta(BaseMeta): model = Profile fields = ( 'active', 'address', 'status', 'category', 'preferences' ) profile_fields = ('account_uid', 'secret', 'passphrase') -
How do I append an input from a form in a html template a url?
I have a search bar on my homepage (http://127.0.0.1:8000/wiki/) where I want users to be able to search for entries and be shown the entry through the url. So, if the user searched for css in the search bar, they would be redirected to /wiki/css (/wiki needs to be kept the same). When something is searched the url stays the same, so it is not redirected or might have been redirected to the same page. How do I append the search term to the url without using a different url? HTML: <h2>Wiki</h2> <form action="/wiki/" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> urls.py: urlpatterns = [ ... path('<str:name>', views.wiki_lookup, name='wiki-lookup'), ] views.py: from django.shortcuts import render, redirect, HttpResponse def wiki_lookup(request): term = request.POST.get('q', 'notfound') return redirect('entry', name=term)