Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Change from using 'url' to 'path' in urls.py for this line (?P<hierarchy>.+)
I am using django2.0 and would like to convert the format of the urls.py from this to from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list , name='post_list'), url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name="detail"), url(r'^category/(?P<hierarchy>.+)/$', views.show_category, name='category'), ] something similar to this: from django.urls import path from . import views app_name='home' urlpatterns = [ path('', views.post_list, name='post_list'), path(<slug:slug>/, views.post_detail, name="detail"), path(???), ] How should I code the last line in the new format. Thank you for any help rendered. -
In what order is the save() called while saving a admin form in Django?
I have few models and in one of the models(say A) I have I have few foreign keys. For each foreign key I have an inline and a formset for each inline. I wanted to know in which order is the save/clean function is called. -
Django Rest Framework: Just get certain values of a ManyToMany relationship
I'm using Django Rest Framework to write my API. I want to write different values than the the id (specifically the uuid) into my serializer. Let me give you the basic setup first. I have a model called House which has amongst other values a pk and a uuid. And I have a second model called Citizen which also has a pk and a uuid. House and Citizen have a ManyToMany relationship with each other. I would like to have a serializer that just gives back an array of it's citizen. Here is the not working pseudo code that I tried (and failed): class HouseSerializer(serializers.ModelSerializer): address = AddressSerializer() citizen = serializers.UUIDField(source="citizen.uuid") class Meta: model = Table fields = [ "uuid", "address", "citizen", ... ] This serializer throws the error: AttributeError: Got AttributeError when attempting to get a value for field `citizen` on serializer `HouseListSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `House` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'uuid'. But on my model for the House I have explicitly citizen = models.ManyToManyField(Citizen). If I just don't specify any serializer and just leave citizen in the fields array, … -
Django translate annotated queryset into objects
I have three models, company, asset, and owner. Each asset is associated with a single company, and with a single CustomUser (each by foreign key). A user may own assets from multiple companies, and may own multiple assets from the same company. I need to know how many assets a user owns in each company in which they own at least one asset, this is done using the following property on the user model: @property def holdings(self): queryset = Company.objects.filter(asset__owner=self).values("name","crn").annotate(num_assets=Count(Case(When(asset__owner=self, then=1),output_field=IntegerField(),))) return queryset This works, and gives a queryset that looks like this (e.g.): <QuerySet [{'name': 'Com1', 'crn': '12334540', 'num_assets': 1}, {'name': "Com2", 'crn': '35873847', num_assets': 158}]> N.B 'crn' is the company registration number, so is effectively a public facing id number for the company. I am writing a form to allow users to transfer ownership of an asset. Since assets (from the user's point of view) are fungible, they need only specify the company from which they want to transfer the asset. Obviously, they should only be able to transfer an asset from a company in which they own at least one asset. The form: class ListingCreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): company_choices = kwargs.pop('company_choices') super().__init__(*args, **kwargs) self.fields['asset_company'].widget = forms.Select(choices=company_choices) … -
How to set user as staff in django by default
Im using default authentication in django and i want to set user as staff while new user is signing up. how do i set is_staff =True. -
the app does not display pictures in file.html - Django, Python
I have problem with inserting photos to my file.html in django-app. I tried to make many changes, but the picture is still not displayed. I will be grateful for any help. My html file {% extends 'base.html' %} {% block title %} <h2>Home templates</h2> {% endblock %} {% block content %} <div class="container"> {% for frond_photo in frond_photo_list %} {% if frond_photo.image %} <img src="{{frond_photo.image.url}}" class="img-responsive" /> {% endif %} {% endfor %} {% endblock %} views.py def frond_photo_list(request): queryset = Frond_Photo.objects.all() context = { "photos": queryset, } return render (request, "reviews/home.html", context) Models.py class Frond_Photo(models.Model): title = models.CharField(max_length=100) text = models.CharField(max_length=200) image = models.FileField(null=True, blank=True) urls.py (app) ... url(r'^home/', views.frond_photo_list, name='home'), ... admin.py class Frond_PhotoAdmin(admin.ModelAdmin): model = Frond_Photo admin.site.register(Frond_Photo) When my file looks like this (below) Everything is working properly. The pictures are displayed and I can adapt them to my needs. I think I had to forget something simple ... models.py class Wine(models.Model): name = models.CharField(max_length=200) image = models.FileField(null=True, blank=True) def average_rating(self): all_ratings = [list(map(lambda x: x.rating, self.review_set.all()))] return np.mean(all_ratings) def __unicode__(self): return self.name views.py def wine_list(request): wine_list = Wine.objects.order_by('-name') context = {'wine_list':wine_list} return render(request, 'reviews/wine_list.html', context) .html ... {% if wine_list %} {% for wine in wine_list … -
Will making a Django website public on github let others get the data in its database ? If so how to prevent it?
I have a locally made Django website and I hosted it on Heroku, at the same time I push changes to anathor github repo. I am using built in SQLlite to store data. Will other users be able to get the data that has been entered in the database from my repo ? If so how to prevent it from happening ? Solutions like adding files to .gitignore will also prevent pushing to Heroku. -
(Jquery, Ajax, Django, Cors, GET) No 'Access-Control-Allow-Origin' header - Cors Whitelist Ignored
I know this issue crops up a lot but I have yet to find a secure solution.(Note I have anonymised the urls below.) Problem: I have set up a Apache server running Django as a restful API on serverA on serverB I have a simple jquery AJAX GET request When the request is sent I get a "No 'Access-Control-Allow-Origin' header" Error but the origin is in the cors whitelist Notes: I have installed Cors Headers in Django as per https://pypi.org/project/django-cors-headers/ I have added serverB's url to CORS_ORIGIN_WHITELIST If I set CORS_ORIGIN_ALLOW_ALL = True it works fine (but insecure) Opening the url directly gives me the correct json response Code: Jquery on ServerB: getValueWithKey : function(table, key, callback){ uri = "serverA.com/{0}/{1}".format(table, key) $.ajax({ url: uri, type:"GET" crossDomain: true, dataType: 'json' }).done(function(data) { console.log(data); callback(data); }); }, Headers(As per chrome console): General: Request URL: http://serverA.com/tablename/keyname Request Method: GET Status Code: 200 OK Remote Address: serverA.com Referrer Policy: no-referrer-when-downgrade Response Headers: Content-Type: application/json Request Headers: !Provisional headers are shown Accept: application/json, text/javascript, */*; q=0.01 Origin: http://serverB.com Referer: http://serverB.com/test.html User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36 Thanks for the help! -
Token key name django-rest-auth
I'm using django-rest-auth==0.9.3 in my Django project (I'm making REST API for mobile application) and i get this problem: After authentication which is used on {base_url}/api/users/login/, API gives me the user's token in a JSON, but the key value of this token is 'key': { "key": "1eca799e88fd76bea3b33c53c33d58e4940bc7b8" } I want it to be "token". Does anyone know special properties for that or how to customize my TokenSerializer or any other solutions? -
Django - How to display table/rows of data dynamically from selected value from dropdown
It's me again, Django newbie. I am trying to display related rows/information through an html table from a value selected from dropdowm from an add py form. e.g. I got a form from employee model. I select employee 1 from an LOV which came from employee model. Employee 1 is fk for skill model. After selecting employee 1 from dropdown, a table will display below listing all the skills that employee 1 has, which is from skill model. These are what I got so far. I can't find any other useful references online that fits this specific requirement esp. how I wrote and structured my code so far. I am really lost. I am really on a stump. I don't know where and how to start. Snippets: employee_form.html {% extends 'skillsMatrixApp/base.html' %} {% block title %}Add Employee{% endblock %} {% block employee_active %}active{% endblock %} {% block body %} {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'skillsMatrixApp/form-template.html' %} <div class="form-group sub"> <div class="col-sm" style="text-align: right"> <button type="submit" formnovalidate class="btn btn-info">Save</button> <button type="submit" formnovalidate name="another" class="btn btn-info">Save and add another</button> <button type="submit" formnovalidate name="cancel" class="btn btn-danger">Cancel</button> </div> … -
Django's manage.py shows old commands
I am coding my own whl-package and after creating some new management-commands and deleting some old ones I was pretty happy with myself. Except after building my wheel-package (with setup.py bdist_wheel) and installing it on my test server (with pip install -U project-2.0b3-py2.py3-none-any.whl), I noticed that the help of manage.py still show the old commands. It will even try to run the old commands, so there is some old stuff there, but I was not quite sure why or how. I tried uninstalling instead of upgrading with pip uninstall project and listing installed packages with pip freeze to make sure it was all gone. Even tried to run the old commands, which would correctly fail when the package was not installed. Where do these old commands come from? -
I want to develop a app using Django but as of now do not want publish it online? Can I use it just like a desktop application?
Is it okay for me use it in browser. How make it run in the environment where there is no Django installed? Need to create exe for that? -
How do I count visits of page in Django? (through redirecting)
I've read through several other questions, yet what I was looking for wasn't there. I want to count how many times the user has gone through the ToPost/to_post.html section. Delayed redirecting works, but incrementing number of visits doesn't: post.visit_num += 1 I have a view whose template redirects after a second: def ToPost(request, pk): post = Post.objects.get(pk=pk) post.visit_num += 1 args = {'post': post} return render(request, 'posts/to_post.html', args) The pk is in the URL: url(r'^(?P<pk>\d+)/to-post/$', views.ToPost, name='to_post'), Template to_post.html: {% extends 'base.html' %} {% block head %} <meta http-equiv="refresh" content="1;url={% url 'home_space:view_post' pk=post.pk %}"> {% endblock %} {% block body %} <div class="container"> <h2> To post {{ post.pk }}... </h2> </div> {% endblock %} The model of Post: class Post(models.Model): title = models.CharField(max_length=128, verbose_name='Title') body = models.CharField(max_length=500, verbose_name='Description') user = models.ForeignKey(User, on_delete=models.CASCADE) visit_num = models.PositiveIntegerField(default=0) def __str__(self): return self.title -
redirect the link present on Homepage
I am developing a dashboard for an app by using Django. On the dashboard, there are hyperlinks to the days means when I click on a specific day, I will get the data that is present for that user and for that day. In the index.html : href="{% url 'mailpieces:get_day_mailpiece' question_id=user_id day=date %}">{{ day }} so get_day_mailpiece function takes two arguments and returns the data, but I am getting that data on the redirected page, I want that data of that day on the same page, on the dashboard. -
What should I do if Django doesn't send any email when I requested?
I was trying to make the custom password reset view for django.contrib.auth.views. I made it by myself (Of course, I see some tutorial articles.) But when I request the password reset form to the development server, It shows like this: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Hello From: <My email address> (Outlook) To: <My another email address> (GMail) Date: Wed, 22 Aug 2018 11:44:55 -0000 Message-ID: <20180822114455.3320.17387@Yeonhos-MacBook-Pro.local> I am testing Django EmailMessage Class But, It doesn't send anything to my address which is marked as My another email address. Can anyone help me? Why doesn't Django send this e-mail? -
django python: how to filter depending on the slug of pk of one app as foreign key in another app
I am trying to create an eCommerce site to learn python and django. I have created an app called category. This has 2 tables called Category and Subcategory. Category table's pk is a foreign key in Subcategory table. In category app's views.py, i have override the get_queryset in SubcategoryListView to show the subcategory items specific to the category on which the user clicks. So far everything is working fine. If from the home page, i click on Kids link, my url shows http://localhost:8000/category/kids/ I created another app called product(Which i am not sure if this is the correct way or should i use the category app for products too). This has a table called Product. Both Category table's pk and Subcategory table's pk are foreign keys in Product table. When i click on the subcategory link, i expect to show all the products that belong to that subcategory. I am not able to achieve this. Like in the kids page if i click on link Dresses, i want the url to be http://localhost:8000/category/kids/dresses-kids (dresses-kids is the slug for Dresses in kids subcategory) my product/views.py is as follows: class ProductListView(ListView): queryset = Product.objects.all() template_name = "product_list.html" def get_queryset(self): return Product.objects.filter(subcategory__slug__contains=self.kwargs['slug']) Is … -
django-allauth AUTH-PARAMS query
I have implemented a google login in my django application using django-allauth. Following is the social account provider setting in settings.py SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', 'hd': 'xxxxyyy.in', } }} When I try to login using using a gmail id (e.g: abc@gmail.com) then too google gives access to it in-spite of "hd" parameter being present. Can anyone please let me know what more parameters should I add so that google only gives access to domain present in "hd" parameter? -
Django Import-Export creates related objects two times (because of transaction)
EDIT I'm importing through GUI in Django-admin with Review page. class MyModel(Model): ... another_model = OneToOneField('AnotherModel'...) def save(...): created = not self.pk super().save(...) if created: if not self.another_model: self.another_model = AnotherModel.objects.create() self.save() class AnotherModel(Model): ... Every MyModel object has to have another_model related so I create it right after MyModel object is created. When I'm importing MyModel objects, the MyModel.another_model is being created 2 times. I think it's because the whole import process is wrapped in transaction so self.another_model returns None but I'm not sure. Do you know how to solve this? -
How to find first instance in django template
my object item_pics = [{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'}, {'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'}, {'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'} {'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'} {'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'} {'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'} {'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'} {'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'} {'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'} ] my template {% for pic in item_pics %} {% if pic.is_front %} <img src="{{ pic.url }}"> {% endif %} {% endfor %} The problem How can pick the first occurrance of pic.is_front == True and then stop the for loop Another problem If pic.is_fron = False for every picture of the item_pics i would like to pick the first pic of the item_pics -
DJANGO saving model types in a field as Generic Foreign Keys
Hey guys I want to create a new model that look something like this: ` class Note(models.Model): id = models.AutoField(primary_key=True) title = ... message = entity = ***************** ` I want the ******* - to be a foreingKey for any model - not object but model. I don't want entity to be multiple objects of the same model - just the model. So if the note comes from a Post entity should save as Post, if it comes from a Notification the foriengKey should be to Notification. Is there a way to do this in django or is my only option to just save the entity name as a String value? and filter for the Model name like. ` # Get all the notes for POST Model Note.objects.filter(entity="Post") ` -
Error {% trans %} in django template
I have a django template that I want to translate a value that is variable, since it is inside a for. The line is the following: {{item.title}} I want to translate what is inside that variable of the template. What I did was {{{% trans 'item.title'%}}} and then in the django.po file the following: #: templates/tittle.html:10 (line where the variable to be translated) msgid "Tittle" msgstr "Titulo" #: templates/tittle.html:10 msgid "Tittle2" msgstr "Titulo2" And so for all the case of for. This does not work for me So I ask what I'm doing wrong, or if there is some other way to do it. Thank you very much in advance. -
Django HttpResponse with redirect
I have a function that download a excel file in django: x= Y.objects.filter(pk__in=ids) response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Test.xlsx' test_data= WriteFile(x) response.write(test_data) return response My objective it's to appear a message after this: messages.success(request, 'Success!') But I need to redirect after the return response because if not the message not appear and only appear if I refresh the page manually. Any ideas how to make the message appear after download a file with the return response? -
Change default value on field after migration in django
I have app in django 1.11 and I made migration. Now I have items in admin panel with 'John' in first_name and 'Smith' in last_name field. I would like to change it. Can I do this after made python manage.py migrate? operations = [ migrations.AddField( model_name='downloadlink', name='company', field=models.CharField(default='Company', max_length=500), preserve_default=False, ), migrations.AddField( model_name='downloadlink', name='first_name', field=models.CharField(default='John', max_length=500), preserve_default=False, ), migrations.AddField( model_name='downloadlink', name='last_name', field=models.CharField(default='Smith', max_length=500), preserve_default=False, ), ] -
JIT not work on Django1.7 with PyPy2
I find out that Django 1.7 with pypy2 flush JIT coverage to zero randomly, using vmprof. I don't know why, but when I run the simple Django app, JIT coverage goes back to zero randomly. you can reproduce using https://github.com/gtlim/pypy-django. I run this code in docker container based on ubuntu16.04 -
Table merge error on sqlite3
Hi these are my tables music_name = char(username),userId(int) meaning = char(meaning),userid(int) i have used the join to merge this db = sqlite3.connect('db.sqlite3') cursor = db.cursor() cursor.execute('\n' 'INSERT INTO music_result SELECT username, meaning ,NULL\n' 'FROM music_name N JOIN music_sample1 T ON N.userid = T.userid \n') db.commit() when i tried to do this i got an error like sqlite3.IntegrityError: datatype mismatch please do help me to solve this error