Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wishlist items are showing correctly in Django
wishlist column from All_Collections have PK of Wishlist.But this below code pointing to the user id instead Wishlist PK(id). products = All_Collections.objects.filter(wishlist= request.user.id) in this line facing issue Can anyone please help me to solve this. View.py @login_required def wish_list_add(request,id): item = get_object_or_404(All_Collections,id=id) wished_item,created = Wishlist.objects.get_or_create(product_id=item, user = request.user.id) messages.info(request,'The item was added to your wishlist') return redirect('all_collections') @login_required def wish_list(request): data = All_Collections.objects.filter() print("All Collections(product table) : ", data.values('wishlist')) data = Wishlist.objects.filter() print("Wishlist PK : " ,data.values('id')) data1=Wishlist.objects.filter(user=request.user.id).values_list('id', flat=True) print("Wishlist pk values :" ,data1) user_id = Wishlist.objects.filter(user = request.user.id) print('wishlist user :' ,user_id) products = All_Collections.objects.filter(wishlist= request.user.id) print('Wishlist Items : ',products) return render(request=request, template_name="D_Crown/wishlist.html",context={'wishlist': products}) @login_required def wish_list_remove(request,id): item = get_object_or_404(Wishlist,id=id) Wishlist.delete(item.id) return redirect('wish_list') Model.py class All_Collections(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='Images') collection_desc = models.TextField() material_details = models.TextField() price = models.IntegerField() color = models.CharField(max_length=200) shape = models.CharField(max_length=200) review = models.IntegerField() no_purchases = models.IntegerField() offer = models.BooleanField(default=False) offer_percentage = models.IntegerField() new_price = models.IntegerField() exchange = models.BooleanField(default=False) quantity = models.IntegerField() items_left = models.IntegerField() delivery_info = models.CharField(max_length=300) def _str_(self): return self.d_crown_all_collection class Wishlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(All_Collections, on_delete=models.CASCADE) added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username output: Quit the server with CTRL-BREAK. All Collections(product table) : <QuerySet [{'wishlist': 4}, … -
Reverse for 'product_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['products/detail/(?P<slug>[-a-zA-Z0-9_]+)/$']
What I am trying to do I was trying to make urls as human-readable urls with slug, instead of using the pk that Django automatically gives me. What I tried at first time Here are my codes that are relevant to my works. models.py from django.urls import reverse class Product(TimeStampModel): slug = models.SlugField(max_length=80, null=False, default='', editable=False) ... def save(self, *args, **kwargs): from django.utils.text import slugify if not self.slug: self.slug = slugify(self.product_name, allow_unicode)=True super().save(*args, **kwargs) def get_absolute_url(self): kwargs = { 'slug': self.slug, } return reverse('products:product_detail', kwargs=kwargs) views.py ProductListView is the view that shows products from all categories ProductDetailView is the view of detail page of product. from django.views.generic import DetailView, ListView class ProductListView(ListView): model = models.Product template_name = 'products/product_all.html' context_object_name = 'products' paginate_by = 12 paginate_orphans = 5 ordering = 'created' class ProductDetailView(DetailView): model = models.Product template_name = 'products/product_detail.html' context_object_name = 'products' urls.py urlpatterns = [ path('all/', views.ProductListView.as_view(), name='product_list_all'), paht('detail/<slug:slug>/', views.ProductDetailView.as_view(), name='product_detail'), ] templates Directory for template file for ProductListView is templates/products/product_all.html Directory for template file for ProductDetailView is templates/products/product_detail.html <section id="all" class="product-list"> <ul class="item-grid"> {% for product in products %} <li class="item"> <a href="{{ product.get_absolute_url }}"> <img src="{{ product.product_thumbnail.url }}" alt="product-image" class="product-image"> <div class="product-info"> <h1 class="product-name">{{ product.product_name }}</h1> <h2 class="product-price">{{ … -
Django + postgres CI/CD testing guide
Working example for how to implement Gitlab CI/CD testing for Django using postgres? -
Django: create endpoint for a file
I have a mesh.obj file and I would like to create an endpoint for it. For example, the endpoint could be of the form 'path/to/mesh'. How would I do this? -
DRF: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I am creating ecommerce api using Django Rest Framework. This is my order model. I have 2 many to many fields for address and order items. payment_options= ( ('COD', 'Cash on Delivery'), ('BANK', 'Bank Transfer'), ('WALLET', 'Wallet Transfer'), ) delivery_options= ( ('Placed', 'Placed'), ('Processing', 'Processing'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ) order_number = models.AutoField(primary_key=True) items = models.ManyToManyField(OrderItem) order_address = models.ManyToManyField(Address) delivery_date = models.DateTimeField(auto_now_add=False) price = models.FloatField() payment_method = models.CharField(max_length=6, choices=payment_options) delivery_status = models.CharField(max_length=16, choices=delivery_options, default='Placed') class Meta: ordering = ['order_number'] def __str__(self): ord = str(self.order_number) ord_text = "Order #"+ord return ord_text Here is my Serializer: class OrderItemSerializer(serializers.ModelSerializer): prod = ProductSerializer() class Meta: model = OrderItem fields = ["quantity", "prod"] class AdressSerializer(serializers.ModelSerializer): class Meta: model = Address fields =[ "address_1", "address_2", "city", "state", "postcode", "country" ] class CompleteOrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) order_address = AdressSerializer(many=True) class Meta: model = Order fields =[ "order_number", "items", "delivery_date", "price", "payment_method", "delivery_status", "order_address", ] def create(self, validated_data): ord_id = [] address_data = validated_data.pop('order_address') print(address_data) for j in range(len(address_data)): address = Address.objects.create( address_1=address_data[j]['address_1'], address_2=address_data[j]['address_2'], city=address_data[j]['city'], state = address_data[j]['state'], postcode=address_data[j]['postcode'], country=address_data[j]['country'] ) ord_id.append(address.id) item = validated_data.pop('items') ids = [] for i in range(len(item)): prod = item[i]['prod']['name'] count = item[i]['quantity'] product = OrderItem.objects.create( prod=Product.objects.get(name=prod), quantity=count ) ids.append(product.id) Order.order_address = Address.objects.filter(id__in=(ord_id)) … -
Django setup url parameter for certain requests only
So I'm trying to setup my Django view such that when they POST to an endpoint they don't need an url parameters, but when they call GET they require it path('posts/', views.PostView.as_view(), name="post"), path('posts/<int:count>/', views.PostView.as_view(), name="post"), The issue with this is that it makes swagger messy and swagger with assume that url/posts/ you can POST and GET from, and url/posts// you can as well, but I only want to be able to POST to the first and GET from the 2nd. Is there a way to do this without creating separate view classes for them? Or is it better practice in this case to create separate view classes? -
Is it easier to create a web or mobile app using Python and Django? What are the other things I need to know?
I am Python intermediate programmer and have no experience in web or mobile development. I only do wish to create a website using python only. I would really be grateful if you could explain all the necessary stuff I should know in order to this. What I am intending to do is to create a QUiz application. -
The modal message does not show the correct data when I added bootstrap into my django project
**homepage.html** {% for country in countries %} <tr> <th scope="row">{{ country.id }}</th> <td>{{ country.name }}</td> <td align="center"><a class="btn btn-warning" href="{% url 'edit_country' country.id %}">Edit</a></td> <td align="center"><a class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#exampleModal">Delete</a></td> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete post</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure you want to delete {{ country.name }}? </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" href="{% url 'delete_country' country.id %}">Delete</button> </div> </div> </div> </div> </tr> {% endfor %} views.py def homepage(request): countries = Countries.objects.all() context = {'countries':countries} return render(request,'homepage.html',context) models.py class Countries(models.Model): name = models.CharField(max_length=75) landmark = models.CharField(max_length=100,null=True) food = models.CharField(max_length=100,null=True) entertainment = models.CharField(max_length=100,null=True) image = models.ImageField(upload_to='travel', default='default.png',null=True) def __str__(self): return self.name Here I have a problem that when I use the Django component Modal although I used for loop to pass the parameter country the modal message could appear but it does not show the correct {{country.name}} data. I tried clicking the delete button on the second row but the message still only shows the data of the first object instead of the second one. May I ask is there a problem that I put the modal … -
How to remove Set-Cookie header from Django response
I've created a middleware but there doesn't seem to be a Set-Cookie header in the response? But when testing the responses, its definitely there MIDDLEWARE = ( "apps.base.middleware.RemoveHeadersMiddleware", ### ) class RemoveHeadersMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) # No Set-Cookie header here????? # del response._headers['Set-Cookie'] return response -
My HTML and CSS causes this padding issue to happen in Django
I am not sure why when resizing my page this happens around the iPad media query level, and then gets fixed for smaller mobile devices like the iPhone once the toggle hamburger icon appears. It is broken until it goes below 768 x 1080 and above 908 x 1080. A lot of this was copy, and paste as I was trying to understand it, but this is stumping me. If anyone can help explain this issue in detail I would be very appreciative. Navbar HTML: <nav class="sticky-top navbar navbar-custom navbar-expand-md"> <div class="container-fluid"> <a class="navbar-brand abs" href="{% url 'home' %}" >"Pure White Logo Here"</a > <button class="custom-toggler navbar-toggler ms-auto" type="button" data-bs-toggle="collapse" data-bs-target="#collapseNavbar" > <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="collapseNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Home" href="{% url 'home' %}" >Home</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="About" href="#" >About</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Leadership" href="#" >Leadership</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Programs" href="#" >Programs</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="News & Events" href="#" >News & Events</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Chapter Membership" href="#" >Chapter Membership</a > </li> <li class="nav-item"> <a class="nav-link" … -
Should a background process be part of Django project?
I'm trying to build a web app which provide an interface to do some queries upon data extracted from another public API server. To complete the queries in real time, I would have to prefetch the data from the public API server. So I think it is reasonable to separate the app deal with query input(there is still some logic here, so only javascript wouldn't be enough) from the app which runs in background and builds the database which could possibly answer the query in real time. Then what comes to my mind is does this background app really have to be a part of Django project? It runs almost without interacting with any Django component. Except for the database which is also accessible by a Django app and some signals maybe(when to start/stop collecting data, but this could probably also decided internally). What would a be good design choice for my situation? -
How to Dockerize a React-Django where the front-end is served from Django?
I'm new to Docker. I have been surfing through the internet to find any resources for how to Dockerize a React-Django project, in which the React App is served from Django, both running on port 8000, but couldn't find any proper resource for this. Can someone help me with the procedure for Dockerizing a React-Django project having a monolithic architecture? -
Django REST error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'BoundField'
I have a funtion which outputs friday by taking in week number as a parameter def fridayOfWeek(p_week): p_year=2021 monday = datetime.datetime.strptime(f'{p_year}-W{int(p_week )- 1}-1', "%Y-W%W-%w").date() wednesday = monday + datetime.timedelta(days=2) friday = monday + datetime.timedelta(days=6.9) - datetime.timedelta(days=2) return friday but when I serializer data and Set serialize = ExamSimulatorSerializer(request.data) date = fridayOfWeek(serializer["week"]) it gives me and error File "C:\Users\user1\Desktop\backend\data_manager\views.py", line 43, in examSimulator date = fridayOfWeek(m['week']) File "C:\Users\user1\Desktop\backend\week_into_date.py", line 10, in fridayOfWeek monday = datetime.datetime.strptime(f'{p_year}-W{int(p_week )- 1}-1', "%Y-W%W-%w").date() Exception Type: TypeError at /api/exam-simulator/ Exception Value: int() argument must be a string, a bytes-like object or a number, not 'BoundField' my serializer class class ExamSimulatorSerializer(serializers.Serializer): week = serializers.IntegerField() subject = serializers.CharField() code = serializers.CharField() def create(self, validated_data): pass my views.py @api_view(['POST']) @parser_classes([JSONParser]) def examSimulator(request): m = ExamSimulatorSerializer(request.data) code = m['code'] date = fridayOfWeek(m['week']) subject = Subject.objects.get(name = m['subject']) for s in subject.students.all().values(): student = Student.objects.get(roll_num=s['roll_num']) score = random.randint(25,95) Exam.objects.create(code=code, date=date, student=student, subject=subject,score=score) return Response(status=status.HTTP_200_OK) Moreover Is this the right way to make a model-less serializer class -
Fushioncharts msline using python(Django)
I try to use msline chart in Django. I write code in views.py. But i cannot find exact grammer of fusioncharts in msline. dataSource1['dataset'].append({"seriesName": '2012', 'value':['1','2','3','4']}) This code is my question. when I test in web, there is no data shown. I think the way of showing value is not correct. can you help me what is exact grammer or way to make value appear def get(request): # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs. dataSource1 = {} dataSource1['chart'] = { "caption": "Temperatures Today", "subCaption": "test", "xAxisName": "Hour", "yAxisName": "Temp C", "lineThickness": "2", "numberPrefix": "%", "theme": "zune", "showValues": "0", "rotateLabels": "0", "setAdaptiveYMin": "1", "theme": "fusion", } catlist = [] for i in range (4): catlist.append({'label':str(i)}) dataSource1['categories'] = [] dataSource1['categories'].append({'category' : catlist}) dataSource1['dataset'] = [] dataSource1['dataset'].append({"seriesName": '2012', 'value':['1','2','3','4']}) dataSource1['dataset'].append({"seriesName": '2013', 'value':['1','2','3','4']}) dataSource1['dataset'].append({"seriesName": '2014', 'value':['1','2','3','4']}) dataSource1['dataset'].append({"seriesName": '2015', 'value':['1','2','3','4']}) chart1 = FusionCharts("msline", "ex1" , "600", "450", "chart-2", "json", dataSource1) a = str(10) return render(request, 'chart.html', {'output1': chart1.render(), 'data':a}) #render -
Python Separate User Data - User Authentication/Access - Django
I've nearly built a full website using python and Django and now I need to build in separate user data. By this I mean I need to keep the same model and fields and pages but when User1 submits a form and it is displayed User2 who has logged in, the same form is there but User1's data will not be displayed for User2 to see and same for when User2 uploads data. I already have models made and I already have working signup and login. I've found a lot of information on restricting pages for curtain users and other things along those lines but that's not what I'm going for. This website will have a lot of users too so I can't really do something tricky with url's but I could be wrong. My models are very big so I would prefer a solution that automatically does something for all of them but at this point I'll take any solution and any help. Thanks! -
How to translate inline javascript?
So I'm working on a django project and we're having English translated to Czech (not important). I can do fine with regular tags being translated with {% trans 'sample text' %} However, I have a button inside a link and on click, this link returns a confirmation. The full html looks like this <a href="{% url 'foo' %}" onclick="return confirm( 'Sample text')"> <button> {% trans 'Regular trans tag' %} </button> </a> Now I would like to somehow translate the 'Sample text' text inside the confirm, however when I try it with {% trans %} it gives me error that 'foo/bar expected (js)' -
Why am I getting 'module not found' on my project when trying to deploy django with apache and bitnami?
I realize this question has been asked, I've tried the other solutions but can't get the configuration right. I'm using the django instance on aws lightsail. I've followed these tutorials to set it up https://aws.amazon.com/getting-started/hands-on/deploy-python-application/ (but instead of hello world I've cloned my own django project into bitnami/projects https://docs.bitnami.com/aws/apps/weblate/get-started/deploy-django-project/ (I'm using Approach A since that was what it said to use when I ran the test command it gives). I can access the site via the <ip-address>:8000 although it doesn't load resources properly (not sure if this is related, I assume it will resolve once I get my configurations correct.) If I go to the domain or the ip without port 8000, I get a 500 error and the following in the logs [Sat Jul 03 22:52:41.094053 2021] [mpm_prefork:notice] [pid 26130] AH00163: Apache/2.4.46 (Unix) OpenSSL/1.1.1d mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Sat Jul 03 22:52:41.094156 2021] [core:notice] [pid 26130] AH00094: Command line: '/opt/bitnami/apache/bin/httpd -f /opt/bitnami/apache/conf/httpd.conf' [Sat Jul 03 22:52:56.109689 2021] [mpm_prefork:error] [pid 26130] AH00161: server reached MaxRequestWorkers setting, consider raising the MaxRequestWorkers setting [Sat Jul 03 22:52:56.111780 2021] [wsgi:error] [pid 26134] [remote x.x.x.x:61724] mod_wsgi (pid=26134): Failed to exec Python script file '/opt/bitnami/projects/onegoodear/onegoodearstudio/onegoodearstudio/wsgi.py'. [Sat Jul 03 22:52:56.111853 2021] [wsgi:error] [pid … -
How to get first N rows from every category in Django
I have following models, with many to many table, for which I would like to get first 20 news from every category in single response. class Category(models.Model): code = models.CharField(primary_key=True, max_length=45) name = models.CharField(max_length=200, blank=True, null=True) is_active = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'category' verbose_name_plural = 'Categories' class News(models.Model): source_code = models.CharField(max_length=45, blank=True, null=True) title = models.CharField(max_length=1000, blank=True, null=True) image = models.CharField(max_length=2000, blank=True, null=True) link = models.CharField(max_length=1000, blank=True, null=True) published_at = models.DateTimeField(blank=True, null=True) scraped_at = models.DateTimeField(blank=True, null=True) is_active = models.TextField(blank=True, null=True) # This field type is a guess. categories = models.ManyToManyField('Category', through='NewsCategory') class Meta: managed = False db_table = 'news' verbose_name_plural = 'News' class NewsCategory(models.Model): news_id = models.ForeignKey(News, db_column='news_id', on_delete=models.CASCADE) category_code = models.ForeignKey(Category, db_column='category_code', on_delete=models.CASCADE) class Meta: managed = False db_table = 'news_category' unique_together = (('news_id', 'category_code'),) verbose_name_plural = 'NewsCategory' My view class looks like this, and here I would like to add some logic to return 20 rows for each category, for example if I have 5 categories it should return 100 news in single request. class NewsViewSet(viewsets.ModelViewSet): http_method_names = ['get'] serializer_class = NewsSerializer def get_queryset(self): queryset = News.objects.all().order_by('-published_at') sources = self.request.query_params.getlist('sources') if len(sources) > 0: queryset = … -
Why is there no dropdown icon on the Form.Control component?
I created a drop-down select list so a user can choose the quantity of the product he/she wants. The problem is, that there is no drop-down mark (?) on the right of the list. { product.countInStock > 0 && ( <ListGroup.Item> <Row> <Col>Quantity:</Col> <Col xs="auto" className="my-1"> <Form.Control as="select" value={ quantity } onChange={ (e) => setQuantity(e.target.value) } > { [...Array(product.countInStock).keys()].map( (x) => <option key={x} value={x + 1}>{x + 1}</option> )} </Form.Control> </Col> </Row> </ListGroup.Item> ) } This is how it looks like at this moment: and this is how it should properly look like: How can I solve this issue? -
Django Paypal: How To Pass User ID With Webhooks Or In Subscription
I am trying to pass the user id with the webhook or the subscription so that i can know which user has subscribed. I have seen Stripe do this and the ipn methods for paypal do it so is there a way to do this by their REST API? Is there a better way to do this? i have seen a few hack ways of doing it but they don't seem like the best way. I am trying to look for ways so i think i can maybe pass the subscriber id by javascript on approve of the subscription and then use that to identify the user but i would rather not use ways that can be manipulated by javascript. -
Django UNIQUE constraint failed: accounts_users.email
I am setting up a multi user account with Django 3.2.3. The first model works perfectly. It generates the tokens for a login. However the inherited model "company"produces the error UNIQUE constraint failed: accounts_users.email I would appreciate your assistance. My Model class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if email is None: raise TypeError('Users should have a Email') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): if password is None: raise TypeError('Password should not be none') user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user def get_by_natural_key(self, email): return self.get(email=email) class Users(AbstractBaseUser, PermissionsMixin): is_company = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(db_index=True, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' objects = UserManager() def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } def natural_key(self): return (self.first_name, self.last_name) def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class CompanyUserManager(BaseUserManager): def create_company( self, first_name, last_name, name_of_company, company_logo, email, password=None, **extra_fields ): if email is None: raise TypeError('Users should have a Email') user = Company(first_name=first_name, last_name=last_name, email=self.normalize_email(email), name_of_company=name_of_company, company_logo=company_logo ) user.set_password(password) user.save() return user class Company(Users, PermissionsMixin): first_name = … -
Django custom model- unable to make superuser
Forgive me if this may look like an obvious error. I made my own custom User model, called Account, with custom create_superuser() and create_user() methods below: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth import get_user_model from django.urls import reverse from django.db import models from djstripe.models import Customer, Subscription # Create your models here. class AccountManager(BaseUserManager): def create_user(self, username, first_name, last_name, email, university, student_year, is_subscriber, password = None): if not username: raise ValueError("Users must have a username") if not email: raise ValueError("Users must have an email") user = self.model( first_name = first_name, last_name = last_name, username = username, email = self.normalize_email(email), university = university, student_year = student_year, ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, username, first_name, last_name, email, password): user = self.create_user( username = username, email = self.normalize_email(email), first_name = first_name, last_name = last_name, password = password, ) user.university = 'Stanford University' user.student_year = '5th +' user.is_subscriber = True user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self._db) return user def create_staffuser(self, username, first_name, last_name, email, password): user = self.create_user( username = username, email = self.normalize_email(email), first_name = first_name, last_name = last_name, password = password, ) user.university = 'Stanford University' user.student_year … -
Can't redirect from port 80 to Django app in docker using Nginx
I have 3 services in docker: db, nginx, django. version: "3.9" services: db: image: postgres volumes: ... web: build: . command: python3 -m gunicorn mysite.wsgi --bind 0.0.0.0:8000 volumes: - .:/mysite expose: - 8000 depends_on: - db environment: ... nginx: build: ./nginx ports: - 80:80 depends_on: - web I need to redirect my request from http://193.123.12.2 to my Django app and have access to the Django app via HTTP nginx.conf: upstream mysite { server web:8000; } server { listen 80; server_name 193.123.12.2; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } -
Gitlab Django CI/CD postgres: Connection refused
The Error I'm having a lot of trouble getting my Django CI/CD working. I am using Django + postgres, my test cases all pass but I want to implement continuous integration. Note the the following output is from the Gitlab Runner. I keep getting this error: (the ... is where I've left out some detail, but its just traceback or name specific stuff about my project etc.) $ cd src $ python manage.py makemigrations /usr/local/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? warnings.warn( Migrations for 'app': app/migrations/0001_initial.py - Create model ... ... ... $ python manage.py migrate Traceback (most recent call last): ... ... psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? … -
Self-submitting CreateView form
As a newcomer to Django, I'm struggling to achieve my ultimate aim of submitting a form to the same page on which it's defined and displaying values entered in the form within text elements of an SVG diagram, displayed below the form. Thus far, I've managed to create a form using a CreateView and can submit the contents of that form to a separate view which displays the entered values in SVG format... models.py class Diagram(models.Model): val1 = models.FloatField(null=True, blank=True, default=None) val2 = models.FloatField(null=True, blank=True, default=None) def get_absolute_url(self): return reverse('diagram-results', kwargs={'diagram_id': self.pk}) forms.py class DiagramForm(ModelForm): class Meta: model = Diagram fields = ['val1', 'val2'] views.py def show(request, diagram_id): try: diagram = Diagram.objects.get(pk=diagram_id) except Diagram.DoesNotExist: raise Http404("Diagram does not exist") return render(request, 'calc_app/diagram.svg', {'diagram': diagram}) class DiagramCreateView(CreateView): model = Diagram form_class = DiagramForm urls.py urlpatterns = [ path('diagram/add/', DiagramCreateView.as_view(), name='diagram-add'), path('diagram/<int:diagram_id>/', views.show, name='diagram-results'), ] diagram_form.html {% extends "calc_app/base_generic.html" %} {% block content %} <form action="." method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %} diagram.svg <svg width="800" height="600" xmlns="http://www.w3.org/2000/svg"> <text id="val1" stroke="#ddd" y="50.0" x="50.0">{{ diagram.val1 }}</text> <text id="val2" stroke="#ddd" y="50.0" x="50.0">{{ diagram.val2 }}</text> </svg> I'd like to take this one step further and submit …