Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Ignore Special characters in queryset filters: Django
I have a model Emp which has a field name. I want to filter on that field by ignoring the special characters. For eg: value of name for an instance is "test_name". And if I pass testname, it should give me the result. result = Emp.objects.filter(name="testname") Is there any lookup to get this result? -
Using docker registry to share my multi-image containerized app: Encountering Problems connecting multiple image repos
My local docker container app is made up of 4 images, React, Django, nginx, postgres. It runs perfectly locally, (although of course I need to manually go to 127.1.1.0 on my local computer to view the app) I want other people to be able to view this app as well, if they have docker installed on their local computer, and so, using the steps in the docker documentation, I pushed all four images to docker hub. I am befuddled by the rest of the documentation, as when I tried an example using my local docker image name as below, docker run -d -p 3000:8000 --restart=always --name myport myport_nginx , only the nginx image service was pulled,and able to start up as a single container, but the rest of the services were not called up. Thus, my question is: How do I define those four images so that they are connected the way they are on my local computer, and so anyone with a local docker can pull my repo and inspect my app by going to 127.0.0.1 on his local computer. I know dockerbub is analogous to github and this should be straight-forward, but somehow my head has muddled this … -
Django: Saving multiple forms from one view
I've looked at a variety of answers but have been unable to progress. Code can be found here: https://github.com/varlenthegray/wcadmin/blob/master/customer/views.py - focused on "customer" right now with a bit of "jobsite" in there for good measure. Question: How do I get the job site primary key? It's reloaded via JS, so I presume it has to be in the form. Is the best method going to be to tag it on as a query string at the end of the URL? It's not "broken" as in it's not giving me any Django errors, but it's also not saving. forms.py class ViewCustomerForm(forms.ModelForm): next_service = forms.DateField(widget=forms.DateInput(format='%m-%d-%Y'), input_formats=['%m-%d-%Y']) edit_customer = forms.BooleanField(widget=forms.HiddenInput, initial=True) class Meta: model = Customer fields = ['company', 'title', 'first_name', 'middle_name', 'last_name', 'secondary_contact_name', 'website', 'email', 'main_phone', 'alternate_phone', 'fax_number', 'billing_address_1', 'billing_city', 'billing_state', 'billing_zip'] class ViewJobSiteForm(forms.ModelForm): edit_job_site = forms.BooleanField(widget=forms.HiddenInput, initial=True) next_service_date = forms.DateField(widget=forms.DateInput(format='%m-%d-%Y'), input_formats=['%m-%d-%Y']) class Meta: model = JobSite fields = ['name', 'address', 'city', 'state', 'zip', 'phone_number', 'email', 'next_service_date', 'active', 'access_code', 'bill_parent', 'customer', 'primary_technician', 'service_interval', 'requires_supporting_technician'] class EditJobSiteEquipment(forms.ModelForm): edit_job_site_equipment = forms.BooleanField(widget=forms.HiddenInput, initial=True) class Meta: model = JobSiteEquipment fields = ['id', 'tags', 'installed_on', 'edit_job_site_equipment'] views.py @login_required def view_customer(request, pk): customer = get_object_or_404(Customer, id=pk) job_site = JobSite.objects.filter(customer=pk).first() all_job_sites = JobSite.objects.filter(customer=pk) edit_customer = ViewCustomerForm(instance=customer, prefix='customer') edit_job_site = … -
Django custom model Interger extrafield not saving in the database return None instead
my models class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): print(phone_number, 'phone_number') """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), **extra_fields ) user.phone_number = phone_number # user.phone_number = 333333 print(user, 'user') user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=100, default="") phone_number = models.IntegerField(default=0, verbose_name='phoneNumber') is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser slug = models.SlugField(max_length=255, unique=True) objects = UserManager() def save(self, *args, **kwargs): print(self.phone_number, 'before') #this print statement return none if not self.slug: self.slug = slugify(utils.rand_slug() + "-" + self.username) super(User, self).save(*args, **kwargs) print(self.phone_number, 'after') #this print statement return none # notice the absence of a "Password field", that is built … -
Django Admin filter by foreign's key foreign key
I have a model that measures a certain tool's use defined as: class MetricToolUse(models.Model): date = models.DateTimeField(default="2000-01-01 12:00:00") user = models.ForeignKey(User, on_delete=models.DO_NOTHING) exec_time = models.FloatField('Execution time (s)') params = jsonfield.JSONField(default={}) On Admin I wan to be able to filter all MetricToolUse's of users that belong to certain groups. So the filter value is the Group name. class MetricToolUseAdmin(admin.ModelAdmin): list_filter = ( ('date', DateFieldListFilter), 'user', # custom filter for all users in group ) I tried using user__group but did not work -
How to get the desired value from the data used by the json dump method
The History model has a summary field. History object is created as follows, and the summary field uses the json.dumps method. The history field is a TextField, and in the template, it is of type 'str'. [views.py - how to create History object] history = History(user=request.user, study=new_study, summary=json.dumps({ 'field_summary': field_summary, 'file_summary': file_summary })) This is the summary field from the template . {"field_summary": {"is_recruiting": "None -> Yes", "teacher": None -> \uad8c\ub098\uacbd/\uae40\uc218\uc5f0"}, "file_summary": {}} But I want to get only the teacher values using annotate [views.py] histories = History.objects.filter(summary__icontains='teacher', create_date__gte='2022-01-01', create_date__lte='2022-04-10')\.annotate(teacher=Value(json.loads('summary')['field_summary']['teacher'], output_field=CharField()))\.values('study_name', 'teacher', 'create_date') Since we used json dumps, we used the json load method to read the data. But I get an error. How do I get the desired value of the textfield's str type? JSONDecodeError at /charts/ Expecting value: line 1 column 1 (char 0) -
How to store data requests in Django API running in AWS EC2?
So I have a Django API (via REST framework) in AWS EC2 that takes in raw JSON data. The API preprocesses the data and outputs a score from 0 to 100. I was wondering how I can store this incoming raw JSON data and the score efficiently for me to analyse the data. Not in a database because it would get complicated but preferrably in a file but I am not sure what is the easiest way. I request the data as data = request.data and the score is outputted like ypred = model.predict_proba(df) for i in range(len(ypred)): # first interval out of 3 intervals if( ypred[i][1]>=0.0 and ypred[i][1]<=0.30): response_dict = {"score": round(ypred[i][1]*100,3)} print(Response(response_dict, status=200)) return Response(response_dict, status=200) Thank you -
if select2 is null, make input field required
I have a text field and a select2 field. The user can input something in the input field, but can also select a predefined choice from the select2 field. I want to do the following: if the select2 is selected, then the form goes through, if not, the input field will be required and the form cannot pass through. I already made a logic in the backend (Django) that copies the value of the select2 to the text field just to make sure all data is valid, but if I leave the frontend without validation, the user could leave everything empty and submit an empty form. Here's my html: <table id="myTable" class="table order-list"> <thead> <tr> <td>Médicament</td> <td>Dosage</td> <td>Posologie</td> <td>Durée</td> <td></td> </tr> </thead> <tbody> <tr> <td class="col-5"> <div class="row"> <div class="col-6"> <input class="form-control mb-4" placeholder="Nom du médicament" type="text" name="medicament0"> </div> <div class="col-6"> <div class="form-group"> <select class="form-control select2-show-search form-select" id="medicament-id0" name="listemedicament0"> <option value="0">Ou choisir de la liste</option> {% for d in drugs %} <option value="{{ d.id }}">{{ d }}</option> {% endfor %} </select> </div> </div> </div> </td> <td> <input class="form-control mb-4" placeholder="20mg" type="text" name="dosage0"> </td> <td> <input class="form-control mb-4" placeholder="2 / j avant repas" type="text" name="posologie0"> </td> <td> <input class="form-control mb-4" placeholder="7 … -
2 models for html in Django
I want to list some data into my html file, below is my 2 models files and My question is how to show products_name in my html ? class ProductsDescription(models.Model): products_id = models.ForeignKey(to='Products', to_field='products_id', on_delete=models.CASCADE, unique=True) products_name = models.CharField(max_length=255, blank=True, null=True) class Products(models.Model): products_id = models.AutoField(primary_key=True) products_type = models.IntegerField(blank=True, null=True) manufacturers_id = models.IntegerField(blank=True, null=True) brand_id = models.IntegerField(blank=True, null=True) products.py from myadmin.models import Products as products from myadmin.models import ProductsDescription def index(request, pIndex=1): mainproducts = products.objects umproducts = mainproducts.filter(products_type=1) pIndex = int(pIndex) page = Paginator(umproducts, 25) maxpages = page.num_pages if pIndex > maxpages: pIndex = maxpages if pIndex < 1: pIndex = 1 list2 = page.page(pIndex) plist = page.page_range context = {"umproducts": list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages } return render(request, "index.html", context) in my html <table class="table table-hover"> <tr> <th>ID</th> <th>TYPE</th> <th>Products Name</th> <th>MANUFACTORES</th> <th>BRAND</th> </tr> {% for vo in umproducts %} <tr> <td>{{ vo.products_id}}</td> <td>{{ vo.products_type }}</td> <td>{{ vo.products_name }}</td> <td>{{vo.products_manufacturers}}</td> <td>{{ vo.products_brand}}</td> </tr> The problem maybe is I cann't put the product_name from ProductsDescription into umproducts tuple,and my question is how to connect 2 models and namea new tuple then I can use it in html?