Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple StreamBuilder using same data source
Directly connecting to websocket using Streambuilder works seamlessly but I tried to make the stream part of the provider so that I can access the stream data in multiple widgets without encountering the "Bad State: Stream has already been listened to". Is this a best way of handling multistreaming of data, if not what are my options? Websocket server is part of Django Code for provider is mentioned below late final WebSocketChannel _fpdSockets; Map _webSocketMessages = {}; Map get webSocketMessages { return _webSocketMessages; } WebSocketStreamProvider() : _fpdSockets = IOWebSocketChannel.connect( Uri.parse('ws://127.0.0.1:8000/ws/socket-server/'), ); Stream<Map<String, dynamic>> get dataStream => _fpdSockets.stream .asBroadcastStream() .map<Map<String, dynamic>>((value) => (jsonDecode(value))); void sendDataToServer(dataToServer) { print("Sending Data"); _fpdSockets.sink.add( jsonEncode(dataToServer), ); } void closeConnection() { _fpdSockets.sink.close(); } handleMessages(data) { print(data); _webSocketMessages = data; // notifyListeners(); } } -
ModuleNotFoundError: No module named 'students.urls.py'; 'students.urls' is not a package
i am just a beginner in python learning from tutorials i can't just run the server, i followed the same steps mentioned in that tutorial but its showing me this error, i searched for some possible answers on stack overflow but couldn't find any answer that could resolve my issue, hopeless what to do with this, my directory structure is as in python console in pycharm its showing me this error Error:Cannot run program "C:\Users\Dell\PycharmProjects\webProject\venv\Scripts\python.exe" (in directory "C:\Users\Dell\Desktop\mydjangoproject"): CreateProcess error=2, The system cannot find the file specified in pycharm terminal its showing me this error > res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Dell\Desktop\mydjangoproject\mydjangoproject\urls.py", line 7, in <module> path('mydjangoproject', include('students.urls.py')), File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) … -
Box SDK client as_user request requires higher privileges than provided by the access token
I have this code in my Django project: # implememtation module_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) # get current directory box_config_path = os.path.join(module_dir, 'py_scripts/transactapi_funded_trades/config.json') # the config json downloaded config = JWTAuth.from_settings_file(box_config_path) #creating a config via the json file client = Client(config) #creating a client via config user_to_impersonate = client.user(user_id='8********6') #iget main user user_client = client.as_user(user_to_impersonate) #impersonate main user The above code is what I use to transfer the user from the service account created by Box to the main account user with ID 8********6. No error is thrown so far, but when I try to implement the actual logic to retrieve the files, I get this: [2022-09-13 02:50:26,146: INFO/MainProcess] GET https://api.box.com/2.0/folders/0/items {'headers': {'As-User': '8********6', 'Authorization': '---LMHE', 'User-Agent': 'box-python-sdk-3.3.0', 'X-Box-UA': 'agent=box-python-sdk/3.3.0; env=python/3.10.4'}, 'params': {'offset': 0}} [2022-09-13 02:50:26,578: WARNING/MainProcess] "GET https://api.box.com/2.0/folders/0/items?offset=0" 403 0 {'Date': 'Mon, 12 Sep 2022 18:50:26 GMT', 'Transfer-Encoding': 'chunked', 'x-envoy-upstream-service-time': '100', 'www-authenticate': 'Bearer realm="Service", error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."', 'box-request-id': '07cba17694f7ea32f0c2cd42790bce39e', 'strict-transport-security': 'max-age=31536000', 'Via': '1.1 google', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"'} b'' [2022-09-13 02:50:26,587: WARNING/MainProcess] Message: None Status: 403 Code: None Request ID: None Headers: {'Date': 'Mon, 12 Sep 2022 18:50:26 GMT', 'Transfer-Encoding': 'chunked', 'x-envoy-upstream-service-time': '100', 'www-authenticate': 'Bearer realm="Service", error="insufficient_scope", … -
Django Filtering Objects
I have here some issue with the Product.objects def say_hello(request): queryset = Product.objects.filter(collection__id=1) return render(request, ‘hello.html’, {‘name’: ‘Mosh’, ‘products’: list(queryset)}) I get the Error: Unresolved attribute reference ‘objects’ for class ‘Product’.:6 It returns no list on: http://127.0.0.1:8000/playground/hello/ Does somebody know what can be the issue? -
my python anywhere website is not loading all my statics
hello i have uploaded my Django project to Pythonanywhere but not all my statics are loading for example some images are missing it is not because i didnt load my staticfiles correctly if that is the case my site wouldnt load css but it does -
Adding custom_password field to UserSerializer without registering it to User model in Django REST API
I need a way to add the confirm_password field in the data my CreateUserView returns without creating it explicitly in my user model. I tried doing the following but it raised TypeError at /user/create/ User() got unexpected keyword arguments: 'confirm_password'. How can I solve this issue? Thank you for all the response Here is my code: serializer.py class CreateUserSerializer(serializers.ModelSerializer): confirm_password = serializers.CharField( max_length=100, write_only=True, required=False ) class Meta: model = User fields = [ "id", "email", "password", "confirm_password", "first_name", "last_name", ] extra_kwargs = {"password": {"write_only": True}, "id": {"read_only": True}} def create(self, validated_data): return User.objects.create_user(**trim_spaces_from_data(validated_data)) views.py class CreateUserView(CreateAPIView): permission_classes = [permissions.AllowAny] serializer_class = CreateUserSerializer def create(self, request, *args, **kwargs): queryset = User.objects.filter(email=request.data["email"]) if queryset.exists(): raise CustomUserException("Provided email address is already in use") if not "confirm_password" in request.data.keys(): raise CustomUserException("Confirm password field is required") if not request.data["password"] == request.data["confirm_password"]: raise CustomUserException("Passwords does not match") serializer = CreateUserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=200, data=serializer.data) -
Django python - how do add new record every time I update the screen? instead it updates the existing record.?
How do add new record every time I update the screen? instead it updates the existing record.? -
Django - Redis distributed lock
Django 4.0.6 Django-redis 5.2.0 Is usage like this: with caches["redis"].lock("bob", ttl=900, timeout=300, retry_delay=15): dostuff supposed to work on a ElastiCache cluster in cluster mode from k8s pods? Seems like I'm getting multiple instances getting into the locked area. -
How to make a query across multiple models in Django
I'm using Django and I want to know how to get objects through 3 models These are my models class Participant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_leader = models.BooleanField(default=False) team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="participants") application_date = models.DateField(auto_now_add=True, null=True) resolution_date = models.DateField(null=True, blank=True) accepted = models.BooleanField(default=False) class Team(models.Model): name = models.TextField(default="") is_public = models.BooleanField(default=False) institution = models.ForeignKey(Institution, on_delete=models.CASCADE, null=True, related_name='teams') campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, null=True, related_name='teams') class Campaign(models.Model): name = models.TextField(default="") description = models.TextField(default="") initial_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) end_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) qr_step_enabled = models.BooleanField(default=True) image_resolution = models.IntegerField(default=800) sponsor = models.ForeignKey(Sponsor, on_delete=models.CASCADE, null=True, related_name='campaigns') I have the user through a request, and I want to get all campaigns of that user. I tried doing it with for loops but I want to do it with queries this is what I had: user = request.user participants = user.participant_set.all() for participant in participants: participant.team.campaign.name is there a way to make a query through these models and for all participants? A user can have many participants, and each participant has a Team, each team has a campaign -
Error when trying to Serialize a ManyToMany relationship (Django with DRF)
I'm getting an error when I try to serialize a many-to-many relationship The error description that is shown to me in the console is this: AttributeError: Got AttributeError when attempting to get a value for field product on serializer Ped_ProDetail. The serializer field might be named incorrectly and not match any attribute or key on the Product instance. Original exception text was: 'Product' object has no attribute 'product'. The models involved in the relationship are written like this: class Produto(models.Model): valor_unitario = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) nome = models.CharField(max_length=75) descricao = models.TextField() genero = models.CharField(max_length=10, default="Indefinido") qtd_estoque = models.IntegerField() cor = models.ForeignKey(Cor, on_delete=models.PROTECT, related_name="produtos") tamanho = models.ForeignKey( Tamanho, on_delete=models.PROTECT, related_name="produtos" ) marca = models.ForeignKey(Marca, on_delete=models.PROTECT, related_name="produtos") class Pedido(models.Model): endereco_entrega = models.ForeignKey( Endereco, on_delete=models.PROTECT, null=True, related_name="pedidos" ) forma_pagamento = models.ForeignKey( Forma_Pagamento, on_delete=models.PROTECT, null=True, related_name="pedidos" ) usuario_dono = models.ForeignKey( get_user_model(), on_delete=models.PROTECT, related_name="pedidos" ) data_entrega = models.DateField() data_pedido = models.DateField(default=date.today) finalizado = models.BooleanField(default=False) qtd_parcela = models.IntegerField() valor_parcela = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) preco_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) itens = models.ManyToManyField(Produto, related_name="pedidos", through="Ped_Pro") class Ped_Pro(models.Model): produto = models.ForeignKey( Produto, on_delete=models.PROTECT, related_name="ped_pros" ) pedido = models.ForeignKey( Pedido, on_delete=models.PROTECT, related_name="ped_pros" ) qtd_produto = models.IntegerField(default=1) data_entrada = models.DateTimeField(default=datetime.now) The serializers: class ProdutoSerializer(ModelSerializer): class Meta: model = Produto fields = … -
How to autofill form based on the selected 'id' using javascript or ajax in django
I am new ,i want to autofill form when i select vehicle id from template .hre is my models . class Fuel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) previous_km = models.IntegerField(blank=False, null=False) progressive_km = models.IntegerField(blank=False, null=False) when i select vehicle then corresponding vehicle previous_km automatically filled in form. here a write simple javascript code manually but i want to take from database. <script> let usersData = [ { id: 1, email: "u1@gmail.com", fname: "fname-1", lname: "lname-1", previous_km : 1000, }, { id: 2, email: "u2@gmail.com", fname: "fname-2", lname: "lname-2", previous_km : 2000, }, ]; document.getElementById('vehicle').onchange = (e) => { let selectedUser = usersData.find(userdata => userdata.id == e.target.value); console.log(selectedUser); document.getElementById('previous_km').value = selectedUser.previous_km; }; -
didnot insert email on field in django rest framework
i insert email field on API but cannot insert. the code is here below if user.group == 'passenger': #request to all drivers passenger_trip = Trip.objects.filter(passenger=user) #display only id and status field of trip model and passenger email passenger_trip = passenger_trip.values('id', 'status', 'created', 'updated', 'pick_up_address', 'drop_off_address', 'price', 'passenger__email') return passenger_trip and response of API on thundredclient is below:- [ { "id": "412f04aa-3b34-4ee4-a07f-e464cff148c3", "created": "2022-09-12T12:27:31.542074Z", "updated": "2022-09-12T12:27:31.542091Z", "pick_up_address": "pokhar", "drop_off_address": "kathmand", "price": "20", "status": "REQUESTED" }, { "id": "6629e234-a723-4e5c-a44d-e272e7b3a124", "created": "2022-09-12T13:04:22.309149Z", "updated": "2022-09-12T13:04:22.309166Z", "pick_up_address": "pokhar", "drop_off_address": "kathmand", "price": "20", "status": "REQUESTED" } -
Django Model Exception on Pre-existent Database: Cannot resolve keyword 'user' into field. Choices are: organization_id
I'm currently building Django model classes for an already existing database. We have three tables: Organization, User, and UserOrganizationMap. This is because there is a Many-to-Many relationship between the tables Organization and User (a user can belong to multiple organizations and an organization has multiple users). I had to explicitly create the UserOrganizationMap model class since it exists in the database already and I cannot use the one that would be created by Django. This is the code to create those models: This the code to create those models: class Organization(models.Model): organization_id = models.UUIDField(primary_key=True) organization_name = models.TextField() class Meta: app_label = 'myapp' # each model will require this managed = False db_table = 'organization' class User(models.Model): user_id = models.UUIDField(primary_key=True) user_name = models.CharField() organizations = models.ManyToManyField( to=Organization, through='UserOrganizationMap', through_fields=('fk_user', 'fk_organization'), ) class Meta: app_label = 'myapp' # each model will require this managed = False db_table = 'user' class UserOrganizationMap(models.Model): fk_user = models.ForeignKey( User, on_delete=models.CASCADE, db_column='user_id',) fk_organization = models.ForeignKey( Organization, on_delete=models.CASCADE, db_column='organization_id',) class Meta: app_label = 'myapp' # each model will require this managed = False db_table = 'user_organization_map' When I tried to iterate over the users I get the following Error users = User.objects.all() for user in users: print(user.user_id) print(user.organizations.all()) … -
How to get a fjango file instance from pyexcelerate workbook?
I have recently checked the pyexcelerate to help improve the performace of exporting a pandas data frame to excel file i have the following code values = [my_df.columns] + list(my_df.values) wb = Workbook() wb.new_sheet('outputs', data=values) wb.save('outputfile.xlsx') I have a django model that has a filefield into it how can i save the generated wb to a django file field ? -
Http Response Python
like the response.json() does not display anything but on the other hand the response.text displays the results how to loop through response.text Exemple de mon code def api: url = 'http://api-content/product/GetProduct' x = requests.get(url) content=x.text "produits":[{ "des":"blaa", "cont":"sdf" }] Merci de votre aide -
How can i auto update my database in django rest?
I have to make a order status, where there are 3 columns: orderId, item_name, status. An order can have multiple items, and every item can have diferemt status. So what i have to do is an endpoint that return the status of the order. Example: if the order 1, has 3 items, and 2 of the items have the status: "Shipped" and the other is "Pending", the expected result of that order status is "Pending", because not all the item have been shipped. models.py from django.db import models import requests class OrderStatus(models.Model): choice = (('SHIPPED', 'SHIPPED'), ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED')) OrderNumber = models.CharField(max_length=255, unique=True) status = models.CharField(max_length=255, choices=choice) def __str__(self): return self.OrderNumber class OrderItems(models.Model): id = models.AutoField(primary_key=True) choice = (('SHIPPED', 'SHIPPED'), ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED')) itemName = models.CharField(max_length=255) OrderNumber = models.ForeignKey(OrderStatus, related_name='items', on_delete=models.CASCADE) status = models.CharField(max_length=255, choices=choice) def __str__(self): return self.status Views.py from rest_framework.viewsets import ModelViewSet from OrderStatus.api.serializers import OrderRegisterSerializer, NumberOrderSerializer from OrderStatus.models import OrderItems, OrderStatus class OrderApiViewSet(ModelViewSet): serializer_class = OrderRegisterSerializer queryset = OrderItems.objects.all() class OrderNumberApiviewSet(ModelViewSet): serializer_class = NumberOrderSerializer queryset = OrderStatus.objects.all() serializers.py from OrderStatus.models import OrderItems, OrderStatus from rest_framework import serializers class OrderRegisterSerializer(serializers.ModelSerializer): #items = serializers.RelatedField(many=True, queryset = OrderItems.objects.all()) class Meta: model = OrderItems fields = ['itemName', 'OrderNumber', 'status'] … -
If the username or password is invalid when logging in, how can appear an error on page without refreshing itself, Django
I have a login pop-up and I want after typing wrong username or password to appear a error message, like usual 'Username or password is incorrect', but after pressing button on the site, it is refreshing and I need to open my pop-up again in order to see the error, how can I do the error msg to appear without refreshing the page. Views.py def main(request): form = CreateUserForm() if "register-btn" in request.POST: .... elif "login-btn" in request.POST: username = request.POST.get('username-log') password = request.POST.get('password-log') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/account') else: messages.info(request, 'Username or password is incorrect') #here I don't know what to write for the purpose of appearing the #error messages on the page without refreshing it return render(request, 'accounts/main.html', context) Main.html ( briefly ) <label>Your login</label> <input name="username-log" class="form-control" type="text" placeholder="Enter your login"> <label>Password</label> <input name="password-log" class="form-control" type="password" placeholder="Enter your password"> {% for message in messages %} <p id="messages" class="xerr"> {{message}} </p> {% endfor %} <button name="login-btn" class="btn btn_100" type="submit">LOG IN</button> -
How to return 404 and 500 errors in json formats instead of standard html pages in Django 4.x
I found only very stale articles on the Internet that don't quite solve my problem. I tried this way, but Django still returns html pages: exceptions.py def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: if response.status_code == 500: response.data = {"code": 500, "message": "Internal server error"} if response.status_code == 404: response.data = {"code": 404, "message": "The requested resource was not found on this server"} return response settings.py REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'backend.exceptions.custom_exception_handler', } -
Stripe; Webhook that triggers when the current subscription gets ended (not cancelled)
I know that there is a webhook type customer.subscription.deleted that gets triggered when a user cancels the subscription (that is they don't want the subscription to be auto-renewed after it ends) so at this webhook event, we just update the users subscription state to cancel but they still have the subscription active (and that is expected) but is there any webhook event that gets triggered when the subscription ends or we have to do that manually? I saw this webhook event but i'm not sure if this is the one I'm searching for subscription_schedule.completed Any guidance would be helpful, thank you :) -
Display the number of comments of each post related to the same post in django
Hello friends I am building a blog and I have encountered a problem. My problem is that when I want to display the number of comments for each post, on the main page of the blog number of comments displays all posts that have comments, but the number of comments for each post is the same. In the event that post 2 has 3 comments and the other has 1 comment. You can see in this picture. Image This is my models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() comment = models.CharField(max_length=500) active = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return "{} by {}".format(self.comment, self.name) This is my views.py def post_list(request): posts = models.Post.objects.filter(status='published') paginator = Paginator(posts, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) comment_count = models.Comment.objects.filter(active=True).count() context = { 'page_obj': page_obj, 'comment_count': comment_count, } # print(posts) return render(request, "post_list.html", context=context) And this too post_list.html <article class="col-12 col-md-6 tm-post"> <hr class="tm-hr-primary"> <a href="{{ post.get_absolute_url }}" class="effect-lily tm-post-link tm-pt-60"> <div class="tm-post-link-inner"> <img src="/{{ post.image }}/" alt="Image" class="img-fluid"> </div> <h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ post.title }}</h2> </a> <p class="tm-pt-30"> {{ post.body|slice:254 }} </p> <div class="d-flex justify-content-between tm-pt-45"> <span class="tm-color-primary">Travel . Events</span> <span class="tm-color-primary">{{ post.created_date.year }}/{{ post.created_date.month }}/{{ post.created_date.day … -
trying to post form data to django rest API by react using axios error buy saying The submitted data was not a file. Check the encodon
I am trying to send the form data( image) using react and Axios to rest API to Django data base I leading an error {photo: ["The submitted data was not a file. Check the encoding type on the form."]}photo ["The submitted data was not a file. Check the encoding type on the form."] "The submitted data was not a file. Check the encoding type on the form." import React, { useState } from "react"; import InputChar from "./SmallComponents/InputChar"; import InputNum from "./SmallComponents/InputNum"; import axios from "axios"; function CreateProduct() { const [productData, setProductData] = useState({ name: "", producttype: "", color: "", brand: "", desc: "", gender: "", offer: 0, price: 0, size: "", photo: "", }); function handleParentCharChange(featureName, featureValue) { setProductData((preProductData) => { return { ...preProductData, [featureName]: featureValue, }; }); console.log("------product data ----", featureName, featureValue); console.log("product data", productData); } function handleFormData(event) { setProductData((preProductData) => { return { ...preProductData, [event.target.name]: event.target.value, }; }); console.log("product data", productData); } function handleImageData(event) { const file = event.target.files[0]; // accessing file console.log("++++++++++image+++++++++++",file); setProductData((preProductData) => { return { ...preProductData, "photo" : file, } }) } function submitHandler(event) { event.preventDefault(); axios .post("http://127.0.0.1:8000/product/productcreate/", productData) .then((response) => { console.log("data is stored", response); }) .catch((error) => { console.log("data is not store", … -
IN ADMIN PANEL __str__ returned non-string (type NoneType)
im new to django tryna build up ecommerce project for education purposes. i got this error "str returned non-string (type NoneType)" from admin panel, when try view/change order or orderItem. I try to return str(self)I cant find error, pls guys help me fix it. I almost google all, but i dont understand how to can be type error if i return str(). Pls guys help my find they way to fix it from django.core.validators import RegexValidator from django.db import models from authentication.models import Customer from catalog.models import Product # Create your models here. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) date_order = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.transaction_id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total class … -
Render html form in django with forms.py
I have django web application with authentication system in it. I have user registration view, customer model and UserCreationForm in forms.py: class CustomerSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) # phone_number = forms.CharField(required=True) # location = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_customer = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') print(user.last_name) user.save() customer = Customer.objects.create(user=user) # customer.phone_number=self.cleaned_data.get('phone_number') # customer.location=self.cleaned_data.get('location') customer.save() return user My model looks like this: ... first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=20) location = models.CharField(max_length=20) I render form in my customer_register.html: ... <section> <div class="container"> <div class="row"> <div class="col-md-6 mx-auto"> <div class="card"> <div class="card-header text-black"> <h2>Register</h2> </div> <div class="card-body"> <form action="{% url 'customer_register' %}" method="POST" novalidate> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% for error in field.errors %} <span style="color:red">{{ error }}</span> {% endfor %} {% endfor %} </div> </form> </div> </div> </div> </div> </div> </div> </section> ... It doesn't look very pretty though. What I want to do is to replace my form in customer_register.html with new form in which I wouldn't use widget_tweaks but just html. -
Django media url from model
I'm working on a simple blog, I have this model for the blog post: class BlogPost(models.Model): title = models.CharField(max_length=150, unique=True) body = models.TextField() cover_image = models.ImageField(upload_to='blogposts/') created_on = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) category = models.ManyToManyField('PostCategory', related_name='posts') slug = models.SlugField(null=True, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("blog_detail", kwargs={"slug": self.slug}) In the settings file, I have the following configuration for static and media files: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I'm creating the blog models and views in a separate app I named "blog" I'm using a Django classed-based list view to display the posts on the page: class BlogListView(ListView): model = BlogPost template_name = "blog/blog_list.html" And I have the URL files working just fine: The problem is in displaying it in my template view, primarily for the post's cover image: {% for post in object_list %} <!-- Single Blog Item --> <div class="single-blog-item style-2 d-flex flex-wrap align-items-center mb-50"> <!-- Blog Thumbnail --> <div class="blog-thumbnail"> <a href="{{ post.get_absolute_url }}"> <img src="{{ post.cover_image }}" alt=""> </a> </div> <!-- Blog Content --> <div class="blog-content"> <a href="{{ post.get_absolute_url }}" class="post-title">{{ post.title }}</a> <p>We'll come back to this...</p> <div class="post-meta"> <a href="#"><i class="icon_clock_alt"></i> {{ post.created_on }}</a> … -
Django - One to One field bug not saving data without error
I am currently experiencing an issue with a one-to-one field in Django where the data was not stored after assigning value and save call is successful without any error. class Model1(models.Model): field1 = models.OneToOneField(Model1, on_delete=models.SET_NULL, null=True, blank=True, default=None) # Some other fields here def link_item(self, model2_id): field1 = Model2.objects.get(id=model2_id) self.field1 = field1 self.save() When I use the link_item of the model from the python shell it was updating the field but when it was used on the normal process the save call is successfully called but when I checked the value again in the shell it didn't update the field1. I have almost 10 million rows of data for Model1 and Model2, I'm not sure if it related to the issue but maybe it could help.