Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
customizing django admin tabular inline using smart_selects chained select field
I am trying to implement dependent select field called ChainedForeignKey (dependent on another select field) using smart_selects . I have followed the documentation (https://django-smart-selects.readthedocs.io/en/latest/index.html)but they do not consider (Django admin) templates where you have no {{ form.as_p }} tag. I'm pointing this out because one of the implementation steps is to include {{ form.media.js }} tag before your {{ form.as_p }}. However django tabular inline template (located in pathtodjango\contrib\admin\templates\admin\edit_inline\tabular.html) looks as following; {% load i18n admin_urls static admin_modify %} <div class="js-inline-admin-formset inline-group" id="{{ inline_admin_formset.formset.prefix }}-group" data-inline-type="tabular" data-inline-formset="{{ inline_admin_formset.inline_formset_data }}"> <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}"> {{ inline_admin_formset.formset.management_form }} <fieldset class="module {{ inline_admin_formset.classes }}"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2> {{ inline_admin_formset.formset.non_form_errors }} <table> <thead><tr> <th class="original"></th> {% for field in inline_admin_formset.fields %} {% if not field.widget.is_hidden %} <th{% if field.required %} class="required"{% endif %}>{{ field.label|capfirst }} {% if field.help_text %}&nbsp;<img src="{% static "admin/img/icon-unknown.svg" %}" class="help help-tooltip" width="10" height="10" alt="({{ field.help_text|striptags }})" title="{{ field.help_text|striptags }}">{% endif %} </th> {% endif %} {% endfor %} {% if inline_admin_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %} </tr></thead> <tbody> {% for inline_admin_form in inline_admin_formset %} {% if inline_admin_form.form.non_field_errors %} <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr> {% endif %} <tr class="form-row {% cycle "row1" "row2" %} … -
Django: javascript variable intermittently not being passed (variable undefined after assignment)
I'm hoping someone can spot what I'm doing wrong here. I have a dropdown list which triggers a javascript function to change the language. It works exactly as expected maybe 19/20 times, but every so often, one variable (always the same one) is undefined after assignment. I've trapped the code with an alert statement to make sure the HTML is rendered ok on the page - it is. I flip between two languages over and over, fine then suddenly, with no changes, I get the variable undefined error. In the Django-rendered HTML: <div class="collapse navbar-collapse flex-grow-0 float-right" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <img src="/static/ca.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Català </a> <div class="dropdown-menu" role="menu" id="language-list" aria-labelledby="navbarDropdownMenuLink"> <input type="hidden" name="csrfmiddlewaretoken" value="..."> <link rel="alternate" hreflang="es" href="http://localhost:8000/es/noticias/el_segundo_elemento" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="es" data-next="/es/noticias/el_segundo_elemento"> <img src="/static/es.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Español </a> <link rel="alternate" hreflang="en" href="http://localhost:8000/en/news/the_second_item" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="en" data-next="/en/news/the_second_item"> <img src="/static/en.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;English </a> <link rel="alternate" hreflang="fr" href="http://localhost:8000/fr/nouvelles/le_deuxieme_element" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="fr" data-next="/fr/nouvelles/le_deuxieme_element"> <img src="/static/fr.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Français </a> </div> </li> </ul> </div> The data-next tag is the one giving me the … -
Django REST Framework: Type Error When Trying To Update Using Nested Serializer
I am trying to use a nested serializer in Django Rest Framework. I basically want to update my instance in a single shot. When I send my response, it throws an error saying- save() got an unexpected keyword argument 'id'. I tried popping "id" but then it just repeats the same error with a different attribute. Here is my model: models.py class Language(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) serializers.py from ..models import Language, Lead, Genre, Business from rest_framework import serializers class LanguageSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Language fields = "__all__" class LeadSerializer(serializers.ModelSerializer): id = serializers.IntegerField() language_id = LanguageSerializer(many=True) class Meta: model = Lead fields = "__all__" def update(self, instance, validated_data): language_ids = [item['id'] for item in validated_data['language_id']] for language in instance.language_id.all(): if language.id not in language_ids: language.delete() for item in validated_data['language_id']: if item.get("id", None) is not None: lang = Language.objects.get(id=item["id"]) lang.save(**item) #This throws an error else: lang = Language.objects.create(**item) instance.language_id.add(lang) validated_data.pop("language_id") validated_data.pop("id") instance.save() return instance -
Django template simple {% block %} and {% extends '' %}
So guys, i'm trying basics from django and {% block %} statement seems not to work for some reason... this is my forms.html: <body> {% include "homepage/navbar.html" %} <div class="container-fluid"> {% block content %} {% endblock content %} </div> {% include "homepage/footer.html" %} </body> and this is my form_model.html: {% extends 'forms/forms.html' %} {% block content %} <h1>Hello world</h1> {% endblock content %} Settings.py in templates: 'DIRS': [BASE_DIR, '/homepage/' '/boards/' '/forms/' ], -
Integrity & NotNull errors for null value in DateField column, but null=True, and blank=True
I'm currently using a Django backend, with a React/Redux frontend. When I try to add a new "Day" to my database, I get: psycopg2.errors.NotNullViolation: null value in column "day_date" ... violates not-null constraint DETAIL: Failing row contains (2, null, Tu). django.db.utils.IntegrityError: null value in column "day_date" ... violates not-null constraint DETAIL: Failing row contains (2, null, Tu). This shouldn't be an issue because in my model, day_date is a DateField: class Day(models.Model): day_id = models.AutoField(primary_key=True) day_date = models.DateField(blank=True, null=True) day_str = models.CharField(max_length=30, blank=True) class Meta: db_constraints = { 'CHK_DayNotNull': 'CHECK (day_date IS NOT NULL OR day_str <> "")' } I thought maybe it was an error with my constraint, but when I deleted the constraint I get the same error. I tried playing with the inputs of the day_date field in the model; I tried all the combinations and get the same error which makes me think something is wrong with how my database is being updated. I'm using PostgreSQL for my database. I tried clearing cache. deleting all my migrations, and then running, python3 manage.py flush python3 manage.py makemigrations python3 manage.py migrate but I'm still getting the exact same error. -
How to add name attribute in dynamically generated HTML form?
I am generating a dynamic input field in my form using javascript in Django template. But on submitting the form in Django, I need the name attribute in every input field. Like this: For input field with From Area label I need a name to be something like this: fromArea-1 Similarly, For input field with To Area label I need a name to be something like this: toArea-1 Any help would be beneficial. Here is my code: function addRow() { const div = document.createElement('div'); div.className = 'card'; div.innerHTML = ` <div class="card-body"> <div class="form-group"> <label>From Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br/> <label>To Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br> <label>Distance</label> <input class="form-control" type="text"></input> </div> </div> `; document.getElementById('permission-wrapper').appendChild(div); } <div class="mt-4 ml-4 mr-4"> <form class="mt-4" method="post"> <div id="permission-wrapper"> <div class="card mb-2"> <div class="card-body"> <div class="form-group"> <label>From Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br/> <label>To Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br> <label>Distance</label> <input class="form-control" type="text"></input> </div> </div> </div> </div> <br/> <button class="btn btn-primary float-right" onClick="addRow()">Add</button> <button class="btn btn-success" type="submit">Submit</button> </form> </div> -
Herko collect static question. How do I make it run python3 manage.py collect static instead of python manage.py collect static
I have python3 installed on my virtual env, but the default python version on my laptop is 2. I run python3 ... for everything I do. Heroku runs python manage.py collectstatic, so it does not work, as my default version is python2. I want it to run python3 manage.py collectstatic. Is there a way I can do this? Also is there a way I can collecstatic files and disable heroku from doing it, so that I can manually get the static files ready for production? Please help me out here, I am very confused. -
I can access fatimatestpro.pythonanywhere.com but not fatimatestpro.pythonanywhere.com/help/
I am working on PythonAnywhere and made my first project. I am trying to access many views (HTML pages) from my views.py. Here is my project tree: emailpro --emailpro ----url.py --emailapp ----urls.py ----views.py --templates ----emailapp ------index.html ------help.html Code inside my emailpro>emailpro>urls.py is from django.conf.urls import url, include from django.contrib import admin #from emailapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), #url(r'^$', views.index, name='index'), url('', include('emailapp.urls')), ] Code inside my emailpro>emailapp>urls.py is: from django.conf.urls import url from emailapp import views urlpatterns=[ url('', views.index, name='index'), url(r'^help/$', views.help, name='help'), ] Code inside my emailpro>emailapp>views.py is from django.shortcuts import render #from django.http import HttpResponse # Create your views here. def index(request): my_dict={'insert_me': "Hi I am index coming from views.py"} return render(request, 'emailapp/index.html', context=my_dict) def help(request): help_dict={'help_insert': "HELP PAGE"} return render(request, 'emailapp/help.html', context=help_dict) My emailpro>templates>emailapp>index.html is <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Index</title> </head> <body> <h1>Index page</h1> {{ insert_me }} </body> </html> Code inside my emailpro>templates>emailapp>help.html is <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> Help </title> </head> <body> <h1>This is my Help HTML</h1> {{ help_insert }} </body> </html> Now when I run my site and access http://fatimatestpro.pythonanywhere.com/, it shows me my index.html page which means it is going inside my emailpro>emailapp>urls.py … -
Update Django Model
How to i update a certain value in the database? class Userdata(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1) is_voted = models.BooleanField(default=False) def __str__(self):return self.user.username class Voting(models.Model): name = models.CharField(max_length=50) faculty = models.ForeignKey(Fakultas, on_delete=models.CASCADE, default=1) pic = models.CharField(max_length=50) text = models.TextField() voters = models.IntegerField() def __str__(self): return self.name My Views : def voted(response): if response.method == 'POST': id = response.POST.get['idcalon'] user = Userdata.objects.get() #get the username calon2 = Voting.objects.get() #get user selection in html user.is_voted = True calon2.voters +=1 user.save(['is_voted']) calon2.save(['voters']) I'm trying to grab the user's name and then when update the user's is_voted value to True when triggered. Then, I wanted to grab my Voting model by id, for example, I wanted to edit id = 1 So how do I do it? I've been trying to understand the documentation, but still have 0 idea how to do it. Thank you -
Docker Django database connection error: UNICODE Using encoding ASCII 'UTF-8' and UNICODE 'UTF-16LE'
I'm running into an issue with docker and django when trying to connect to a remote database (on a different server). Using Python 3.4 and django 1.9.7. I can perform runserver just fine when running locally, and can connect using tsql or pyodbc.connect() in the docker container. However, when performing runserver on the docker container for the project, here is the error I receive: [ODBC][14][1604961520.418108][SQLDriverConnectW.c][290] Entry: Connection = 0x7f48618ecba0 Window Hdl = (nil) Str In = [UID={{UID}};PWD={{password}};DRIVER=FreeTDS;SERVER={{serverIP}};DATABASE={{databaseName}};unicode_results=True;][length = 110] Str Out = (nil) Str Out Max = 0 Str Out Ptr = (nil) Completion = 0 UNICODE Using encoding ASCII 'UTF-8' and UNICODE 'UTF-16LE' This error is mentioned on https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/known-issues-in-this-version-of-the-driver?view=sql-server-ver15 with the comment: There is more than one Driver Manager installed and your application is using the wrong one, or the Driver Manager was not built correctly. I have tried everything I can think of and feel like I'm overlooking something really obvious here, but I've had no luck figuring out this error, or if I even have more than one driver being used (and if so how to fix that). Here are other related setup files, perhaps someone will spot something or have an idea. Any help is greatly … -
Django Rest API ManyToMany on exsiting Database not working
I have a database with one table for recipes without the ingredients and one table with the ingredients each with a recipe id to reference each other. Now I don't know how to refer to the recipe id column, because at the moment (I build a rest API) it returns no ingredients. My models.py class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. ingredients = models.ManyToManyField(Ingredients) class Meta: managed = True db_table = 'Recipes' If there is no issue it has to be somewhere on the api part: Serializer: class FullRecipeSerializer(serializers.ModelSerializer): ingredients = serializers.PrimaryKeyRelatedField(queryset=Ingredients.objects.all()) class Meta: model = Recipe fields = ['title','ingredients'] ViewSet: class FullRecipesView(generics.ListCreateAPIView): serializer_class = FullRecipeSerializer permission_classes = [ permissions.AllowAny ] queryset = Recipe.objects.all() I hope you understand my … -
How to setup a socket server on django?
how can i use django to create a socket server that could be able to call procedures on a python client from the server ? it has to be launched on init, so when i just add a server like this one : https://pypi.org/project/aiohttp-json-rpc/ in the __init__.py it starts the RPC server, and block django, not allowing the HTTP server to start -
Block title renders but Block content does not, on the same page
The {% block title %} is being rendered, so Test is displayed on the page, and changes when I change whatever is in there. However, no matter what I do with {% block content %}, the content does not display on the page. I would have assumed that either both of them, or none of them would display. Why would only one block type display and not the other? <!-- templates/registration/password_reset_complete.html --> {% extends 'base.html' %} {% block title %} Test {% endblock %} {% block content %} <div id="content" class="colM"> <p>We've emailed a new password to the e-mail address you submitted. You should be receiving it shortly.</p> <p> You can log in now on the <a href="{% url 'login' %}">log in page</a>.</p> <h1>Password reset sent</h1> <br class="clear"> </div> {% endblock %} -
Error 'int' object has no attribute 'get'
This one is really confusing me. I am reading a excel file into my python script. When I run the script with about 5 rows it runs perfectly. When I run it with 10 rows it gives me this error. I looked the error up and it seems the solution is to use HttpResponse. I am already using the HttpResponse. io = BytesIO() writer = ExcelWriter(io) data.to_excel(writer, 'Results', index=False) data2.to_excel(writer, 'Suggestions', index=False) writer.save() rFile = io.getvalue() response = HttpResponse(rFile ,content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename={FilePath}.xlsx' return response return render(request, 'home.html') Here is the error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/page_objects/ Django Version: 3.1.2 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback (most recent call last): File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /page_objects/ Exception Value: 'int' object has no attribute 'get' If you think any other part of my code would be useful to see let me know and I will edit it in. -
Django: grid of 5 by 5 elements on desktop on 2/3 of the width screen
I need to make a grid of images of 5 by 5 (total 25) in desktop mode, but only occupaying 2/3 of the width of the screen (this is why I first create a col-md-8) on top of evertything. However, my grid is showing 3 images in the first row, 2 images in the second row, and 3 in the last element. I thought it was because of the size of the images, but made them smaller and the layout is still the same. So I think problem is in my code: DB only has 8 elements at the moment but grid will show 25 (5 by 5) images. Code: <div class="row"> <div class="col-md-8"> <div class="row"> {% for product in products %} <div class="col-sm-4"> <img src="https://picsum.photos/100/110" style="margin-right: 5%; margin-top: 5%;"> </div> {% if forloop.counter|divisibleby:5 %} </div> <div class="row"> {% endif %} {% endfor %} </div> </div> <div class="col-md-4"></div> </div> -
Celery task can not call Channels consumer via channel_layer.send
I've been setting up a websocket for a fairly simple application. I wrote a JsonWebsocketConsumer as well as some celery tasks in order to perform some longer-running tasks (db accesses). Everything is working without error but my consumers are never getting called. Any ideas? consumers.py class NetworkCompConsumer(JsonWebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive_json(self, content): include = content['include'] # exclude = content['exclude'] # Reduce Dimensions of Inputs to 2, Just in Case User uploads 3D # Geojson wkb_w = WKBWriter() wkb_w.outdim = 2 include = GEOSGeometry(json.dumps(include)) include = GEOSGeometry(wkb_w.write_hex(include)) # if exclude is not None: # exclude = GEOSGeometry(json.dumps(exclude)) # exclude = GEOSGeometry(wkb_w.write_hex(include)) print("firing tasks") genPolySize.delay(include.json, None, self.channel_name) genBuildingCount.delay(include.json, None, self.channel_name) self.send_json({ "hello world": "Hi!!!" }) def polygon_area(self, event): print("poly area consumer called!!") self.send_json( {"area": event['value']} ) def building_count(self, event): print("building count consumer called!!") self.send_json( {"buildingCount": event['value']} ) tasks.py def sync_send(channelName, consumer, value): channel_layer = get_channel_layer() print(channel_layer) async_to_sync(channel_layer.send)( channelName, { "type": consumer, "value": value, } ) @shared_task def genBuildingCount(include, exclude, channelName): query_skeleton = building_count_skeleton query_skeleton = getQueryTemplate(query_skeleton, exclude is not None, False) with connections['gis_data'].cursor() as cursor: cursor.execute( query_skeleton, [include, exclude] if exclude is not None else [include]) results = cursor.fetchone() buildingCount = results[0] sync_send(channelName, "building.count", buildingCount) print("successfully completed … -
Django admin field. get value in relation field
Models.py class Student(models.Model): first_name = models.CharField(max_length=255) class Room(models.Model): room_name = models.CharField(max_length=20) student = models.OneToOneField(Student, on_delete=models.CASCADE) Admin.py class RoomAdmin(admin.ModelAdmin): model = Room fields = ('room_name', 'student__first_name',) I need to appear field "first_name" on add room admin page. So i set admin follow source code, I recived errors. ERRORS: <class 'building.admin.RoomAdmin'>: (admin.E108) The value of 'fields[1]' refers to 'student__first_name', which is not a callable, an attribute of 'RoomAdmin', or an attribute or method on 'building.Room'. Please guide or suggess for this thank you :) -
Django set ModelForm ModelChoiceField initial value in UpdateView class
There are many related questions I checked on so before posting my own, but I still can't figure this out. Using Django 2.2.x. I want the owner field of my html form to initially display only 1 username and this username has to be the current event instance owner. Being a ModelChoiceField, the field on the html form is rendered as a dropdown. This dropdown for the time being contains all the app users, since the ModelChoiceField has queryset=User.objects.all() I tried to override the get_initial() method of my UpdateView but, afaict, this has no effect on the ModelChoiceField. I'm able to set all forms.CharField() initial values though. I tried also to override the __init__ method of my class EventForm(forms.ModelForm) without luck. forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ["customer", "owner", ...] # the helper block comes from crispy_forms extension. # It rules the form layout, allowing to specify css classes, fields order # and even adding custom buttons helper = FormHelper() helper.layout = Layout( Field('customer'), Field('owner'), ... Submit('submit', 'Update') ) customer = forms.CharField(disabled=True) owner = forms.ModelChoiceField(queryset=User.objects.all()) ... views.py class EventUpdateView(LoginRequiredMixin, UpdateView): """ this view renders the update form that allows service desk operators to update event status, … -
How can I navigate through different links in DJango
I know how to access different views in django but I want to put links in my pages and them navigate through. Is this possible. What I am saying is that instead of typing the url path myself in django, i want to put links in pages and then click on them to navigate from page to page. Is it possible? -
no python at "C:\Users\AccountName\AppData\Local\Programs\Python\Python38-32\python.exe" error in VsCode
I was running the Django project without any problems. Until I reinstalled Windows and then reinstalled vscode! Now that I am running the Django project, vscode shows the following error. please guide me -
Multiple forms in one django template
I have a django template that has 2 forms. Each form submits to different models, and each form has one field to populate. The two models are: Coverletter Snippits My page allows users to add content to the coverletter via form and click submit, which will populate the content field in the coverletter model. On the same html page / template, the user can add content to snippits via form and click submit, which will populate the body field in the snippit model. I am using 2 views: CoverLetterUpdateView, which uses django built in UpdateView SnippitCreateView, which uses django built in CreateView The problem I cannot get each form to populate their own models. They both only populate the coverletter model. I'm not sure what I am doing wrong and cannot seem to find an answer online. I've been stuck at this for a couple days now. I'm sure I am missing something obvious like naming the forms different, but I cannot seem to figure out how to solve this. Any guidance would be appreciated. -
How can I return additional data when using a raw query on a model using Django?
I am new to django and have a question in regards to db queries. I am currently using a raw query to get places within x radius of a given lat lng. My query is query = """SELECT id, (3959*acos(cos(radians(%2f)) *cos(radians(lat))*cos(radians(lng)-radians(%2f)) +sin(radians(%2f))*sin(radians(lat)))) AS distance FROM businesses_business WHERE approved > 0 HAVING distance < %2f ORDER BY %s LIMIT %d OFFSET %d;""" % ( float(lat), float(lng), float(lat), details['radius'], details['orderBy'], details['limit'], details['offset'] ) and I am serlializing the data using the following: queryset = Business.objects.raw(query) serialized_data = serializers.serialize('json', queryset) I get back the data which matches the Business model. However, I also want to receive back the distance which is calculated in the query. How could I do this so that the distance for each row is also returned? p.s. If there is a better way to do this then I'd love to hear about it :) -
Django: how to use AWS access key without revealing it in source code
I'm following tutorial from https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/hls-playback.html#how-hls-ex1 It works great! But the access key is visible to user in the source code. How can I go about hiding access key from the user using Django? Tutorial puts it visible in the source code: var options = { accessKeyId: $('#accessKeyId').val(), secretAccessKey: $('#secretAccessKey').val(), sessionToken: $('#sessionToken').val() || undefined, region: $('#region').val(), endpoint: $('#endpoint').val() || undefined } var kinesisVideo = new AWS.KinesisVideo(options); var kinesisVideoArchivedContent = new AWS.KinesisVideoArchivedMedia(options); I think I need to set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY variables in settings.py, but how can I use them without revealing them to the user? -
Django module tests: Failing to attach a non-anonimous user to a request
I am trying to test that my custom permissions in DRF work properly, so I need to imitate some requests made by users with different rights (the rights are stored as attributes in the db in a table linked to the default User table). I am using RequestFactory for setting the request user, but it doesn't seem to work properly, as it still sees the request user as AnonymousUser, and returns AttributeError when checking the permission. Here's an example of my testcase: class TestSingleClient(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create( username='admin', password='admin', first_name='Name', last_name='Surname', email='user@gmail.com', is_staff=True ) AccountProfile.objects.create( phone='8999999999', occupation='tst_occupation', user=self.user ) Client.objects.create( name='Client1', type=0) def test_get_single_client(self): client = Client.objects.get(name='Client1') request = self.factory.get('/system/clients/{}/'.format(client.id)) request.user = self.user response = ClientView.as_view()(request, id=client.id) client_data = Client.objects.get(id=client.id) serializer = ClientSerializer(client_data) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK) which results in: File "***/core/extra.py", line 10, in my_permissions_func roles = AccessRoles.objects.filter(user_groups=user.user_profile.group_id, can_read=True).\ AttributeError: 'AnonymousUser' object has no attribute 'user_profile' Any suggestions for fixing that? P.S. A similar topic was discussed here: Django RequestFactory doesn't store a User, which didn't bring me any closer to the answer. -
When using natural_keys in Django, how can I distinguish between creates & updates?
In Django, I often copy model fixtures from one database to another. My models use natural_keys (though I'm not sure that's relevant) during serialization. How can I ensure the instances that have been updated in one database are not inserted into the other database? Consider the following code: models.py: class AuthorManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Author(models.Model): objects = AuthorManager() name = models.CharField(max_length=100) def natural_key(self): return (self.name,) Now if I create an author called "William Shakespeare" and dump it to a fixture via python manage.py dumpdata --natural_keys I will wind up w/ the following sort of file: [ { "model": "myapp.author", "fields": { "name": "Wiliam Shakespeare" } } ] I can load that into another db and it will create a new Author named "William Shakespeare". But, if I rename that author to "Bill Shakespeare" in the original database and recreate the fixture and load it into the other database then it will create another new Author named "Bill Shakespeare" instead of update the existing Author's name. Any ideas on how to approach this?