Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to run that view inside of a django?
I'm new with Django, so please bear with me. I have the following view @csrf_exempt @api_view(http_method_names=['POST']) def login_agro_user(request): request_data = request.data if not request_data: return Response({"status_code": 400}) secret = request_data.get('secret') if secret != 'test': return Response({"status_code": 400}) payload = request_data.get('payload') payload = json.loads(base64.b64decode(payload).decode('utf-8')) serializer = AgroUserSerializer(data=payload) if serializer.is_valid(): query = AgroUser.objects.filter(user_guid=payload['user_guid']) if not query: serializer.save() elif query[0].active == False: query.update(active=True) key = secrets.token_urlsafe() query.update(key=key) response_data = {"callback": f"{settings.FRONT_BASE_URL}/{key}"} return Response(response_data) return Response({"status_code": 400}) This view seems to be linked to the following endpoint urlpatterns = [ path('', admin.site.urls), url(r'^api/v1/login_agro_user', login_agro_user), The code should be generating a token, like this one zLdu6NrHnvyUnixnvV-PiaQwro4QSNp0MaRmYQ9W09c. However, My question are the following: Where should the view be appearing? If I want to create the token, should I run the views in a standalone mode? Any help is welcomed as I'm losing my sanity. Thanks. -
How ro create e questionnaire in python django
I have an assignment to work on. The details of assignment are as follows: Learning variables: Python, Django/flask, Docker, JS Task: to develop a simple questionnaire system The user should be able to have a simple dialog with the system and to go through predefined questions and answers. Dialog example: Are you hungry? (Yes/No) Yes: What would you like to eat? (Hamburger/Pizza/Pop Corn/Chicken) Hamburger: Nice, I will order a hamburger for you! Pizza: Would you like pizza with mushrooms? (Yes/No) Yes: Ok, I will order the best pizza in town for you No: No? Well... stay hungry then No: Ok. Call me when you're hungry. The system consists of two parts: user app (frontend) and backend. Frontend functionality: 1. Show questionnaires list (user can select what questionnaire he/she will pass) 2. Go through Q&A (show question and possible answers to the user) Backend functionality: 1. Load questionnaires structure from JSON file 2. REST API for user app (questionnaires list) 3. When the conversation finished (last question answered) the backend should log the conversation history into the console. The log should contain the first question and all subsequent user answers. Example: Are you hungry?: Yes -> Pizza -> Yes Limitations: 1. … -
Partially annotate django queryset
I have a query that looks like that TrendData.objects.filter(owner__trend_type__mnemonic='posts').filter( date_trend__date__range=[date_from, date_to]).order_by(sort_by)[0: 100].values( 'owner__name', 'owner_id', 'owner__link', ).annotate( owner_count=Count('owner_id')).annotate(views=Sum('views'), views_u=Sum('views_u'), likes=Sum('likes'), shares=Sum('shares'), interaction_rate=Sum('interaction_rate'), mean_age=Sum('mean_age') ) It was worse before, however I have noticed that annotation sums ALL the values in queryset, not the limited queryset that I set before annotation. Is it possible to annotate only partially , the amount I have limited. My RAW query looks like this 'SELECT "api_trenddata"."id", "api_trenddata"."owner_id", "api_trenddata"."views", "api_trenddata"."views_u", "api_trenddata"."likes", "api_trenddata"."shares", "api_trenddata"."interaction_rate", "api_trenddata"."mean_age", "api_trenddata"."source_id", "api_trenddata"."date_trend", SUM("api_trenddata"."views") AS "views", SUM("api_trenddata"."views_u") AS "views_u", SUM("api_trenddata"."likes") AS "likes", SUM("api_trenddata"."shares") AS "shares", SUM("api_trenddata"."interaction_rate") AS "interaction_rate", SUM("api_trenddata"."mean_age") AS "mean_age" FROM "api_trenddata" INNER JOIN "api_owner" ON ("api_trenddata"."owner_id" = "api_owner"."id") INNER JOIN "api_trendtype" ON ("api_owner"."trend_type_id" = "api_trendtype"."id") WHERE ("api_trendtype"."mnemonic" = posts AND("api_trenddata"."date_trend" AT TIME ZONE \'UTC\')::date BETWEEN 2019 04-05 AND 2019-04-06) GROUP BY "api_trenddata"."id"' -
Django request.data.get('submit') returns always none, even if name is provided as name="submit"
I am passing a form from my template to views, with some text inputs and a input type button as follow: <input type="submit" name="submit_btn" value="Continue"> But in my views when I do print(request.data.get('submit_btn')) It return none. Also when I do : print(request.data) It return all values except the 'submit_btn' Please HELP! -
Django: serialize QuerySet and send it to template to be used with Javascript
I've a QuerySet and I need to send it to my template, because I need to manipulate its values to generate a JS array. But when in my view I use: order_items = json.dumps(order_items) I get: Object of type QuerySet is not JSON serializable view: import json def thanks_deposit_payment(request): order_number = Order.objects.latest('id').id total = Order.objects.latest('id').total costo_despacho = Order.objects.latest('id').shipping_cost order_items = OrderItem.objects.filter(order=Order.objects.latest('id')) # order_items = json.dumps(order_items) response = render(request, 'thanks_deposit_payment.html', dict(order_number=order_number, total=total, order_items=order_items, costo_despacho=costo_despacho)) return response This is what I need to do in my template: <script> window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'eec.purchase', ecommerce: { currencyCode: 'PEN', purchase: { actionField: { id: {{ order_number }}, affiliation: 'Stickers Gallito E-Commerce', revenue: {{ total }}, shipping: {{ costo_despacho }}, coupon: 'SUMMER2019' } }, products: [ {% for item in order_items %} { id: item.order.id, name: item.product, price: item.price, size: item.size, quantity: item.quantity }, {% endfor %} ] } }); </script> -
ListSelect2 in django-autocomplete-light showing an empty dropdown
I'm trying to add autocomplete to a country field on out model. The autocomplete is populating when this code is added: # form.py class CustomUserChangeForm(UserChangeForm): country = autocomplete.Select2ListCreateChoiceField( choice_list=get_user_model().get_country_choice_list, # widget=autocomplete.ListSelect2(url='http://127.0.0.1:8000/accounts/country-list-autocomplete',), ) class Meta: model = CustomUser fields = ('first_name', 'last_name', 'company', 'country') but when i decomment the widget line the field is rendered as empty in the dropdown, and it doesn't resemble an input at all- rather a dropdown still. get_user_model().get_country_choice_list returns a list as expected: ['Afghanistan', 'Åland Islands', 'Albania', 'Algeria'... My endpoint is functioning correctly (assuming the format is correct): { "results": [ { "id": "Afghanistan", "text": "Afghanistan" }, ... for the widget i've tried the following options: widget=autocomplete.ListSelect2(url='http://127.0.0.1:8000/accounts/country-list-autocomplete',), widget=autocomplete.ListSelect2(url='accounts/country-list-autocomplete',), widget=autocomplete.ListSelect2(url='country-list-autocomplete',), each to no avail. I have no error in the terminal, and no request is generated. The html element looks like this when the widget is uncommented: <select name="country" id="id_country" data-autocomplete-light-language="en-US" data-autocomplete-light-url="/accounts/country-list-autocomplete" data-autocomplete-light-function="select2"> <option value="Antarctica" selected="">Antarctica</option> </select> Any ideas why this is not working? -
How do I order a model by parent category in django?
I have a model "Category" with a ForeignKey to "parent_category". How can I order this model in the Django admin list view like: - category 1 -- subcategory 1 of category 1 --- subsubcategory 1 of subcategory 1 of category 1 -- subcategory 2 of category 1 -- subcategory 3 of category 1 - category 2 -- subcategory 1 of category 2 -- subcategory 2 of category 2 I have tried the following but this won't work. So I need some help to order the function 'get_relative_name'. class PrivateContentCategory(models.Model): name = models.CharField( max_length=250, verbose_name=_('Naam'), ) slug = models.SlugField( verbose_name=_('Url'), blank=True, ) parent_category = models.ForeignKey( 'self', on_delete=models.SET_NULL, related_name='child_category_list', verbose_name=_('Hoofdcategorie'), blank=True, null=True, ) def __str__(self): str = self.name parent_category_obj = self.parent_category while parent_category_obj is not None: str = parent_category_obj.name + ' --> ' + str parent_category_obj = parent_category_obj.parent_category return str def get_relative_name(self): str = self.name parent_category_obj = self.parent_category while parent_category_obj is not None: str = '--' + str parent_category_obj = parent_category_obj.parent_category get_relative_name.short_description = _('Naam') get_relative_name.admin_order_field = [ 'parent_category__parent_category', 'name', ] -
How to use custom django filters in django passing string parameters?
I made a new filter in django. Its name is iarray and this is its definition: from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter(is_safe=True) @stringfilter def iarray(value, arg): """ This return the value of array in arg index:: value[arg] :param value: :return: """ value = eval(value) return value[str(arg)] In theory, this function should return the value of a dict in a given position. The problem is when templates are rendering. For example: "text": "<h1>Holguín</h1><br /><p>{{ provincias|iarray:'Holguín'|safe }}</p>"... The above code throws the following exception: Error during template rendering In template /srv/www/eicma/templates/eicma/index7.html, error at line 527 (the above line). The trouble is in production mode, in dev mode the trouble doesn't exist So, my questions are the following: 1. It's something wrong? Of course, I loaded filters and added to INSTALLED_APPS. -
How to assign a row id to a selected radio button?
I have a table with multiple entries. Each row has a radio button. I want to assign the id of the row to the currently selected radio button. I am using Django 2.1 and ModelForms where one of these should be a RadioSelect form. However I don't quite get how to assign the value of the row to the radio button. Here is how it looks right now Model class Testplan (models.Model): testName = models.CharField(max_length=200,default='') selectionScenario = models.CharField(max_length=200,default='') author = models.CharField(max_length=200,default='') type = models.CharField(max_length=200,default='', choices=testplan_type_options) status = models.CharField(max_length=200,default='', choices=testplan_status_options) version = models.CharField(max_length=200, default='') created = models.CharField(max_length=200,default='') updated = models.CharField(max_length=200,default='') ModelForm class TestPlanForm(forms.ModelForm): CHOICES=[('',''),] selectionScenario = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) #Since Radio is not supported in the Model. class Meta: model = Testplan fields = ('testName', 'selectionScenario', 'author', 'type' , 'status', 'version', 'created', 'updated', ) widgets = { 'testName': forms.TextInput(attrs={'class' : 'form-control'}), 'author': forms.TextInput(attrs={'class' : 'form-control'}), 'type': forms.Select(attrs={'class' : 'form-control'}), 'version': forms.TextInput(attrs={'class' : 'form-control'}), 'status': forms.Select(attrs={'class' : 'form-control'}), 'created': forms.TextInput(attrs={'class' : 'form-control'}), 'updated': forms.TextInput(attrs={'class' : 'form-control'}), } HTML Snippet <table id="dt_basic" class="table table-striped table-bordered table-hover" width="100%"> <thead> <th>Select</th> <th>Scenario Name</th> <th>Scenario Functional</th> <th>Author</th> <th>Type</th> <th>Version</th> <th>Map</th> <th>Dynamic Objects</th> <th>Weather</th> <th>Maneuver</th> <th>Created</th> <th>Updated</th> </thead> <tbody> {% for item in scenario_list %} <tr> <!-- <td>{{ … -
sequence item 1: expected string, OrderedDict found
I'm trying to perform a check, but I get an error sequence item 1: expected string, OrderedDict found. With what it can be connected? This is the function in the documentation. https://github.com/cloudipsp/python-sdk/blob/master/cloudipsp/helpers.py#L85 def get_transaction(self, request, signature, origin): print(type(origin)) #dict data = origin.copy() result = None trans = None if data: data['signature'] = signature data = dict((k, v) for k, v in data.iteritems() if v not in (None, '')) data = OrderedDict(sorted(data.items())) if helper.is_valid(data, self.secret_key, self.api.api_protocol): #sequence item 1: expected string, OrderedDict found -
auto hide text on zoom in
I have piece of code in openlayers. I need to auto hide some text after zooming in. nothing worked so far. This is what I have now. var mar = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])), }); var iconBlue = new ol.style.Style({ image: new ol.style.Icon({ anchor: [12, 40], anchorXUnits: 'pixels', anchorYUnits: 'pixels', opacity: 1, src: '../../images/marker_blue.png' }), text: new ol.style.Text({ text: "Test text", scale: 1.2, fill: new ol.style.Fill({ color: "#fff" }), stroke: new ol.style.Stroke({ color: "0", width: 3 }) }) }); mar.setStyle(iconBlue); vectorSource.addFeature(mar); }``` need to hide text while the user zooms in fully(or after a particular zoom). any help/guidance is appreciated. -
Django Filters: Use existing function and add it to a filter
in helpers.py I have function def is_user_available(user): #some logic return True return False and then I have to use the same logic in my template but since I don't want repeating code can I assign this function into a filter in my filters.py I've tried @register.filter(is_safe=True,name='is_user_available', function=is_user_available) but it's not working. -
Foreign key error in django, Cannot assign "'1'": "Release.projectID" must be a "Project" instance
I have two applications. 'Project' and 'Release' In release table, projectId is foreign key associated with Project table. when tried creating new release, when entered projectID , getting "Cannot assign "'1'": "Release.projectID" must be a "Project" instance" error I have three files named, models.py, forms.py,views.py models.py: class Project(models.Model): JIRAID = models.CharField(max_length=20,null=True) projectID = models.AutoField(primary_key=True) projectName = models.CharField(max_length=100) projectDescription = models.CharField(max_length=100) projectStartDate = models.DateField() projectEndDate = models.DateField() projectEstimatedLOE = models.IntegerField() createdBy = models.CharField(max_length=30) createdAt = models.DateTimeField(default=datetime.datetime.now,null=True,blank=True) updatedAt = models.DateTimeField(default=datetime.datetime.now,null=True,blank=True) def __str__(self): return (self.JIRAID, self._get_pk_val, self.projectName, self.projectDescription, self.projectStartDate, self.projectEndDate, self.projectEstimatedLOE,self.createdBy,self.createdAt,self.updatedAt) class Meta: db_table='Project' class Release(models.Model): JIRAID = models.CharField(max_length=20 ) projectID = models.ForeignKey(Project,on_delete=models.CASCADE,null=True) releaseID = models.AutoField(primary_key=True) releaseName = models.CharField(max_length=100) releaseDescription = models.CharField(max_length=100) releaseStartDate = models.DateField() releaseEndDate = models.DateField() releaseEstimatedLOE = models.IntegerField() createdBy = models.CharField(max_length=30) createdAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) updatedAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) def __str__(self): return (self.JIRAID, self.projectID,self._get_pk_val,self.releaseName, self.releaseDescription, self.releaseStartDate, self.releaseEndDate, self.releaseEstimatedLOE,self.createdBy,self.createdAt,self.updatedAt) class Meta: db_table='Release' unique_together = (('projectID', 'releaseID'),) Views.py: def releasecreation(request): context = {'form': Release} if request.method=='POST': form = ReleaseCreationForm(request.POST) if form.is_valid(): JIRAID=request.POST.get('JIRAID') projectID=Project.objects.get('projectID') releaseID=request.POST.get('releaseID') releaseName=request.POST.get('releaseName') releaseDescription=request.POST.get('releaseDescription') releaseStartDate=request.POST.get('releaseStartDate') releaseEndDate=request.POST.get('releaseEndDate') releaseEstimatedLOE=request.POST.get('releaseEstimatedLOE') createdBy = User.objects.get(username=request.user.username) form.save() return render(request,'releasepages/releasecreateconfirmation.html') else: return render(request,'releasepages/releasecreate.html') else: return render(request,'releasepages/releasecreate.html',context) I should be able to create release,by getting dropdown at projectID column while creating release. -
Custom registration form don't register the user and no error message is shown
I've create a registration form divided in two part: company's datas and rapresentative's datas. At the start of developing I'm interesting only at the company's datas and, as tests, I've registered the users both use the default Django admin panel that my form. Now I've upgraded the model for registration with other datas. When I send the datas the new user is registered only if I use the default Django admin panel, but if I use my form something was wrong because I see on the terminal the message Invalid form. Something was wrong!! I don't understand where is the error because on the terminal there isn't another error message even if I delete print("Invalid form. Something was wrong!!"). form.py class UserProfileCreationForm(UserCreationForm): username = forms.CharField( widget=forms.TextInput(attrs={ 'placeholder': 'Write the username', 'class': 'form-control', } ), label='Company Username', help_text='Write the name of your Company', required=False, ) password1 = forms.CharField( label="Password", widget=forms.PasswordInput(attrs={ 'class': 'form-control', } ), strip=False, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput(attrs={ 'class': 'form-control', } ), ) company_name = forms.CharField( widget=forms.TextInput(attrs={ 'placeholder': 'Write the name of your Company', 'class': 'form-control', } ), label='Name of Company', ) company_city = forms.CharField( widget=forms.TextInput(attrs={ 'placeholder': 'Write the name of the city in which there … -
How to setup django app setup on live IP?
Error: That IP address can't be assigned to. I am facing some problem to setup python django app on my server. when I gave private IP address it runs but when I gave public IP: in the browser it does not work. Can you please tell me how to run public IP: from the browser? -
How to add fields from different models in the same admin view?
I am trying to create a separate admin page entry where I can see fields that interest me from different models on the same page. get_sensor_id is defined in a model called MountedSensor, separate from SensorViewTypeBackgroundInfo @admin.register(SensorViewTypeBackgroundInfo) class SensorViewBackground(admin.ModelAdmin): model = SensorView fields = ('sensor_view_id', 'sensor_view_name') list_display = ('enum_name', 'info_id', 'get_sensor_id') Currently, I get the following error: The value of 'list_display[2]' refers to 'get_sensor_id', which is not a callable, an attribute of 'SensorViewBackground', or an attribute or method on 'app.SensorViewTypeBackgroundInfo' -
Django filter based on request data inside perform_create
I have an API endpoint which creates an object with a specific field. I do this by using perform_create def perform_create(self,serializer): group = DeviceGroup.objects.get(is_default=True, customer_uuid='some uuid') serializer.save(group_uuid=group) When I hardcode the uuid of a customer, it works like a charm. However, I obviously do not want to hardcode an uuid in there. The customer_uuid is sent in the POST request. I tried: self.kwargs['customer_uuid] self.request.customer_uuid self.request.GET['customer_uuid] self.request.GET('customer_uuid') How do I get the customer_uuid from the request? -
could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
i try to publish my first project on python anywhere but it still not working and this is my error : could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'arena', 'USER': 'arenadbuser', 'PASSWORD': , 'HOST': 'localhost', 'PORT': '', } } -
Async changes in template when model update
I have a django chat app, and in my models I have rooms and these rooms have messages. I want to reflect notifications asynchronously in the navbar when new messages are created (just like the red dot that appears in most commons real chat apps, like WhatsApp or Telegram). Any suggestions? This is my actual notification image And this is kinda what i want -
Python/Django Best way to control a program with a button?
I'm currently working on a django project. I would like to run background tasks such as a script checking URLs every hours and inserting data in my db. And I have a few questions... I am currently running the script in my view as a subprocess. I have a start button on my HTML page and when I click on it, I'm creating a subprocess and entering True in a table. I also have a stop button, when I click on it I'm turning the record to False. So here is my little script : (buttonValue() is checking my db record to see the button value) Script.py while True: while buttonValue() == True: doWhatIHaveToDo() View.py def post(self, request, **kwargs): value = ButtonValue.objects.last() if 'start' in request.POST: value.status = True value.save() Popen('python Script.py') else: value.status = False value.save() context = super(ClassName, self).get_context_data(**kwargs) context['value'] = value return super(TemplateView, self).render_to_response(context) This script is working but my question is : what is the best way to manage this kind of needs ? -
Django Left Join With Filter on Custom Many to Many Model
I have 3 models (User-default model , Project, ClickedUsers-custom m2m model) and I want to perform left join with filter in ORM on ClickedUsers and Project models. I tried the solutions on Stack Overflow but when I print those queries I saw they performed Inner join. Here are my models : class Project(models.Model): … clicked_users = models.ManyToManyField(User,through='ClickedUsers',blank=True) class ClickedUsers(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) project = models.ForeignKey(Project,on_delete=models.CASCADE) status = models.IntegerField(default=0) And the query I want to perform : select * from project LEFT JOIN clickedusers ON project.id = clickedusers.project_id WHERE clickedusers.user_id = 1; -
postgresql to sqlite migration issue
I'm new to postgresql. I've django project using postgresql. I want to move my existing database in postgresql to sqlite. For this, I've tried different methods as mentioned in this forum but each gave me various. Finally, a tool named potgresql-to-sqlite worked with some minor changes to postgrql dump file. Now I could launch my django webapp. But on a certain page I get error like, TechItem' object has no attribute '_mi_selection_params_cache' I've a column named 'mi_selection_params'., but there is no such column as '_mi_selection_params_cache' in my database. What does this error mean? Where should I look into the code for solving this issue? Here is the traceback, Traceback (most recent call last): File "E:\gir\python3.5\lib\site-packages\django\db\models\fields\related_descriptors.py", line 178, in __get__ rel_obj = getattr(instance, self.cache_name) AttributeError: 'TechItem' object has no attribute '_mi_selection_params_cache' -
Passing data between endpoints in Django
I am working a project where it requires me to pass one set of data from one endpoint to another. For example I have data in this table: I want to be able to select one item, or all items from the table and moved them to another endpoint, while the items on this endpoint get delete. The endpoint example is like: data from: '/approve' -> '/match' I was wondering how would I go about doing this in Django, I am fairly new to the framework. -
Copy a File from one Model's FileField to another Model's FileField without reading it
Let's say I have a model somewhat like this - class Test(models.Model): some_file=FileField(upload_to='test_directory') class TestTransfer(models.Model): transferred_file=FileField(upload_to='transfer_directory') Now, I have already tried simple object to object copying like this: transfer_object.transferred_file=test_object.some_file transfer_object.save() What the above code does not do is, it does not upload the file to transfer_directory. I am using S3 as media storage is that's needed. If there is some work around this problem, I would be content -
Ordering using DateTimeField Not Accurate
I want to order objects in descending order using the date_joined field that is a DateTimeField. My major problem is the inaccuracy of the queries. I'm currently on Django 2.1 and my database is MySQL. When I run: CustomUser.objects.filter(is_staff=True).order_by('-date_joined') I get these as the results: Aug. 17, 2018, 12:48 p.m. Aug. 17, 2018, 10:46 a.m. June 22, 2018, 11:28 a.m. Feb. 15, 2019, 3:18 p.m. July 14, 2018, 6:28 p.m. July 13, 2018, 6:28 p.m. Feb. 21, 2019, 4:17 p.m. Instead of: Feb. 21, 2019, 4:17 p.m. Feb. 15, 2019, 3:18 p.m. Aug. 17, 2018, 10:46 a.m. Aug. 17, 2018, 12:48 p.m. July 13, 2018, 6:28 p.m. July 14, 2018, 6:28 p.m. June 22, 2018, 11:28 a.m. What am I missing?