Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432?
Hello I occured an error like in title during composing Django web app. I get this error Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? I have no idea how can i solve it, I have already, restarted Postgresql database and docker but I neither of these work. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fitshopuser', 'PASSWORD': 'fitpass', 'HOST': 'localhost', 'PORT': '5432', } } docker-compose.yml version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=fitshopuser - POSTGRES_PASSWORD=postgres ports: - "5432:5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db -
Need to add User fields in Order [Django]
I have model for Order and OrderItem class Order(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) email = models.EmailField() phone = models.CharField(max_length=15) adress = models.CharField(max_length=100) comment = models.TextField() created = models.DateField(default=datetime.date.today()) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity Have Forms for Anonymous User (all fields) and User - only adress and comment fields. class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ('first_name’, 'last_name', 'email', 'phone', 'adress', 'comment') class OrderUserCreateForm(forms.ModelForm): class Meta: model = Order fields = ('adress', 'comment') And I have views for Anonymous User: def my_order(request): context = {} cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() context['order'] = order else: form = OrderCreateForm() context['form']=form return render(request, 'my-app/order.html', context) My problem: How to make a view for an active user so that the fields 'first_name’, 'last_name', 'email', 'phone' are taken from the user??? And for user form class OrderUserCreateForm(forms.ModelForm) or maybe class OrderUserCreateForm(forms.Form)? Or is it possible … -
Pytest patch field's default attribute for inherited django model
I have the following model in common/models.py: from django.db import models from uuid import uuid4 class BaseModel(models.Model): guid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) class Meta: abstract = True In app/models.py I have the following: from django.db import models from common.models import BaseModel class Entity(BaseModel): name = models.CharField() In tests I tried to patch uuid4 in the following ways: def test_model_create(mocker): # Given mock_guid = mocker.patch("uuid.uuid4", return_value="some-guid") # When entity = Entity.objects.create(name="test_name") # Then mock_guid.assert_called_once() assert "some-guid" == entity.guid mock_guid.assert_called_once() returns not called. What can be the issue here? -
Django to_python method of custom models.DateTimeField not receiving the correct value
I have a ModelForm based on a model which includes a customized DateTimeField. The only customization is to override the to_python method so I can convert the 'AM/PM' formatted string into a 24 hr time format that Django will validate. I specified a DateTimeInput widget on the form so I could format into AM/PM notation (format=('%m/%d/%Y %H:%M %p')), which I initialize to the current datetime. The form displays correctly, eg '10/10/2021 04:33 PM' but when the to_python function of the custom field is called, the value passed to it does not include the time; only the date. Also, I don't understand why the to_python method of that field is called (twice) when a listener on another field creates an AJAX call rather than when the Submit button is clicked. I looked at the request data sent when the Submit is clicked, and it does have the full '10/10/2021 04:33 PM'. (I realize the actual conversion in to_python to handle the AM/PM is not done at all; I haven't gotten that far yet). I tried using several popular datetimepickers instead, but none of them solved this problem. models.py: class ampmDateTimeField (models.DateTimeField): def to_python(self, value): print ('initial_date_time = ',value) # Here is … -
How to fix the problem createview is missing a queryset
I'm getting this error CreateBlog is missing a QuerySet. Define CreateBlog.model, CreateBlog.queryset, or override CreateBlog.get_queryset(). It seems like Django thinks that I'm using CreateView without specifying a model. However, my view does define a model. can anybody tell where i am wrong here is view.py file from django.shortcuts import render from django.http import HttpResponseRedirect from django.views.generic import (CreateView, DetailView, UpdateView, ListView, TemplateView, DeleteView) from .models import Blog,Comment,Likes from django.urls import reverse,reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin import uuid # Create your views here. def blog_list(request): return render(request, 'App_Blog/blog_list.html', context = {}) class CreateBlog(LoginRequiredMixin, CreateView): models = Blog template_name = 'App_Blog/createblog.html' fields = ('blog_title', 'blog_content', 'blog_image') def form_valid(self,form): blog_obj = form.save(commit = False) blog_obj.author = self.request.user title = blog_obj.blog_title blog_obj.slug = title.replace(" ","-") + "-" + str(uuid.uuid4()) blog_obj.save() return HttpResponseRedirect(reverse('index')) here is urls.py file from django.urls import path from . import views app_name = 'App_Blog' urlpatterns = [ path('', views.blog_list, name = "blog_list"), path('write/', views.CreateBlog.as_view(), name = "blog/create_blog/"), here models.py file from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name= "Put a title") slug = models.SlugField(max_length = 264, unique=True) blog_content = … -
Django rest framework: Cookies lost after page refresh
i am facing issue with cookies. My login cookies lost when my page redirects to profile page after loggin in. I can see my cookies being set after login success but then they lost when page redirects. profile page fetches the profile first by hitting a get request. Please help me. Its only happening in production not in development server. My backend and frontend has different domains. My login view - class LoginView(APIView): def post(self,request,format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'], ) response.set_cookie( key = "tokenvalidate", value = data["access"][0:len(data['access'])//2], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = False, samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'], #setting this cookie for logout functionality. frontend can remove this non httponly cookie using js in logout function. #if this cookie is not sent in request then the authorization will be failed. ) csrf.get_token(request) response.data = {"Success" : "Login successfully","data":data} return response else: return Response({"No active" : "This account is not active!!"},status=status.HTTP_404_NOT_FOUND) else: return Response({"Invalid" : "Invalid username … -
Django unittests fixture loading error when using --parallel
I am working on a project that has a substantial amount of (Django) unit tests, total run-time about 10 minutes. We're hoping to use --parallel to speed things up a bit, without having to chop op the test suite ourselves. I am running into a fixture problem when running --parallel. Running without --parallel, or using lower values like 1 or 2 work fine. As soon as I chose 3 or higher (--parallel 3), tests start failing with an error about not being able to load the fixture because a column doesn't exist. On consecutive runs, it's different tests failing, sometimes more, sometimes less. ./manage.py test dojo.unittests --pattern="test_a*.py" -v 3 --parallel 4 ERROR: test_full_scan (dojo.unittests.test_apiv2_scan_import_options.ScanImportOptionsTest) Import the ZAP scan with a test file. ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/valentijn/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/valentijn/venv/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/valentijn/venv/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/valentijn/venv/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/valentijn/venv/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'delete_duplicates' in 'field list'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.8/unittest/suite.py", line 163, in _handleClassSetUp … -
Reverse for 'forum_post' with no arguments not found. 1 pattern(s) tried: ['forumpost/(?P<pk>[0-9]+)/$'] How can I do to solve the problem?
I would like to link this function to the link in the base Templates, but I have this error, what solution could be found? Should I use the Reverse function? my views def forumPostList(request, pk): conversation = get_object_or_404(Conversation, pk=pk) form_response = PostModelForm() posts_conversation = Post.objects.filter(conversation=conversation) context = {"conversation": conversation, "posts_conversation": posts_conversation, "form_response": form_response } return render(request, "account/forum_post.html", context) <!-- begin snippet: js hide: false console: true babel: false --> {% extends 'base.html' %} {% block content %} <h1>Received messages:</h1> <hr> <br> {% for post in posts_conversation %} <h3>{{ conversation.title }}</h3> <p>Posts: {{ post.author_post.posts.count }}</p> <p>Posts: {{ post.author_post.username }}</p> {% endfor %} {% endblock content %} my base <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'forum_post' %}">forum_post</a> </li> -
Django change argument value of a custom filter in template
currently i have 2 filters, classroom(recinto) and course(carrera) i want to get only the courses that are assigned to the selected classroom, for that i got models called "CarreraRecinto". Models: class Recinto(models.Model): codigo = models.CharField(max_length=10, unique=True) nombre = models.CharField(max_length=300) class Meta: ordering = ['codigo'] def __str__(self): return f"{self.codigo} - {self.nombre}" class Carrera(models.Model): codigo = models.CharField(max_length=5, unique=True) nombre = models.CharField(max_length=300) def __str__(self): return f"{self.codigo} - {self.nombre}" class CarreraRecinto(models.Model): carrera = models.ForeignKey(Carrera, on_delete=models.CASCADE) recinto = models.ForeignKey(Recinto, on_delete=models.CASCADE) Views: class EditorInventarioView(LoginRequiredMixin, TemplateView): template_name = "pages/editor-inventario/estandar.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["recintos"] = Recinto.objects.values("id", "codigo", "nombre") context["carreras"] = Carrera.objects.values("id", "codigo", "nombre") return context editor_inventario_view = EditorInventarioView.as_view() Filter: @register.filter(name="fc") def filter_carreras(carrera, recinto): qs = Carrera.objects.filter(carrerarecinto__recinto=recinto) return qs template: <div class="col-lg-4"> <label for="laboratorioSeleccionado"> Selecciona Ficha FER: </label> <select class="form-control" id="laboratorioSeleccionado" style="width: 100%;"> {% for recinto in recintos%} <option value="{{ recinto.id }}"> {{ recinto.codigo }}_{{ recinto.nombre }}</option> {% endfor %} </select> </div> <div class="col-lg-3"> <label for="carreraSeleccionada"> Selecciona carrera: </label> <select class="form-control" id="carreraSeleccionada" style="width: 100%;"> {% for carrera in carreras|fc:17 %} <option value="{{ carrera.id }}">{{ carrera.nombre }}</option> {% endfor %} </select> </div> what i need to do, is to change in Template the value "17" from the fc(filter_carreras) based on the selected value from the previous filter … -
Django: store variables in database and pass them between different modules
In my model I'm trying to calculate my user age and create for them an id code and I want this information to be saved in my database, but "age" and "id_code" fields are missing in my database. If I change the name of the function age and id variable are not computed at all. **accounts.models** class UserInformation(models.Model): name = models.CharField(max_length=250) lastname = models.CharField(max_length=250) phone = models.CharField(max_length=250) birthday = models.DateField() age = models.CharField(max_length=2) id = models.CharField(max_length=250) def __str__(self): self.name + '_' + self.lastname + '_' + str(self.birthday.year) def age(self): age = datetime.now().year - int(self.birthdate.year) return age def id_code(self): id_code = self.name + '_' + self.lastname + '_' + int(self.birthday.year) return id_code **accounts.forms.py** class UserInformationForm(forms.ModelForm): class Meta: model = UserInformation fields = ('name', 'lastname', 'birthday', 'phone') **accounts.views.py** def add_information(request): if request.method == 'POST': form = UserInformationForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('home') else: form = UserInformationForm() return render(request, 'add_information.html', {'form': form}) I've also an another models file in another app where I've two quiz for my user. I'd like to save in my database with answers also the id code created in the other models file and use the userinformation answer to create the string name to use … -
deploy django app on aws lightsail containers
WHAT I'M TRYING TO DO AND WHAT I DID i'm trying to deploy a django app through a container in amazon lightsail containers. i've found several tutorial on how to do this but some of them seem to overcomplicate things to such a way that the files became unreadable. in particular everybody start using some complex database but i should be fine using the standard db.sqlite3 of django. finally i stumbled upon this tutorial that seems clear enough. i thought i could simply skip the Postgres part and use the rest of it. it worked. MY CONFIGURATION These are my files that manage the containers. i have multicontainer setup. nginx act as reverse proxy that get all the request and serve static file and media. The other container is the django app. I use docker-compose to build and start the images. Dockerfiles this is the Dockerfile in my app: # pull official base image FROM python:3.9.6 # set work directory its an absolute path WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . and this … -
Cannot add new post via fetch
i'm trying to send new post via fetch, but every time i get these two errors(visible in an image). Could you tell me why i'm getting this errors? fetch('/posts', { method: 'POST', body: JSON.stringify({ body: document.querySelector('#compose-body').value }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); [errors] https://i.stack.imgur.com/7Lp2V.jpg -
Getting a type error at Articles/1/:get() got multiple values for argument 'id'
class Article_List(APIView): def get(self,request): articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) def post(self,request): serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Bad Request class ArticleDetails(APIView): def get_objects(self, id): try: return Article.objects.get(id=id) except Article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def get(self, id): article = self.get_objects(id) serializer = ArticleSerializer(article) return Response(serializer.data) def put(self, request , id): article = self.get_objects(id) serializer = ArticleSerializer(article, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request,id): article = self.get_objects(id) article.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
I want to retrieves all Post objects which have at least one followUser whose user=request.user
FieldError at /en/account/profile/follow_list/ Cannot resolve keyword 'followidf' into field. Choices are: author, author_id, This spanning can be as deep as you’d like. It works backwards, too. While it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model. This example retrieves all Post objects which have at least one followUser whose user=request.user class Post(models.Model): title = models.CharField(max_length=250) excerpt = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favourite = models.ManyToManyField( User, related_name='favouriteUser', default=None, blank=True) avatar = models.ImageField( upload_to=user_directory_path, default='users/avatar.png') bio = models.TextField(max_length=5500, blank=True) fullName = models.CharField(max_length=221, blank=True, default=rand_slug(5) ) dr = models.BooleanField( default=False ) slug = models.SlugField(max_length=250, unique=True, blank=True, default=rand_slug(8)) class followUser(models.Model): folPr = models.ForeignKey(Profile, related_name='followfp',on_delete=models.CASCADE, default=None, blank=True) follUser = models.ForeignKey(User, related_name='followidf',on_delete=models.CASCADE, default=None, blank=True) vote = models.BooleanField(default=True) publish = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.follUser.username @ login_required def follow_list(request): new2 = Post.objects.filter( followidf__followidf=request.user ) return render(request, 'accounts/follow_list.html', {'new': new2 } ) -
AttributeError at /create_order/4 in Django
I am making inline formsets for create new products in each client, but when I try to save it throw me this error views.py: Here im focus in the fuction "createOrder" for create the orders of customers from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.forms import inlineformset_factory from .forms import OrderForm # Create your views here. def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() myFilter_value = OrderFilter() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count, 'myFilter_key':myFilter_value} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): OrderFormSet= inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10) customer = Customer.objects.get(id=pk) form_set_value= OrderFormSet(queryset=Order.objects.none() ,instance=customer) if request.method == 'POST': form_set_value= OrderFormSet(request.POST, instance=customer) if form_set_value.is_valid: form_set_value.save() return redirect('/') context = {'form_set_key':form_set_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form_value = OrderForm(instance=order) if request.method == 'POST': form_value = OrderForm(request.POST, instance=order) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', … -
Django: An alternative to using composite keys
I have the following 2 tables. Discount: id, supplier_id, buyer_id, discount_rate (with supplier_id and buyer_id being unique_together) Product: id, product_name, supplier_id, buyer_id, price Just to explain why I have a buyer_id in my product table: A product is offered to a specific buyer only. So at the time of loading the products into my Product table, I already know who the potential buyer will be. Discounts are not product-specific but rather a supplier would offer a discount specific to the buyer. The discount_rate can change therefore I cannot capture the rate in the product table. So when the user/buyer views a product, I want to get the discount_rate offered by suppliers to that specific buyer and calculate the discounted price. I previously did this in ASP.NET by making the buyer_id and supplier_id composite keys and using that as a foreign key. Since composite keys are not available in Django, how can I get the discount which applies to the buyer/supplier relationship? I can change the database design, any suggestions are welcome. -
How to get data from aa website inside an I frame
Basically, my intention is to scrape an ecommerce website and when the checkout button is clicked in the cart and get the items price and name and images if evailable. I've looked at iframe, but I think it might not work because of same site policy, So I'm asking if anyone has done this before and what's a good method of implementing this. If there is any alternative I would like that, as I wouldn't want to be on the wrong side of the law. -
Remote Postgresql is very slow
I run .py files using Django ORM, that connected to Postgresql server on another server. Both servers working on Ubuntu 20.04 when i run the same file it takes the following time: 2-3 seconds on server with postgresql 8-12 seconds on another server. I tried: Turn off firewall on both servers (sudo ufw disable) Change postgres configs and then restart postgres server Use pgBouncer I checked internet speed on the servers and its normal This is postgresql.conf # Generated by PGConfig 2.0 beta ## http://pgconfig.org # Memory Configuration shared_buffers = 2GB effective_cache_size = 6GB work_mem = 41MB maintenance_work_mem = 512MB # Checkpoint Related Configuration min_wal_size = 512MB max_wal_size = 2GB checkpoint_completion_target = 0.9 wal_buffers = 16MB # Network Related Configuration listen_addresses = '*' max_connections = 1000 # Storage Configuration random_page_cost = 1.1 effective_io_concurrency = 200 # Worker Processes max_worker_processes = 8 max_parallel_workers_per_gather = 4 max_parallel_workers = 8 # Logging configuration for pgbadger logging_collector = on log_checkpoints = on log_connections = on log_disconnections = on log_lock_waits = on log_temp_files = 0 lc_messages = 'C' # Adjust the minimum time to collect data log_min_duration_statement = '10s' log_autovacuum_min_duration = 0 # 'csvlog' format configuration log_destination = 'csvlog' In pg_hba i just insert 1 … -
No: 'noindex' detected in 'X-Robots-Tag' http header
I have this problem with my sitemap No: 'noindex' detected in 'X-Robots-Tag' http header, and I think this is why my sitemap show "Sitemap could not be read" Does anyone has an idea how to solve it. I am using Django this the URL of my sitemap https://www.freeconvert.tk/sitemap.xml #Screenshots https://i.stack.imgur.com/1Z7yF.png https://i.stack.imgur.com/vfs9a.png https://i.stack.imgur.com/GekJU.png #sitemaps.py from convert.models import Snippet from django import http from django.urls import reverse from django.contrib import sitemaps from .models import Snippet class StaticViewsSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = "daily" def items(self): return [ 'home', ] def location(self, items): return reverse(items) class SnippetSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = "daily" def items(self): return Snippet.objects.all().order_by('id') -
Django - pass value from html template to python function
I am trying to spin first Django project and I am struggling how to pass value to python function from html. Basically, I have 1 placeholder with 3 buttons next to it. I have file.html in templates. <form method="POST" action=""> {% csrf_token %} <input type="text" name="name_id" placeholder="placeholder value"/> <input type="submit" value="Value 1"/> <input type="submit" value="Value 2"/> <input type="submit" value="Value 3"/> </form> I am trying to pass placeholder value to views.py. In views.py I have 3 functions. I want to execute only one of them based on value. Value 1 from html triggers function 1 in views Value 2 from html triggers function 2 in views Value 3 from html triggers function 3 in views I am not sure how to handle urls.py All files are in same app/folder Any help is much appreciated. -
How to update Django models from another app?
I have a running Django server using MySQL.I want to modify its models from another python program. I came up with a few ideas. Directly insert data into MySQL (will this reflect on model objects?) Create a REST interface I'm unfamiliar with Django's ORM, what is the right approach? -
django test multiple testcases in for loop
I want to test register view in django project, so I build some fake test cases(self.correct_samples) after register successfully, it should redirect to home page which means the status code should be 302. from django.test import TestCase from django.urls.base import reverse class RegisterTests(TestCase): def setUp(self): url = reverse('account:register') self.response = self.client.get(url) self.correct_samples = ( ('testuser1@email.com', 'testuser', 'test112233', 'test112233'), ('fakeuser@email.com', 'fake123', 'fakeuser111', 'fakeuser111'), ('correct@email.com', 'Jack', 'myfavorite', 'myfavorite'), ('failemail', 'Jack', 'myfavorite', 'myfavorite'), # fail for purpose ) def test_register_form(self): for test_case in self.correct_samples: email, username, password1, password2 = test_case self.response = self.client.post(reverse('account:register'), data={ 'email': email, 'username': username, 'password1': password1, 'password2': password2, }) self.assertEqual(self.response.status_code, 302) self.assertRedirects( self.response, expected_url='/', status_code=302, target_status_code=200) The fourth data in self.correct_samples which is ('failemail', 'Jack', 'myfavorite', 'myfavorite') should be a fail case. but after python manage.py test. It passed. (env) C:\Users\User\myblog>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). C:\Users\User\myblog\env\lib\site-packages\whitenoise\base.py:115: UserWarning: No directory at: C:\Users\User\myblog\staticfiles\ warnings.warn(u"No directory at: {}".format(root)) . ---------------------------------------------------------------------- Ran 1 test in 0.195s OK Destroying test database for alias 'default'... Here comes the tricky thing, it failed after switching order from fourth to first. from django.test import TestCase from django.urls.base import reverse class RegisterTests(TestCase): def setUp(self): ... self.correct_samples = … -
How to solve value error -cannot assign... in Django
I added a new row to my model that assigns the recent project to the page where I can turn on some charts but if I hit the save button I get this error message that I can't figure out why: ValueError at /mpa/project_details/1/ Cannot assign "'1'": "ProjectDetailsAdmin.projekt" must be a "Projekt" instance. views.py @user_passes_test(lambda u: u.is_superuser) def project_details(request, projekt_id): projekt = Projekt.objects.raw('SELECT projekt_id, id FROM stressz_profile WHERE stressz_profile.projekt_id=%s', [projekt_id]) projects_details = Profile.objects.filter(projekt_id=projekt_id) allprojects = Projekt.objects.all() ... lots of queries here context = { ... 'projekt': projekt, 'projects_details': projects_details, 'allprojects': allprojects, ... } if request.method == 'POST': projekt = request.POST.get('projekt') projekt_name = request.POST.get('projekt_name') r01 = request.POST.get('r01') szervkult_adm = ProjectDetailsAdmin(projekt=projekt, projekt_name=projekt_name r01=r01) szervkult_adm.save() return render(request, 'stressz/project_details.html', context) models.py class ProjectDetailsAdmin(models.Model): def __str__(self): return str(self.projekt_name) projekt = models.ForeignKey('Projekt', on_delete=models.CASCADE, default=False, null=True ) projekt_name = models.TextField(max_length=200, null=True ) r01 = models.IntegerField(null=True, blank=True, default=0) class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) html <div class="container bg-warning my-3">Válaszd ki projektet: <select class="form-select" id="projekt" name="projekt" aria-label=""> {% for i in allprojects %} <option>{{ i.id }}</option> {% endfor %} </select> </div> Thank you very much in advance! -
How to use __range in Django
class Order(models.Model): customer = models.ForeignKey('Customer' , on_delete=models.SET_NULL , null= True , blank = True) date_ordered = models.DateTimeField(auto_now_add = True) I have this in order model . Now I want to take order.objects.filter and take only data whose date_ordered is between , date_ordered and ( date_ordered + 7 days ) . Is this possible using __range or not ? -
How do I connect python web app with sql server and create a dynamic queries
I have a project where I have a SQL server with order records and customers records. And I need to create a web app that authenticates the user and then queries the SQL server for this customer's orders using a dynamic SQL query e.g select * from orders where customer_number = "User customer number that is authenticated" What is the best approach to dealing with this? Should I use Django or flask? This is like homework for school I thought it would be easy but I couldn't find anything on the web to approach this. This is how I got started: with a flask. I made a separate database to contain the information about authenticated users, such as their email address, customer number, and a login page. Any guidance will be appreciated. Thanks