Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle race conditions in ModelForms
I have a ModelForm that uses the model instance to perform a clean validation: class MyForm(forms.ModelForm): text_field = forms.CharField() def clean_text_field(self): print(self.instance.text_field) This works fine with the expected output when one user is using the form. However, if I open the form in 2 browser tabs, complete the form on the second tab and then try to complete the form on the first, self.instance.text_field returns None. What could be causing this? -
How to display the name of the wilaya and the name of the municipality on the map instead of displaying their id?
How to display the name of the wilaya and the name of the municipality on the map instead of displaying their id? The code below displays the wilaya id and the commune id instead of displaying the wilaya name and the commune name. How to solve this problem #models.py wilaya class Wilaya(models.Model): id = models.BigIntegerField() name = models.CharField(max_length=75)`` geom = models.MultiPolygonField(srid=4326) matricule=models.BigIntegerField(primary_key=True,null=False) def __str__(self): return self.name #models.py commune class Commune(models.Model): id = models.BigIntegerField() name = models.CharField(max_length=75) geom = models.MultiPolygonField(srid=4326) wilaya=models.ForeignKey(Wilaya,on_delete=models.DO_NOTHING,null=True) def __str__(self): return self.name #models.py even class Even(models.Model): name = models.CharField(max_length=20, default='Even') date = models.DateField(null=True, blank=True) wilaya=models.ForeignKey(Wilaya,on_delete=models.DO_NOTHING,null=True,blank=True commune=models.ForeignKey(Wilaya,on_delete=models.DO_NOTHING,null=True,blank=True geom = models.PointField(srid=4326, null=True, blank=True,) def __str__(self): return self.name #map.html var even = new L.GeoJSON.AJAX("{% url 'even' %}", { pointToLayer: function (feature, latlng) { return L.marker(latlng, { icon: L.icon({ iconUrl: "/static/img/icons/red.png", iconSize: [28, 32], iconAnchor: [12, 28], popupAnchor: [0, -25] }), title: feature.properties.name, riseOnHover: true }); }, onEachFeature: function (feature, layer) { var content = "<table class='table table-striped table-bordered table- condensed'>" + "<tr><th>Name</th><td>" + feature.properties.name + "</td> </tr>" + "<tr><th>Date</th><td>" + feature.properties.date + "</td></tr> </th></table>" + "<details><summary>" + "See more details"+"</summary> <table class='table table-striped table-bordered table-condensed'>" + " </td></tr>" + "<tr><th>Commune</th><td>" + feature.properties.commune + " </td></tr>" + "<tr><th>Wilaya</th><td>" + feature.properties.wilaya + " … -
Saving current user as assigned agent to model when updating model
I have a list of jobs that are created by the admin. When one of the agents starts the job by updating the notes. I would like to save that agent to the job model. Models.py class Job(models.Model): name = models.CharField(max_length=20, blank=True, null=True) agent = models.ForeignKey("Agent", on_delete=models.SET_NULL, null=True) start_date = models.DateField(null=True, blank=True) notes = models.TextField(default=0, null=True, blank=True) Views.py class JobUpdateView(LoginRequiredMixin, generic.UpdateView): template_name = "jobs/job_update.html" queryset = Job.objects.all() form_class = JobModelForm def get_success_url(self): return reverse("leads:lead-list") def job_update(request, pk): job = Job.objects.get(id=pk) form = JobModelForm(instance=job) if request.method == "POST": form = JobModelForm(request.POST, instance=job) if form.is_valid(): form.save() return redirect("/jobs) context = { "form": form, "job': job } return render(request, "jobs/job_update.html", context) -
Django REST Framework: I want to resolve n+1 in SerializerMethodField
I am trying to create a queryset that returns Boolean from a queryset prefetched with a reverse reference by SerializerMethodField, as shown in the code below. I'm creating one that determines if there is an object for the current user and returns Boolean. However, when I use the prefetched queryset to filter by the current user as shown below, a new queryset is issued instead of the prefetched queryset, and the n+1 problem occurs. In the following code, how can we save the queryset and return Booelan? class VideoSerializer(serializers.ModelSerializer): is_viewed = serializers.SerializerMethodField() is_favorited = serializers.SerializerMethodField() is_wl = serializers.SerializerMethodField() class Meta: model = Video fields = ( "pk", "is_viewed", "is_favorited", "is_wl", ) @staticmethod def setup_eager_loading(queryset): queryset.prefetch_related('history_set', 'favorite_set') def get_is_viewed(self, obj): user = self.context["request"].user if user.is_authenticated: try: obj.history_set.get(user=user) # <- here return True except History.DoesNotExist: pass return False def get_is_favorited(self, obj): user = self.context["request"].user if user.is_authenticated: try: obj.favorite_set.get(user=user) # <- here return True except Favorite.DoesNotExist: pass return False def get_is_wl(self, obj): user = self.context["request"].user if user.is_authenticated: try: Track.objects.get(playlist__user=user, playlist__is_wl=True, video=obj) return True except Track.DoesNotExist: pass return False A large number of query sets were issued. -
User group and permission based on tenants
This is a broad question and I'm here only to get my logic correct. I have an application where different companies registers. Now each company will have its own users. So I have extended the user model and made the user available only to their specific companies. The problem to me is with the user group and permission. Now each company will have its own group and permission (how to manage this?) also when a new company registers I create the user from the data available, now how to create the new group belonging to this new company and add roles and permission to this particular group or even give permission to this user at the time of registration. The permission is required because this will be the first user and based on permission it can do other things. Till now I created a superuser at the time of company registration but that's not right? (the dev work is still on that's why.) I have also extended the user registration model so for eg., if 2nd user is created for this company I am able to add it to a particular group. 2nd user is created at /api/registeruser/ and the … -
How to keep dropdown value in form after submit with Bootstrap and Django?
I've got a Bootstrap search form and I want to keep the values populated after submitting the form. Using Django and Jinja2 I can accomplish this using the value attribute for a regular input: <div class="form-group required"> <label class="control-label" for="carrier">Carrier</label> <input type="text" class="form-control form-control-sm" id="carrier" name="carrier" placeholder="Enter carrier" maxlength="25" value="{{request_data.carrier}}" required> </div> I'm trying to do the same thing with a Bootstrap dropdown/select field but after submitting the form the value resets back to the default value: <label for="environment">Select Environment for Data Search</label> <select class="form-control form-control-sm" name="environment" id="environment"> {% for env in environments %} <option>{{env.name}}</option> {% endfor %} </select> I tried adding the value attribute to the select tag but it didn't work and also messed up some formatting. Also, I don't have experience with PHP so ideally the solution wouldn't use PHP. Thanks -
django button with link to prefiltered data
Hej! I have multiple views, some with result tables and some detail views. From the detail views there should be links to other detail views (which works) and to some of the result tables with prefilled forms/prefiltered results. For example after the name given in the detail view. If clicked on the button I want to get redirected to the result table already filtered for the name of (e.g.) the parent institution given in the detail view. But I want to use the same template for all detail views (every institution gets a detail view) so it should be universal and not hard coded. Does anyone knows I could achieve that? I'm totally blank and can't find a good solution. # forms.py class SearchInstitutionsForm(forms.Form): name = forms.CharField( label="Name", required=False, ) # views.py def search_institution(request): if request.method == "POST": # create a form instance and populate it with data from the request: form = SearchInstitutionsForm(request.POST) if form.is_valid(): query = institution_filter_query(form) context = { "result_data": serialize(query), "form": form, "show_form": False, } return render(request, "stakeholders/search_form.html", context) else: form = SearchInstitutionsForm() class InstitutionDetail(DetailView): model = Institution def get(self, request, *args, **kwargs): institution = get_object_or_404(Institution, pk=kwargs['pk']) context = {'institution': institution} return render(request, 'stakeholders/institution_detail.html', context) # … -
Customize a response from a mutation using django-graphql-auth with graphene
I'm using django-graphql-auth and graphene on my django project. The django-graphql-auth library is nice but it lacks a bit on documentation and examples of customization. I already sent this question there but repo does not seem to get much activity lately (time to replace and use another package in the project perhaps), so I'll try my luck here: most of the questions related to customization are regarding inputs. In my case I'd like to change the output of the Register mutation, as I need the id of the user created on the response. So far what I manage to accomplish was to create a new custom mutation that inherits register, so I can add the logic to grab the created user: class RegisterCustom(mutations.Register): response = graphene.Field(RegisterResponseType) @classmethod def mutate(cls, *args, **kwargs): try: res = super().mutate(*args, **kwargs) if res.success: user = get_user_model().objects.order_by('-date_joined')[:1] return RegisterCustom(success=True, error="", user_id=user[0]['id']) except Exception: raise Exception(res.errors) However the return is not what I expect { "errors": [ { "message": "None", "locations": [ { "line": 472, "column": 5 } ], "path": [ "registerCustom" ] } ], "data": { "registerCustom": null } } if I add a print right before return let's say print(user[0]['id']) I can see the user … -
Preventing/Reducing deadlocks within a django application
I've been having a few issues recently working with a large MySQL database within django, MySQL seems to be having issues with deadlocks. I keep getting the error: (1213, 'Deadlock found when trying to get lock; try restarting transaction') Usually this seems to happen when calling the save or create functions for a new model instance (e.g). payment = Payment.objects.create( to_member=to_member, to_name="%s" % to_member.username, from_member=from_member, from_name="%s" % from_member.username, description="Resubscription", type='resubscription', amount=5.00, currency=from_member, processor='e-wallet' ) The particular table I'm trying to insert into has about 3.1 million rows and a size of 2.2 GB. In production the application has quite a number of active users (Member). The Payment model has two particular foreign keys (to_creator and from_member). So I wondered if that might be the cause of the be the cause of the issue rather than just on the Payment model? I've tried tweaking various aspect of the mysql configuration to manage this, but I seem to either get more deadlocks or the whole system locks up! Below are my current settings for the locks: Database locks Any help would be greatly appreciated. I've been pulling my hair out over the last few days about this. Dan -
Remove Decimal like " [Decimal('1220'), Decimal('160')] "from Django Queryset results
I have a queryset result which I would like to put into a list of Data and a list of Labels for Chart.js without showing Decimal. In my view.py the following funtion based view is written: labels = [] data = [] total_transactions_by_user = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins') ) ).order_by('-total') for each in total_transactions_by_user: labels.append(each["coin__name"]) data.append(each["total"]) The results of the lists are: ['Bitcoin', 'Dogecoin'] [Decimal('1220'), Decimal('160')] How do I remove Decimal() ,so I have 1220, and 160 in my List[] Thank you in advance. -
how can i create mini photo while creating photo?
i have a photo upload service on django. when i add a photo I want it to add one more photo with 50% split. If I put it in the pre_save on my photo save service, it can't find the photo (because it's not actually on the server) If I add it to the post_save, it goes into loop and adds unlimited when I add a photo (postman or etc.) How can get to save a small photo at a time?. here is my model class UserPhoto(General, Status): user = models.ForeignKey(UserBase, on_delete=models.CASCADE, verbose_name="User Id", related_name='UserPhoto_user', null=True, blank=True) link = models.ImageField(blank=True, null=True) order = models.IntegerField(null=True, blank=True) mini_link = models.ImageField(upload_to='mini_photos', blank=True, null=True) class Meta: db_table = 'user_photos' my view class UserPhoto(APIView): def get_object(self, pk): try: return Photo.objects.get(user__user__pk=pk) except Exception as e: return e def get(self, request): try: photo = self.get_object(request.user.pk) serializer = UserPhotoSerializer(photo) return Response(serializer.data) except Exception as e: print(e) def post(self, request): serializer = UserPhotoSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request): photo = self.get_object(request.user.pk) serializer = UserPhotoSerializer(photo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my serializer class UserPhotoSerializer(serializers.ModelSerializer): class Meta: model = UserPhoto fields = '__all__' def create(self, validated_data): validated_data["user"] = … -
Can I just only use MySQL command instead of pure Model in Django? [closed]
I'm newbie in Django and in my first project, I realise that it isn't neccessary to use the pure module Model of Django, and I prefer to use MySQL command to handle data. So when should I use the pure Model instead of MySQL to handle data? Are there any advantages of the Model over MySQL? -
individual Response message on perform_destroy()
I've written a custom perform_destroy()-method to do some additional checks. def perform_destroy(self,instance): force = self.request.data.get('force',None) resp = {} if Processingstepstatus.objects.filter(orderfile__order=instance).exists() and not force: raise serializers.ValidationError({"message": "Order already in production and can't be canceled cost-free. Perform Delete Request with parameter \"force:True\" to cancel and assume the costs of "+ str(instance.currentcosts)+"€" }) else: if Processingstepstatus.objects.filter(orderfile__order=instance).exists() and force: resp['invoice'] = "Placeholdervalue" instance.canceled = True instance.save() resp['message'] = "Successfully canceled your order." return Response(resp,status=status.HTTP_200_OK) This should give back a json-response with the message and the invoice information but it doesn't give any response except 204 - no content. I think it is being overwritten by the higher-level method destroy() here, right? How to handle that? best regards -
What is the recommended Django project strcuture for a SaaS product?
I would try to explain our desired product idea as clear as possible but feel free to ask further questions. So, basically what we want to build is a SaaS product that will be used by multiple clients. For now, we're not interested in custom domains like (cust1.myproduct.com, cust2.myproduct.com) and we will simply be using one database to manage all customers' data. So far so good. Our SaaS product will be sold to enterprise organizations which will then be used by their employees. So for any one customer organization, there are three types of roles that we would like to provide their users, as follows: Admin: An organization's admin that should be able to do all the settings for that particular organization Manager: An organization's manager that can manage the users that are under his/her team Employee: A normal user with bare minimal permissions that can only manage his own data Now, to provision customers for this SaaS product and to set their global settings (e.g. maximum allowed users, license type etc), we also plan to create an admin portal and APIs that will be used by our internal employees only. For this portal, we also want to define roles … -
Windows Apache stopped working and doesn't start anymore - "httpd.exe -k start" doesn't give errors
I have been hosting my Django REST project on a Windows server using Apache such that it works from https. Today it stopped working and I've been trying to find out the issue but I can't seem to get any useful info out of Apache. If anyone knows how to properly debug the error, or recognizes the issue I would greatly appreciate any help! I start Apache using PS C:\Apache24> bin/httpd.exe -k start Powershell doesn't say anything after this. But when I attempt to stop Apache it says it was never started! Again with no reason. PS C:\Apache24> bin/httpd.exe -k stop The 'Apache2.4' service is not started. I also checked the error.log, which again simply mentions that it failed to start. AH00378: Failed to start the 'Apache2.4' service This is my httpd.conf (I removed a lot of comments and boilerplate code). Note that it has worked before, I didn't change a thing. Define SRVROOT "c:/Apache24" ServerRoot "${SRVROOT}" Listen 8000 User daemon Group daemon ServerName 85.999.999.85:8000 # Django Project LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" WSGIScriptAlias / "c:/users/administrator/Desktop/django1/project/wsgi.py" WSGIPythonPath "c:/users/administrator/Desktop/django1/" <Directory "c:/users/administrator/Desktop/django1/project/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "c:/users/administrator/Desktop/django1/static/" <Directory "c:/users/administrator/Desktop/django1/static/"> Require all granted </Directory> WSGIPassAuthorization on … -
Django DRF - How to interact with a POST endpoint using CURL?
I'm new to Django DRF or API development in general, please be patient with me ;) Beside some pure get API views I now wanted to setup my very first endpoint where I can send data to, so I decided to go with a user password change. Here is what I did so far: views.py @api_view(['GET', 'POST']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def update_user(request): if request.method == 'GET': serializer = UserSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = UserSerializer(request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) password = serializers.CharField( max_length=128, min_length=8, write_only=True ) class Meta: model = User fields = ('id', 'user', 'password', 'pin', 'avatar') read_only_fields = ('id', 'user') def update(self, instance, validated_data): password = validated_data.pop('password', None) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() return instance Now the question is how can I update the referenced fields like "pin" or especially "password" using curl. The first thing I always do is to get myself a new token like this: curl -X POST -d "user=admin&password=admin" http://localhost/api/v1/token/obtain {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWYzN2RiODUtYjU5Yy00YjRmLWFhNjYtMDExNGFmYWQ4ZDdiIiwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6MTYzNDE3Mjg3MiwidXNlciI6ImFkbWluIiwib3JpZ19pYXQiOjE2MzQxMjk2NzJ9.zz9Zyai3Y7MhR_chGkzA6jXY_BdjN5Eu2muRvyWIppw"} With this token in place I can now reach the update_user endpoint but I don't understand how to interact with it … -
Type Error: Init Requires 1 Positional Argument Yet 2 Are Given
Hey so I'm getting this error when I'm trying to make a text area on my site to update a user's 'about' information. It just handles the info of an existing user to update their 'about' field. Any more info needed just let me know and any insight/solutions would be appreciated, thanks in advance. class change_about(UpdateView): def get_object(self, queryset=None): return User.objects.get(user=self.request.user) def form_valid(self, form): instance = form.instance # This is the new object being saved instance.user = self.request.user instance.save() return super(change_about, self).form_valid(form) -
Django Multiple Queries
I'm using lots of queries to find the sum of fields [ft_day, ft_night] in multiple records for specified date intervals e.g. last 7 days, last 6 months etc. This is needed to display a summary of total times at the aforementioned date intervals in a template. ft_total is a property in Models Is there a more efficient way to do this? Not really sticking to DRY here. Thanks for your help. views.py get_context_data() ## shortened ## context['last_6_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 5)/12), (self.date_now.month - 6) % 12 - 1, self.date_now.day), self.date_now) ).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total')) context['last_12_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 12)/12), (self.date_now.month - 12) % 12 - 1, self.date_now.day), self.date_now) ).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total')) -
Frontend, I don't understand if querySelector has been found Frontend
I'm writing the front,ajax response js. The final code comes, which must be inserted on the page Like after const div = document.querySelector('.row_wow_fadeIn>#xxx1'); the code doesn't work. js function ajaxSend(url, params) { // Отправляем запрос fetch(`${url}?${params}`, { method: 'GET', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(response => response.json()) .then(json => render(json)) .catch(error => console.error(error)) } const forms = document.querySelector('form[name=filter]'); forms.addEventListener('submit', function (e) { // Получаем данные из формы e.preventDefault(); let url = this.action; let params = new URLSearchParams(new FormData(this)).toString(); ajaxSend(url, params); }); function render(data) { // Рендер шаблона let template = Hogan.compile(html); let output = template.render(data); const div = document.querySelector('.row_wow_fadeIn>#xxx1'); div.innerHTML = output; } let html = '\ {{#twister}}\ <div>\ <img class="X" src="{{ image }}" class="img-fluid">{{ title }}\ <p class="text-dark">{{ price }} ₽</p>\ </div>\ </div>\ {{/twister}}' Html: <!--Grid row--> <div class="row_wow_fadeIn row d-flex justify-content-center wow fadeIn col-md-12"> <!--Grid column--> <div class="col-lg-3 col-md-6 mb-4"> <div> <div id="xxx1" class="XXX"> {% for twister in case_list %} <img class="X" src="{{ skin.image.url }}" class="img-fluid">{{ skin.title }} <p class="text-dark">{{ skin.price }} ₽</p> {% endfor %} </div><input type="button" onclick="LetsGo()" value="!!!Исчо!!!"> </div> </div> <!--Grid column--> </div> -
I need my Kivy App to send data to my Django Website
So I created a App with Kivy that creates a poll. I want to send this poll data (Name, Time) to my website made with django. Has anybody experiece with it or knows how I can do it? -
Images from database not displaying in Heroku Django after hosting
I have few images in my SQLite database which I will be changing from admin panel over a period of time. I have hosted the django app in heorku(free service). All the static images are displaying (The one's not in database), but the uploaded images are not displaying. I have uploaded the image before deploying. The description for each image is being displayed but the image is not. I am using whitenoise and have viewed multiple other answers and they have not worked settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' if os.getcwd() == '/app': DEBUG = False html template: <div class="container"> {% comment %} Row 1 {% endcomment %} <div class="row my-5"> {% for image in images %} <div class="col-sm col-md-4 col-lg-4 col-xl-4 my-3"> <div class="card" > <img loading='lazy' src="{{image.image.url}}" class="img card-img-top my-2" alt="{{image.title}}"> <div class="card-body"> <p class="card-text">{{image.title}} </p> </div> </div> </div> {% endfor %} </div> </div> models.py : class Gallery(models.Model): image = models.ImageField(upload_to … -
The view "..." didn't return an HttpResponse object. It returned None instead
I am currently getting a Value Error on my current application where the program is supposed to print a pdf file. The full error message states the following: ValueError at /accConnect/trialBalanceMonthly/8 The view main.views.trialBalanceMonthly didn't return an HttpResponse object. It returned None instead. I have tried to check if there was any module I am missing and checked to see if the bool value that printing this file depended on was True (it was )- So I can't seem to find what could be causing this problem. My current code is as follows: URL.py: path('accConnect/trialBalanceMonthly/<int:reports_pk>' , views.trialBalanceMonthly, name='trialBalanceMonthly'), path('accConnect' , views.reportsHome, name='reportsHome'), View.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML import tempfile def trialBalanceMonthly(self , reports_pk): pkForm = get_object_or_404(SettingsClass, pk=reports_pk) complexName = pkForm.Complex # CHECKING TRIAL BALANCE MONTHLY SETTINGS if pkForm.Trial_balance_Monthly == True: # SQL STATEMENT baseTRBMonth = 'SELECT Master_Sub_Account , cAccountTypeDescription ,Debit , Credit FROM PostGL AS genLedger ' \ 'Inner JOIN Accounts ' \ 'on Accounts.AccountLink = genLedger.AccountLink ' \ 'Inner JOIN _etblGLAccountTypes as AccountTypes ' \ 'on Accounts.iAccountType = AccountTypes.idGLAccountType ' \ 'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) ' \ 'AND genLedger.TxDate > ? ' xtrbMonth = … -
Create a django model for saving train and test data in database
I am trying to create a website by django which a user can upload a csv file. in server I want to save this csv file as train data for a machine learning model. and I can't make a Model by the csv file because I don't know the name of the fields. and these names can change in differant datas. for example for one data it may seem like this: class TrainData(models.Model): humidity = models.IntegerField(...) wind_speed = models.IntegerField(...) is_it_raining = BooleanField(..) and we want to run a machine learning algorithm on this model by fields. and another data will be like: class TrainData(models.Model): X1 = models.CharField(...) X2 = models.CharField(...) X3 = models.CharField(...) y = models.CharField(...) a bad approach is (I guess) to convert this csv file into a DataFrame and convert DataFrame into a Pickle file and save it in data base by a model like bellow: class TrainData(models.Model): data = PickledObjectField() is there a better way to create this model?? and is creating data to pickle a good practice? -
Python Django variables data duplication after page refresh
I am passing a string to template, and It works fine, but when I reload the page, that string is duplicated. The string is generated dynamically and contains html-table, I want to render a table from variable in my template Only server reset helps to see the actual table without duplicates Code from views.py: def test(request): headings = ('RED', 'GREEN', 'BLUE') tb = Table() tb.make_headings(headings) cell_1 = Cell('1') cell_2 = Cell('2') cell_3 = Cell('3') row_1 = Row() row_1.add_cell(cell_1) row_1.add_cell(cell_2) row_1.add_cell(cell_3) tb.add_row(row_1) html_table = tb.create_html_table() return render(request, 'test.html', context = { 'table' : html_table }) create_html_table() function: def create_html_table(self): html_table = '<table>' for row in self.raw_table: html_row = '<tr>' for cell in row.cells: html_cell = '<td>{}</td>'.format(cell.get_data()) html_row += html_cell html_row += '</tr>' html_table += html_row html_table += '</table>' return html_table Row code: from .cell import Cell class Row(): cells = [] def __init__(self): self.cells = [] def add_cell(self, cell: Cell): self.cells.append(cell) def get_cells(self): return self.cells Cell code: class Cell(): def __init__(self, data = []): self.data = data def get_data(self): return self.data -
Without AuthMiddlewareStack how can I get logged user in Django channels?
Without AuthMiddlewareStack how can I get logged, user? Because I am not used auth models that's why self.scope['user'] returning the 'Anonymous'. I tried to add this class AllowedHostsOriginValidator - doesn't work. I want a session user. please help me. routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from chat.consumers import ChatConsumer from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('ws/chat/pm-with/<str:username>/',ChatConsumer()), ]) ) ) }) consumers.py from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from chat.models import user,Thread,Message from chat.views import ChatView from django.contrib.sessions.models import Session class ChatConsumer(SyncConsumer): def websocket_connect(self,event): me = self.scope['user'] other_user = self.scope['url_route']['kwargs']['username'] getOtheruser = user.objects.filter(username = other_user).first() self.send({ 'type': 'websocket.accept', }) def websocket_receive(self,event): print("new event is received") print(event) self.send({ 'type': 'websocket.send', 'text': event.get('text'), }) def websocket_disconnect(self,event): print("disconnect event is called") custom user models models.py class user(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50,default="", blank=True, null=True) last_name = models.CharField(max_length=50,default="", blank=True, null=True) username = models.CharField(max_length=50,default="", blank=True, null=True) password = models.CharField(max_length=100,default="", blank=True, null=True) image = models.ImageField(upload_to ='user_image',default="",blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) deleted = models.DateTimeField(default="",blank=True, null=True) is_deleted = models.BooleanField(default=False) I want login users from custom models, not auth user models. please help me for this