Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM how to use case when and use other objects value with filter?
so i have 2 models: label, label models is used to define what is the label of a "type" code example coupon type code 2, has label expired. class Labels(models.Model): label_id= models.AutoField(primary_key=True) label_type = models.CharField(null=False, max_length=50) label_code= models.IntegerField() label_name = models.CharField(max_length=50) coupon model used for coupon data class Coupons(models.Model): coupon_id = models.AutoField(primary_key=True, null=False, unique=True) coupon_name = models.CharField(max_length=200, null=False) coupon_desc= models.CharField(max_length=200, null=False) valid_date = models.DateField(null=False) status = models.IntegerField(null=False) so i want to use case when to filter the data and get status name example if the coupon date is more than today then it's expired else it's activate and i want to get the value of the status name from another model called label model, here is my current attempt label_status = Labels.objects.filter(label_type='coupon_status').all() data = Coupons.objects. annotate( coupon_status_name=Case( When(status=0, valid_date__lte=date.today(), then=Value(system_used.filter(label_code="2").first().label_name)), default=Value(label_status.filter(label_code=status).first().label_name), output_field=CharField() ) ).all() i am able to filter the first line on the When() function but i am not able to filter the label objects in the default parameter of case function that reference the coupon dynamically, so how can i do this ? i tried using OuterRef() like default=Value(label_status.filter(label_code=OuterRef(status)).first().label_name) but it gives me this error: This queryset contains a reference to an outer query and may only be … -
Django annotate count of subquery items - ValueError: This queryset contains a reference to an outer query and may only be used in a subquery
I have an Agent, Client and Car models. In Client model: agent = ForeignKey('Agent'...) In Car model: client = ForeignKey('Client'...) I want to annotate (on an Agent QuerySet) a total number of active cars of all clients of an agent. So if the agent Bob has clients Alice and Peter, Alice has 3 active cars and Peter has 2 active cars, the active_cars variable will be 5. I tried: Agent.objects.annotate( active_cars=Subquery( Car.objects.all().active().filter( client__agent=OuterRef('pk') ).count() ) ) which raises: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Do you know how to do that? -
Django automatically add number in table
I would like when I add a file in the table it automatically adds a number from 1. I cannot use the primary key in the model because I already use it. anyone have a solution. thank you. ====Page.html==== <h5>Documents</h5> </div> <div class="row"> <div class="col-md"> <div class="card card-body"> <table class="table table-sm"> <tr> <th>#</th> <th>Nom du fichier</th> <th>Fichier</th> <th></th> </tr> {% for d in document %} <tr> <td>{{d.Number}}</td> <td>{{d.Description}}</td> <td><a download href="{{d.Fichier.url}}">{{d.Fichier}}</a></td> <td><a class="btn btn-outline-danger" href="{% url 'supprimerdocument' d.id %}">Supprimer</a> </tr> {% endfor %} </table> </div> </div> </div> ====view.py==== # Button to add docs @login_required(login_url='loginpage') @allowed_users(allowed_roles=['admin', 'livraison']) def createDocument(request): forms = documentForm() if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/employe') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) ====Models.py==== class Document(models.Model): employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL) Number = models.IntegerField(default=1) Description = models.CharField(max_length=100, null=True) Fichier = models.FileField(upload_to='documents/') data_created = models.DateTimeField(auto_now_add=True, null=True) ====Form.py==== class documentForm(ModelForm): class Meta: model = Document fields = '__all__' exclude = ['Number'] -
How do I display a picture in Django's DetailView based on a foreign key relationship?
I am currently building a website with Django that will host music and album/song details. My models are set up so that each song has a foreign key to it's associated album, or to a database object titled "Singles" if they are not part of an album. This relationship between song and album has worked great while building the site, until I got to the 'Play Song' page I am currently working on. Each Single has an associated artwork in the 'Song' model, while each song in an album has no 'picture' in the database, as the 'picture' is a part of the Album model and not the Song model in these instances. I am attempting to pass data from both the Song model and the Album model into my DetailView so that if the song being played is from an album rather than a single, it takes the 'picture' from the Album model it has a foreign key to rather than from it's own internal 'picture' object. My code is below, it renders the 'picture' for Singles perfectly, but cannot render the 'picture' object from the album and instead shows my {% else %} condition of a object not … -
Migrations applied in site-packages.django.contrib.sites instead of local app after extending Site object with OneToOne field
I borrowed ideas from this answer to extend the default Site object created during the initial migration with Django sites framework. The new model, SiteSettings, establishes a OneToOne relationship with the Site model to add additional fields. I then use signals to create the SiteSettings object. When I made the first migration for the SiteSettings model everything appeared to work fine. A SiteSettings object was created that had a OneToOne relationship with the default Site object. However, what I didn't notice is that a migration file wasn't created under my local app for this. I was able to makemigrations and migrate just fine, so I'm not sure where that migration went. It's not listed in my migrations table. Anyway, since it worked I didn't notice. I then proceeded to add additional fields to SiteSettings a day or two later, and noticed when I made those migrations, they were for creating a SiteSettings model, not updating its fields. That's when I noticed that the first migration wasn't created in the right spot. The second migration was created, however it was created in site-packages/django/contrib/sites/migrations/. It looks like this: class Migration(migrations.Migration): dependencies = [ ("sites", "0002_alter_domain_unique"), # the initial auto migration ] operations … -
How do I typehint things that are linked to the User in Django?
I've got typehints working for most things, but running into issues with django.contrib.auth.models.User. Pylance isn't picking up on things like Profile and several other models which have a ForeignKey to User. Is there a simple way to add these typehints without having to spec out the whole User Model that is already working (with these few exceptions) -
read a CSV file from post request
i am trying to get read some data from a CSV file but when I try read the file with the folwing method I get the error ValueError: I/O operation on closed file. def post(self, request): serializer = MosqueFileSerializer(data=request.data) if serializer.is_valid(): serializer.save() file =pd.read_csv(request.FILES['file']) return Response(status=status.HTTP_200_OK) and when i try to open the file i get another error TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile def post(self, request): serializer = MosqueFileSerializer(data=request.data) if serializer.is_valid(): serializer.save() file =pd.read_csv(open(request.FILES['file'])) return Response(status=status.HTTP_200_OK) so can someone help me to find a solution? -
Heroku Postgres Database to ElephantSQL
I have a Postgres database on Heroku and I want to have that database hosted on ElephantSQL, but I cannot for the life of me find how to do it. I have a DUMP file downloaded from the Heroku Postgres database, but I cannot find how I put the data into ElephantSQL. My database was linked to a Django app and I already have my instance on ElephantSQL linked to the a copy of the same Django app, but hosted on Render. I can see on ElephantSQL that the instance has all the tables, so I just need to put the data in there somehow. Any tips or hints are welcome! -
Set django.setup() on another container in docker-compose. Websockets server + django app
I am building app in docker that contains two services, one is django app and second is websockets server for playing chess which contains client.py server.py chess.py. Whole game is conducted by terminals, while server is running both players can play by run client.py in their terminals. Now, I want to integrate websockets server with django and force players to auth by providing a token generated in django-sesame like in this docs, but I receive error on line contains django.setup(): django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I assume that I need point to django settings, but I don't have access due to it is place in another containers. How can I do that? Code from mentioned docs: import asyncio import django import websockets django.setup() from sesame.utils import get_user async def handler(websocket): sesame = await websocket.recv() user = await asyncio.to_thread(get_user, sesame) if user is None: await websocket.close(1011, "authentication failed") return await websocket.send(f"Hello {user}!") async def main(): async with websockets.serve(handler, "localhost", 8888): await asyncio.Future() # run forever if __name__ == "__main__": asyncio.run(main()) I tried to point to settings by os.environ.setdefault("DJANGO_SETTINGS_MODULE", "code.app.app.settings") django.setup() But I got … -
Filter between 2 dates using a date from another transction
I have a custom record that has 3 fields: Sequence Number Start Date End Date What I am trying to do is create a search via suitescript that takes a date from an invoice (the date is in a custom field) and find the sequence number that falls within the start date and end date. I tried using the below filters (myDate = the date from the invoice field which in my example is 9/26/2022) but this did not turn up any results even though there is a custom record with a start date of 9/25/2022 and an end date of 10/1/2022: filters: [ ["custrecord_startDate","onorafter",myDate], "AND", ["custrecord_endDate","onorbefore",myDate] ] What would be the best way to filter my results to get the correct value? -
save() prohibited to prevent data loss due to unsaved related object 'student'
I am a recreating a Django project. I am trying create post_save signal that will create student marks when a student is created. I am getting the error message: save() prohibited to prevent data loss due to unsaved related object 'student'. Here is my student model: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) class_id=models.ForeignKey(Class, on_delete=models.CASCADE, null=True, blank=True, default=1) col = models.CharField(max_length=50, null=True, blank=True, default=science_college) name = models.CharField(max_length=100, null=True, blank=True) sex= models.CharField(max_length=50, choices=SEX_TYPE, null=True, blank=True) DOB=models.DateField(default="1998-01-01", null=True, blank=True) created = models.DateTimeField(auto_now_add=True) SID=models.CharField(('STUDENT_ID'), max_length=30, default=student_ids, unique=True, editable=False) id = models.IntegerField(primary_key=True, editable=False) def __str__(self): return self.name And here is the signal code def create_marks(sender, instance, created, **kwargs): if created: if hasattr(instance, 'name'): ass_list = instance.class_id.assign_set.all() for ass in ass_list: try: StudentCourse.objects.get(student=instance, course=ass.course) except StudentCourse.DoesNotExist: sc=StudentCourse(student=instance, course=ass.course) sc.save() sc.marks_set.create(name='CAT 1') sc.marks_set.create(name='CAT 2') sc.marks_set.create(name='CAT 3') sc.marks_set.create(name='SEMESTER EXAM') elif hasattr(instance, 'course'): student_list = instance.class_id.student_set.all() cr = instance.course for s in student_list: try: StudentCourse.objects.get(student=s, course=cr) except StudentCourse.DoesNotExist: sc = StudentCourse(student=s, course=cr) sc.save() sc.marks_set.create(name='CAT 1') sc.marks_set.create(name='CAT 2') sc.marks_set.create(name='CAT 3') sc.marks_set.create('SEMESTER EXAM') post_save.connect(create_marks, sender=Student) -
How to get field from different model to filter in filter.py?
is there some way how get field from different model to my filter which is used in my template? I am trying to filter by category_name from Category model in Warehouse model which is connected with Category Model by Product model. When I try in shell, relation is working: Warehouse.objects.filter(product__category__category_name__icontains="shoes") But when I use similar code in filter.py, I get blank field instead of field for category (other fields from filter are working, so filter is OK): class WarehouseDataFilter(django_filters.FilterSet): product = django_filters.CharFilter(label="Product", field_name="product__name", lookup_expr='icontains') category = django_filters.CharFilter(label="Kategorie", field_name="product__category__category_name", lookup_expr="icontains" ), pyear = django_filters.NumberFilter(label="Rok výroby", field_name="product__pyear") class Meta: model = Warehouse fields = ("product", "pieces") attrs={"a": {"class": "orange"}, "thead": {"class": "orange"}} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form.helper = WarehouseDataFilterFormHelper() models.py class Warehouse(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) pieces = models.IntegerField("Quantity", null=True, blank=True) updated_on = models.DateTimeField(auto_now=True, null=True) class Product(models.Model): name = models.CharField("Product", max_length=150) pyear = models.IntegerField("Rok Výroby", null=True, blank=True) drop = models.IntegerField("Drop", null=True, blank=True) productgroup = models.ForeignKey(ProductGroup, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) class Category(models.Model): category_name = models.CharField("Category", max_length=100, blank=True, null=True) -
Using NuxtJS (or VueJS) to handle dynamic Django forms?
I have a Django site with Bootstrap styling the front-end. The primary function of the site is to show a form, send the form submission to the Django View, and have the view render back a output page based on the information in the form. The form is pretty dynamic, using jQuery. When one particular dropdown is selected, another field might be disabled. When another dropdown value is selected, it might unhide a with extra form fields (conversely, it can re-hide the div if another dropdown value is selected) One of the main features that I've done is to save all of the form field values into the DB, so that we can use a specific URL to retrieve that exact input/output. When the inputs are loaded from the database, all of that same jQuery is being run to disable, hide, show different parts of the form. And it all seems kind of brittle or prone to errors. All of that run-up for the actual question: I am learning about NuxtJS. Is there a specific feature of NuxtJS or development pattern that is going to help me with this dynamic loading of a conditional Django form? Are there specific things … -
Trim a dajango model attributes
I have a project in django, witch uses database first. The problem is the data format, because they have a lot of blank space. As I am using rest_framework, I would like to trim the objects before pass it to the serializer, because if I try to do something like nombre = serializers.CharField(source='nombre.strip') it says that I cannot use build-in functions. So, if anyone can help me I it would be great. -
Could not connect to wss
I want to add websockets chat to my Django (DRF) application. I am following this tutorial https://dev.to/earthcomfy/django-channels-a-simple-chat-app-part-3-a3b My versions django-rest-passwordreset==1.2.1 channels==3.0.5 channels-redis==3.4.1 Nginx configuration What should I add for websockets? upstream app { server django:8800; } server { listen 80; server_name 127.0.0.1; client_max_body_size 100M; location / { proxy_pass http://django:8800; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_read_timeout 300s; proxy_connect_timeout 75s; } ... Routing websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] I have a standard consumer: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) I am sending request wss://localhost:6060/ws/chat/r1 On the server side I see logs: nginx_1 | 172.18.0.1 - - [28/Sep/2022:19:55:22 +0000] "\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03<\xA1\xCE\xACW\x06T\x84\x1F\xE3\x13\xD8F\x00\x03\x11\xC3><4k~_\x14\x83j=\xD1}u^R '\xCE\xF3\xB2\x142\x84+J~\xEC\xDAG?c\xD0)q\xBDZ\xD9\x95_\x1C\xED\x83L,\x1C" 400 157 "-" "-" "-" But have the following error. How to fix it? -
Django: how to pass data from view to forms to validate it
In my form class I have a contact field in string to save several contacts separated by semicolons. In the request, contacts is an array so I do a ";".join(contacts) to get one contact field for my class form. I would like to pass this ";"join(contacts) contact from my view to the form class to validate it. -
How to add decorator to class based view in django
I have signup class based view in my django authentication application. I created a new file: decorators.py from django.shortcuts import redirect def authenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if not request.user.is_authenticated: return view_func(request, *args, **kwargs) else: return redirect('/') return wrapper_func and in my view I have: from .decorators import authenticated_user class Signup(View): @authenticated_user def get(request): ... And it results in an error: AttributeError at /accounts/signup-professor/ 'ProfessorRegister' object has no attribute 'user' But if I add same decorator to function based view it works. Why is this happening and how to fix it? -
How to send kwargs arguments via .save() method to a post_save signal?
I have two models, Process and Notification and I need to create a notification when a process is saved so Im using a post_save signal for this: def create_notification(sender, instance, *args, **kwargs): if instance.status in ["ERR", "FIN"] or instance.percent == 100: type = kwargs["type"] notification = Notification() notification.account = instance.owner notification.process = instance notification.status = "UNREAD" notification.content = instance.description notification.notification_type = type if instance.sub_processes.exists(): for sub_process in instance.sub_processes.all(): if sub_process.model_id != "": notification.model_id = sub_process.model_id if sub_process.model_name != "": notification.model_name = sub_process.model_name notification.save() this is working fine but my problem is that I need to pass an extra argument when I save a process, this argument is for the Notification Object that Im creating, which is type so every time im saving a Process object (in a view for example) im trying to do something like this process.save(type="EMM") but its not working, the line type = kwargs["type"] in create_notification signal isn't doing anything, so how can I send extra arguments to save method ? -
how do I display the tags used more than once only one time?
The same tags are being repeated and displayed in the dropdown list. It is looping over the tags used in each post but it is not checking if the tags are repated or not. So is there any way that I can avoid this repetition? my dropdown list is as below: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for post in posts %} {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}"> {{ tag.name }} </a> {% endfor %} {% endfor %} </div> </div> views.py def home(request, tag_slug=None): posts = Post.objects.all() #tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) return render(request, 'blog/home.html', {'posts':posts}) models has title = models.CharField(max_length=100) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default= 'blog_default.jpg', upload_to='blog-pics') tags = TaggableManager() I need to solve this issue. I want to use the same tags in different posts but I want to display the tags just once in the dropdown list. -
How to design a model for a Django TaskManager App?
I need a small task manager app that performs certain tasks, e.g. copy file, send email, create pdf and so on. The tasks must also run in an order/priority, e.g. first: create pdf, second: send mail. I'm currently wondering what a good model would be for this. Somewhere I don't quite like the ideas I have. Among other things, I have questions like: How could the model look like? Should i use an abstract class? What about inheritance? Should i use NULL values here and better use a large table instead of dividing it into individual tables? Example for "models.py": class Channel(models.Model): name = models.CharField(max_length=50, unique=True, null=False) active = models.BooleanField(default=False) @admin.display(boolean=True) def is_active(self): return self.active def __str__(self): return self.name class Meta: db_table = 'channel' verbose_name = 'Channel' verbose_name_plural = 'Channel' class Task(models.Model): name = models.CharField(max_length=50, unique=True, null=False) active = models.BooleanField(default=False) priority = models.IntegerField(null=False) channel = models.ForeignKey(Channel, on_delete=models.CASCADE, related_name='%(class)s_channel') @admin.display(boolean=True) def is_active(self): return self.active class Meta: abstract = True class CopyFile(Task): path_src = models.CharField(max_length=200, null=False) path_dest = models.CharField(max_length=200, null=False) pattern = models.CharField(max_length=200, null=False) def __str__(self): return self.name class Meta: db_table = 'task_copy_file' verbose_name = 'Task (CopyFile)' verbose_name_plural = 'Task (CopyFile)' class SendMail(Task): recipient = models.CharField(max_length=200, null=False) sender = models.CharField(max_length=200, null=False) content … -
I am getting this error: AttributeError at /home/ 'list' object has no attribute 'values'
models.py from django.db import models class Student(models.Model): Student_Name = models.CharField(max_length=40) Father_Name = models.CharField(max_length=40) Contact = models.CharField(max_length=10) Address = models.CharField(max_length=120) def __str__(self): return self.Student_Name serializers.py from rest_framework import serializers from .models import Student class StudentForm(serializers.ModelSerializer): model = Student fields = ['Student_Name','Father_Name','Contact','Address'] app urls.py from django.urls import path from restapiapp import views urlpatterns = [ path('home/', views.HomeView, name='home'), ] admin.py from django.contrib import admin from .models import Student admin.site.register(Student) views.py from django.http import HttpResponse,JsonResponse from rest_framework.decorators import api_view from .models import Student from .serializers import StudentForm @api_view(['GET']) def HomeView(request): serializer_obj = Student.objects.all() serializer1 = StudentForm(serializer_obj,many=True) return JsonResponse(serializer1.data, safe=False) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'restapiapp', ] urls.py from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('restapiapp.urls')), ] Error: Internal Server Error: /home/ Traceback (most recent call last): File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Omkar\django_projects\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc … -
django-allauth Azure Ad Configurations
I'm tyring to setup django azure ad authentication using django-allauth but currently the documentations is not having proper documentation for setting up Azure ad. I have client_id, secret and tenant_id with me. I have tried few configurations but it seems to be not working. Config 1: SOCIALACCOUNT_PROVIDERS = { 'azure': { 'APP': { 'client_id': 'client_id', 'secret': 'secret', 'key': '' } } } Config 2: SOCIALACCOUNT_PROVIDERS = { 'azure': { 'APP': { 'client_id': 'client_id', 'secret': 'secret', 'key': '', 'tenant_id': '', } } } I have experimented few more configuration but its seems to be not working https://django-allauth.readthedocs.io/en/latest/providers.html -
Django Picture showing as broken when referenced in template
I am trying to create a settings page for user profiles and I have hit a roadblock. I included a profile image inside of my User model and when trying to reference said ImageField in my profile template the image shows up as broken. Firstly, everything else related to the storing of a profile image works. When an account is created, the default image saves and same with using the upload picture form. The issue comes when trying to display the current profile picture through the model's url and the image shows up as broken. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(max_length=300, blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile.jpg') verified = models.BooleanField(default=False) def __str__(self): return self.user.username views.py def settings(request): user_profile = Profile.objects.get(user=request.user) if request.method == "POST": if request.FILES.get('image') == None: image = user_profile.profileimg bio = request.POST['bio'] user_profile.profileimg = image user_profile.bio = bio user_profile.save() if request.FILES.get('image') != None: image = request.FILES.get('image') bio = request.POST['bio'] user_profile.profileimg = image user_profile.bio = bio user_profile.save() return redirect('settings') return render(request, 'settings.html', {'user_profile': user_profile}) Section of html file that tries to show image <img width="100" heigh="100" src="{{ user_profile.Profileimg.url }}" /> I have also added all of the necessary MEDIA_URL/root settings and have tried … -
Django form not showing errors but redisplays new form
I have a Insert view which displays model data from one primary and one related model. Once finished displaying the data a form is appended to the table to add a new related item. This works fine - however if I enter invalid data (like a invalid time to be exact), and hit one of the submit buttons, it simply refreshes the page with a blank entry form for the related data again. It doesn't display the data I entered, and it doesn't display an error message even though the form includes the error fields. I have tried adding form_invalid to my CBV and calling the form but I can see that it just calls the InserView again with no context (which basically does the get_context_data call again and give me a new blank form). How do I get it to put up the form with my data from before and the errors as well. See code below: views.py class SegmentAddView(LoginRequiredMixin,CreateView): login_url = reverse_lazy('login') model = Segment template_name = 'segment_add_view.html' form_class = SegmentForm def get_context_data(self, **kwargs): context = super(SegmentAddView,self).get_context_data(**kwargs) program_info = get_object_or_404(Program, pk=self.kwargs['pk']) context['program_info'] = program_info last_segment = program_info.segments.last() if last_segment: add_sequence_num = last_segment.sequence_number + Decimal(1.00) else: add_sequence_num = Decimal(1.00) … -
Django: Display data from other table
I'm having a hard time displaying some datas from two or three tables. So this is my code for showing all the data only from Device table. def device(request): if request.method == 'GET': queryset = Device.objects.all() if queryset: data = {"queryset": queryset} return render(request, 'device/device.html', data) else: return render(request, 'device/device.html') And I want to add some data from other table, how do I insert it here?