Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form save ForeignKey fields
So I have this ModelForm in my django project: class DateForm(ModelForm): image = forms.ImageField() class Meta: model = Date exclude = ('user',) the Photo model: class Date(models.Model): ... class Photo(models.Model): date = models.ForeignKey(Date, on_delete=models.CASCADE) image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/') the form: <p class="p-form">Title</p> {{ form.title }} <p class="p-form">Description</p> {{ form.description }} <p class="p-form">Place</p> {{ form.place }} <p class="p-form">Rating</p> {{ form.rating }} <p class="p-form">Photos</p> {{ form.image }} Whenever I try to save my form, its form_invalid method is being called and it doesn't save the form. What is the matter? How do I save extra field of ForeignKey model? How can I get that images sent via form? Thanks! -
how to call filter database with "Id " Django,
I want to make pay form, but I cannot show produk in orederitem, please helping me to show orderitem :v. I am really newbie in here . models.py class Order(models.Model): name = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) order_data = models.DateTimeField(auto_now_add=True) selesai = models.BooleanField(default=False, blank=True, null=True) status = models.BooleanField(default=False, blank=True, null=True) id_transaksi = models.CharField(max_length=200, null=True) bukti = models.ImageField(null=True, blank=True) ongkir = models.CharField(max_length=200, null=True) total = models.CharField(max_length=200, null=True) total_harga = models.CharField(max_length=200, null=True) pembayaran = models.CharField(max_length=200, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0) date_added = models.DateTimeField(auto_now_add=True) views.py def pembayaran(request): customer = request.user.profile ido = Order.objects.filter(id) orders = Order.objects.filter(name=customer, selesai=True) pengiriman = Pengiriman.objects.filter(name=customer) OrderItems = OrderItem.objects.filter(order=ido) print(OrderItems) context = {'orders': orders,'pengiriman' :pengiriman , 'OrderItems': OrderItems } return render(request, 'store/pembayaran.html', context) -
how to show 'staff' of certain 'shop' correctly?
as you can see on a picture i have Staff Worker named Max Barren but the thing is he is connected only to one of this shops. How do I write code properly so this staff worker will appear only under one of this shops? views.py def list_view(request): context = {} context['library_dataset'] = VideoLibrary.objects.all() context['staff_dataset'] = Staff.objects.all() return render(request, 'app/list_view.html', context) at views.py i get objects like adress and shop name from VideoLibrary model and staff_name and gender form Staff model to put it in list_view.html models.py class VideoLibrary(models.Model): shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') def __str__(self): return self.shop_name class Meta: verbose_name_plural = "Video Libraries" class Staff(models.Model): staff_name = models.CharField(max_length=264) living_adress = models.TextField(max_length=264) gender = models.CharField(max_length=264) age = models.IntegerField() staff_rating = models.IntegerField() shop_name = models.ForeignKey(VideoLibrary, on_delete=models.CASCADE) def __str__(self): return f'{self.staff_name}' class Meta: verbose_name_plural = "Staff" I suppose i got some troubles wtih my code at list_view.html but I don't know how to figure it out list_view.html <div class="main"> {% for data in library_dataset %} Shop name: <br /> <br /> {{ data.shop_name }} <br /> {{ data.adress }} <br /> <td><a href="{% url 'update_shop' data.id %}"> <button type="button">Edit Shop Details</button> </a></td> <br /> Staff that work in the shop: … -
How to refresh JWT TOKEN in django
I'm using jwt token authencation 1.11.0. But every 30 minutes token is expiring how to refresh the JWT token with version of 1.11.0 -
Problem django, accessing database, "django.db.utils.OperationalError: (1043, 'Bad handshake')"
I want to deploy a Django app on a virtual machine hosted on a cluster. For this app i need access to a MySQL database that is also hosted on the cluster. When I launch $ mysql -h 1XX.1XX.1.1XX -u test -p test on the virtual machine, i can access the database. But when i run the django server, i've got an error : django.db.utils.OperationalError: (1043, 'Bad handshake') It is the same error as when the versions of MySQL between the cluster and the VM are different but I installed the same. Thank you for help. -
Google Cloud SECRET_KEY
I'm following the Google Cloud Documentation Running Django on the App Engine standard environment. I reach the part where I'm suppose to create a SECRET_KEY on my .env file and I occured on a error when i'm executing the last line. The error Actually I'm using Windows 11 and Windows PowerShell (i know that lc_all=c is used on Unix & Linux but i don't know what can i use on windows). -
objects.get(id = id) only works randomly
I think somewhat related: link. I create a model entry: def bulk_asset_update(stores, links, img): def do_update(id): task = ThreadTask.objects.get(pk = id) ## <--- DOES NOT EXIST SOMETIMES ... task.is_done = True task.timestamp_end = timezone.now() task.save() task = ThreadTask() task.name = "update" task.save() t = threading.Thread(target = do_update, args = [task.id]) t.setDaemon(True) t.start() return {"id": task.id} Sometimes (every 5th time or so) the ThreadTask.get(pk = id) line fails - so I suspect it might not be written to the database yet maybe? I tried replacing the lines: task = ThreadTask() task.name = "bulk asset update" task.save() with: task = ThreadTask.objects.create(name = "update") which seams to work better. But can I make sure that the task object is really saved first before code execution continues? -
How i can integrate scrapy in django and get spider results in django views?
i want to use scrapy spiders in django views, crawl that spider within django view and store scraped data in python list or dictionary. Is there any easy way to do this? -
DJANGO Supplement to the data list via an intermediate table
I have an intermediate models connection Simplified: Person table: first_name last_name Company table: company_name CompanyEnrollment table: FK Person FK Company I want to create the following array: datas = Person.objects.All(...{All elements of Person supplemented with Company_name}...) There is a case where a person does not have a company_name association Is it possible to solve this with a query? -
create a persistant instance of aiohttp.ClientSession in Django app
I'm trying to create an instance of aiohttp.ClientSession() in a django app. I want to create the object via the ready() hook in apps.py and then access the instance from views.py. From views.py I'm using the my_app_config.my_object to pull back the instance, but I'm seeing weird behaviour. For example 'Timeout context manager should be used in side a task'. Is anyone able to provide a clear example of how I might go about creating an instance of aiohttp.ClientSession() which I can pull into views.py (or indeed any other class in the app) for reuse. -
How to use return two time in a function in Django using async?
I have a model called response. If the user is selected for a duration the response is turning to the default value after that duration time. But I need to return the value until the duration time is over. I think I need to use the async function. I looked at the SO. but couldn't find any solutioın. models.py class Response(models.Model): def_res = models.CharField() expected_res = models.CharField() current_res = models.CharField() is_duration= models.BooleanField(default=False) duration = models.PositiveIntegerField() views.py def manage_response(request): if request.method == "POST": a = Response.objects.filter(id=request.POST.get('resp_id')) a.current_res = a.expected_res a.save() if not a.is_duration == True: return JsonResponse(a.current_res) else: return JsonResponse(a.expected_res ) #after return won't work in sync time.sleep(a.duration) a.current_res = a.def_res return JsonResponse(a.current_res) -
How to update models with proxy tabular inline?
I have the following code. I used a proxy model because I needed to register the same model in admin. I get the message: 'Please correct the error below.' with no error field, and I get no exception. I can't trackdown the error since there is no error in the log file. I can save new info if the table is clear, but I get that error when I try to update info. I think it's trying to overwrite the parent model, Laptop. class Laptop(models.Model): _id = models.ObjectIdField() Type = models.CharField(max_length=30, unique=True) def __str__(self): return self.Name def save_model(self, request, *args, **kwargs): try: return super(Laptop, self).save_model(request, *args, **kwargs) except Exception as e: self.message_user(request, e, messages.ERROR) class LaptopProxy(Laptop): class Meta: verbose_name = 'Info' proxy = True def save_model(self, request, *args, **kwargs): try: return super(LaptopProxy, self).save_model(request, *args, **kwargs) except Exception as e: self.message_user(request, e, messages.ERROR) class InfoForm(InternalModelAdminMixin, admin.TabularInline): model = Info extra = 30 def is_valid(self): log.debug(force_text(self.errors)) return super(InfoForm, self).is_valid() class InfoAdmin(InternalModelAdminMixin, admin.ModelAdmin): inlines = [InfoForm] admin.site.register(Laptop, LaptopAdmin) admin.site.register(LaptopProxy, InfoAdmin) -
Django - Save override to update fields issue
Having trouble with figuring out a way to update fields of a table through the save method override and have the updated value factor in values from previous saved objects that share the same primary key. Let me explain: I have two tables, table A and table B. Table A has a field that is the foreign key PK of table B. Multiple objects in table A share the same foreign key from Table B. Here are some JSON bodies to represent each table. Table A [ { "pk": 1 "count(fk)": "Cat counter", "name" "Jerry" }, { "pk": 2 "count(fk)": "Cat counter", "name" "Max" }, { ... } ] [ Table B { "pk": "Cat counter" "count": 0 }, { "pk": "Dog counter" "Count": 0 } ] Let's say we POST all the values that represent Table A in one POST request. At the same time, I want table B to be updated with the count of cats or dogs through a save method override of Table A. Right now I am doing it this way in Table A's model which does update the count field as I wanted to, but it doesn't seem to remember previous iterations, even though … -
How to upload a database tables into File Filed of django directly
I have tables name TBL_Result_1 ,TBL_Result_2 etc in postgresql database. I have created a File filed in django model to upload a file from backend. I want these tables to upload directly in django created File filed option in csv format. How it can be implemented -
How to call celery task in view depends of body in request
I have four celery tasks and need to call specific task depends of what provided in the body in request. For example I provide in Postman {'1'}, then need to call task_one(). If I provide {'2'}, then call task_two(). This logic need to be done in a view or in a serializer? -
Django+Vue:static file not found
When I use Django+Vue to build a web appliction, It occoured that the staic files always not found though I had placed all the files correctly. the logs from server like this: WARNING Not Found: /static/js/app.4c2224dc.js WARNING Not Found: /static/css/app.a5d43e07.css WARNING Not Found: /static/css/chunk-vendors.2ccfa1b8.css WARNING Not Found: /static/js/chunk-vendors.c2488b8d.js WARNING "GET /static/js/app.4c2224dc.js HTTP/1.1" 404 179 WARNING "GET /static/css/app.a5d43e07.css HTTP/1.1" 404 179 WARNING "GET /static/css/chunk-vendors.2ccfa1b8.css HTTP/1.1" 404 179 WARNING "GET /static/js/chunk-vendors.c2488b8d.js HTTP/1.1" 404 179 WARNING Not Found: /login WARNING "GET /login HTTP/1.1" 404 179 WARNING Not Found: //performanceProject WARNING "GET //performanceProject HTTP/1.1" 404 179 WARNING Not Found: /performanceProject WARNING "GET /performanceProject HTTP/1.1" 404 179 -
What is the way for me to get rid of Reverse Accessor error in Django (fields.E304)
I am trying to create these models : class User(models.Model): name = models.CharField(max_length=USERNAME_LEN) class Room(models.Model): host = models.ForeignKey(User, on_delete=models.CASCADE) users = models.ManyToManyField(User) In my mind, I want something in the lines of : One User can access to multiple Rooms One User can host mutliple Rooms One Room can have mutliple Users One Room have one host that is an User However, trying to migrate those, I get an error and as I am not an expert on SQL relations nor in Django, I'd like to know what is the best way for me to make this. Thanks -
How to load saved data with json.dumps method in django
[models.py] class History(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True) study = models.ForeignKey(Study, on_delete=models.SET_NULL, blank=True) summary = models.TextField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) [views.py] def add_history(request): history = History(user=request.user, study=new_study, summary=json.dumps({ 'field_summary': field_summary, 'file_summary': file_summary })) history.save() def chart(request): histories = History.objects.filter(summary__icontains='teacher', create_date__gte='2022-01-01', create_date__lte='2022-04-10')\ .annotate(teacher=json.loads('summary')['field_summary']['teacher'])\ .values('study_name', 'teacher', 'create_date') return render(request, 'chart.html', {'histories': histories}) [chart.html] {% for h in histories %} {{ h.study_name }},{{ h.teacher }}, {{ h.create_date }} {% endfor %} An error is: JSONDecodeError at /chart/ Expecting value: line 1 column 1 (char 0). I want to extract only the teacher value in the summary field. However, an error occurs in the annotate part. -
Django allauth redirects me to signup when trying to login with google?
Using Django allauth I am trying to implement social login for the user. But when I tried to log in using google, the application redirects me to the signup page. Menu: Sign In Sign Up Sign Up You are about to use your Google account to log in to **Domain_Name**. As a final step, please complete the following form: E-mail: Username: Sign Up » -
use django admins icons for my own fields
What is the best way to use the standard django icons from the admin menu in custom fields for the admin? I know they are stored in projectname-static/admin/img/icon-alert.svg etc ... but is there something like from django.templatetags.static import static where I can access them? I know they are implemented in the admin using css: ul.messagelist li.warning { background: var(--message-warning-bg) url(../img/icon-alert.svg) 40px 14px no-repeat; background-size: 14px auto; } I imagine something like: class CustomFieldAdmin(admin.ModelAdmin): fields = ["custom",] def custom(self, obj): return format_html(f"""<img src="{icon}">obj.text""") -
Can't able to Save base64 string in the same image field by overriding the save method using django
models.py class Organisation(models.Model): """ Organisation model """ org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) org_logo_b64 = models.BinaryField(null=True, blank=True) def save(self, *args, **kwargs): if self.org_logo: logo = self.org_logo.open() self.org_logo_b64 = base64.b64encode(logo.read()) super(Organisation, self).save(*args, **kwargs) else: super(Organisation, self).save(*args, **kwargs) I need to override the save method to save the base64 data in the image field. But the org_logo should be an image field as I need to receive as file object while POST and save it as base64 in the same org_logo field and in database. Is that possible? or it that possible to change the field name of org_logo_b64 to org_logo while performing GET operation? -
How to return Django Nested Json?
I am a beginner at Django. I want to create an API JSON Response in below format, like Every Faculty have some Department and Every Department have some Teacher Information. Please help me to create this kind of complex JSON format faculty Department Teacher I have a Teacher model class Teacher(models.Model): name = models.CharField(max_length=200, blank=False, null=False) phone_number = models.CharField(max_length=11,blank=False,null=False) email = models.EmailField(max_length=150,blank=False,null=False) designation = models.CharField(max_length=200,blank=False,null=False) faculty = models.CharField(max_length=200,blank=False,null=False) department = models.CharField(max_length=200,blank=False,null=False) priority = models.IntegerField(blank=False,null=False) serializer.py class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = '__all__' -
Using Django crispy forms' Layout class with relationship fields
I have a model with lots of related fields (ForeignKey, OneToOneField, ManyToManyField). I want to render it with django crispy forms' FormHelper and Layout classes in forms.py. But I don't know syntax to get related fields. I've tried like query syntax wit double underscore, but it didn't get populated by instance data: class Model_A_Form(forms.ModelForm): initial_info = forms.CharField(label="Initial info") field_1__relfield1 = forms.CharField(label='Field 1.1') field_1__relfield2 = forms.CharField(label='Field 1.2') field_2__relfield1 = forms.CharField(label='Field 2.1') field_2__relfield2 = forms.CharField(label='Field 2.2') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) tab_1 = TabHolder( Tab('Tab 1.1', 'field_1__name' ), Tab('Tab 1.2', 'field_2__name' ), ) tab_2 = TabHolder( Tab('Tab 2.1', 'field_1__name' ), Tab('Second Tab', 'field_2__name' ), ) layout = Layout( Tab('Tab 1', tab_1 ), Tab('Tab 2', tab_2, ) ) self.helper = FormHelper() self.helper.layout = layout class Meta: model = Nizam_Manzum fields = ( 'initial_info', 'field_1__relfield1', 'field_1__relfield2', 'field_2__relfield1', 'field_2__relfield2', ) And I've tried using other forms directly but I got an error about passing Forms as argument to Layout object is can't be done: tab_2 = Tab_2_Form(instance=tab_2_id) layout = Layout( Tab('Tab 2', tab_2 ), So is there anyway to get related fields with FormHelper and Layout classes of crispy forms? -
Multiple image upload using django restframework and postman
Models.py class Image(SafeDeleteModel): image = models.ImageField(upload_to='image/') class Meta: db_table = TABLE_PREFIX + "image" serializers.py class MultiImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' views.py class MultiImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = MultiImageSerializer # parser_classes = (MultiPartParser, FormParser) # permission_classes = (IsAuthenticated,) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) if serializer.is_valid(): print(serializer.validated_data) serializer.save() custom_data = { "data": serializer.data } return Response(custom_data, status=status.HTTP_201_CREATED) else: custom_data = { "data": serializer.errors } return Response(custom_data, status=status.HTTP_400_BAD_REQUEST) I'm getting an empty list when i print 'serializer.validated_data' inside view. I use postman to invoke the api. It returns a null value, and i'm not sure if its the right way to do it. I removed 'many=True' from views and tries single image upload with the api, it works fine. Someone please suggest me the simplest way to upload multiple images with the api. Thank you for the time you spend on my problem. -
ValueError at /issue/1/comment Cannot assign "<SimpleLazyObject: <User: miko>>"
So I'm trying to create a simple Comment feature for a blog app. In the Class-based views, if you are using a Foreign Key in your model, I know that you have to override the def form_valid: in order for the Comment to be posted by the current logged-in User. I did this for the Blog model in my app, and it works just as intended, however, when I try to do the same with the CommentCreateView, I get the error. Here's my code so far views.py class IssueCreateView(LoginRequiredMixin, CreateView): model = Issue fields = ['title', 'content', 'mark_as', 'assignee', 'priority', 'label'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['title', 'content'] template_name = 'issues/add_comment.html' def form_valid(self, form): form.instance.issue = self.request.user return super().form_valid(form) models.py class Comment(models.Model): issue = models.ForeignKey(Issue, on_delete=models.CASCADE, related_name='comments') name = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, null=True) content = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) class Issue(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) What did I do wrong? Traceback (most recent call last): File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line …