Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model load choices from a json file
I am writing a Django User model which contains a mobile_country_code field. This field needs to be populated from a list of ISD codes, pre-populated in a json file. What is the best pythonic way to do the same? Possible options: Using a model's __init__ method to create COUNTRIES_ISD_CODES Importing a library method, like: from library import import_countries_isd_codes class User(models.Model): mobile_country_code = models.CharField(choices=import_countries_isd_codes()) My current implementation, which is working: json_data/countries.json [ ... { "name": "Malaysia", "dial_code": "+60", "code": "MY" }, ... ] project/app/models.py import json, os class User(models.Model): with open(os.path.dirname(__file__)+'/json_data/countries.json') as f: countries_json = json.load(f) COUNTRIES_ISD_CODES = [(str(country["dial_code"]), str(country["name"])) for country in countries_json] mobile_country_code = models.CharField(choices=COUNTRIES_ISD_CODES, help_text="Country ISD code loaded from JSON file") -
Django v2+ regex for custom path converter to handle csv
Note: prior to posting I already searched for csv regex. The best regex I found for csv so far can be found in the answer here. I would like to create a custom path converter for handling a csv e.g. something like: register_converter(CSVConverter, 'csv') urlpatterns = [ ... path('csv/<csv:list_of_values>/', views.csv_view, name='csv_view'), ... ] where each value of list_of_values is a string that does not need to be wrapped in quotes e.g. http://localhost:8000/csv/value1,value2,value3/ I tried the following: class CSVConverter: # see https://stackoverflow.com/a/48806378/5623899 regex = "(?:,|\n|^)(\"(?:(?:\"\")*[^\"]*)*\"|[^\",\n]*|(?:\n|$))" def to_python(self, value): return value.split(',') def to_url(self, value): return ','.join(value) but this doesn't work... -
Django url No Activity matches the given query?
I'm trying to write a slug field so users can view my activity_detail page. I think I wrote the code right, but I'm getting 404 error with No Post matches the given query. Here is my code: my urls.py from django.urls import re_path from . views import activity_list, activity_detail, activity_index app_name = 'activity' urlpatterns = [ re_path(r'^$', activity_index, name='index'), re_path(r'^(?P<year>[0-9]{4})/$', activity_list, name='list'), re_path(r'^(?P<year>[0-9]{4})/(?P<slug>[\w-]+)/$', activity_detail, name='detail'), ] my views.py: def activity_detail(request, year, slug=None): activity = get_object_or_404(Activity, year=year, slug=slug) context = { 'activity': activity, } return render(request, "activity/detail.html", context) I'm planning to call my url addresses from the browser as follows: http://localhost/activity/ http://localhost/activity/2018/ http://localhost/activity/2018/myactivity -
AttributeError: 'Manager' object has no attribute 'normalize_email' in django-username-email package after moving to PostgreSQL
my django project worked well until I changed my database from SQLite to PostgreSQL. Then the whole mess started. I am solving the issues gradually one by one. Unfortunately, I encountered something that I have no idea how to solve. I am using the package django-username-email. Before moving to PostgreSQL it worked without any issues. Now while I try to sign up the user, I get an error: [01/Oct/2018 09:17:06] "GET /accounts/signup/ HTTP/1.1" 200 5530 Internal Server Error: /accounts/signup/ Traceback (most recent call last): File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/views/generic/edit.py", line 172, in post return super().post(request, *args, **kwargs) File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/views/generic/edit.py", line 141, in post if form.is_valid(): File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/forms/forms.py", line 179, in is_valid return self.is_bound and not self.errors File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/forms/forms.py", line 174, in errors self.full_clean() File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/forms/forms.py", line 378, in full_clean self._post_clean() File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 106, in _post_clean super()._post_clean() File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/forms/models.py", line 401, in _post_clean self.instance.full_clean(exclude=exclude, validate_unique=False) File "/Users/Kuba/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/db/models/base.py", line 1151, in full_clean self.clean() File … -
'NoneType' object is not iterable in specific object updates
def update(self, request, *args, **kwargs): feed_obj = self.get_feed_obj(request, kwargs.get('feed_id')) budget_list, goal_list = self.data_formating(request, feed_obj) FeedBudget.objects.filter(state=1, feed_id=feed_obj.id).update(state=-1) FeedBudgetGoal.objects.filter(state=1, feed_id=feed_obj.id).update(state=-1) for budget, goal in zip(budget_list, goal_list): budget_serializer = self.serializer_class(data=budget) goal_serializer = FeedBudgetGoalSerializer(data=goal) if budget_serializer.is_valid() and goal_serializer.is_valid(): budget_obj = budget_serializer.create(validated_data=budget) goal['budget'] = budget_obj.id goal_serializer = FeedBudgetGoalSerializer(data=goal) if goal_serializer.is_valid(): goal_serializer.perform_update(validated_data=goal) def perform_update(self, serializer): serializer.save() def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) I need to update my current feed and want to update only budget, but It keeps giving me the error that "nonetype" object is not iterable -
Django REST TestCase: How to retrieve a response queryset that wasn't assigned to an attribute?
For a view that extends a generic ListAPIView and returns a queryset by simply assigning a collection to the View queryset attribute, like so: class MyView(ListAPIView): queryset = MyModel.objects.all() How can the queryset be retrieved in the TestCase for this view? def test_my_view(self): request = self.factory.get('my/url') # self.factory was set in the setUp method response = MyView.as_view()(request) self.assertEqual(response.status_code, 200) # I'd like to now test the query set, something like # self.assertQuerysetEqual(response.queryset, []) I've found that on querysets that are assigned to an attribute, the way to retrieve the queryset is this: response.context['queryset_attribute_name'] But I'd like my view to act like a simple REST endpoint for the front end and not add the attribute name to it. This seems like such a simple thing to do, but I'm new to Django and just can't figure out how to do it and already wasted way too much time searching for it... -
Apache hosted application not providing cookies
I have a Django application hosted in Apache. The Application check's for any logged in session by accessing "user" cookie in document.cookies(js). if the same is not available .js file will redirect to SSO login page. Once the user enter the credentials "user" cookie gets generated and application shows welcome message by accessing the same. This was the workflow which was working when i hosted the app in IIS 8.5. Now i hosted the same in Apache and now i'm not getting the cookies from the redirect URL. Application is just showing csrftoken token. I have hosted the application in port 80 and i tried the same with 8000 also. PS: Redecoration is completely handled by .js file. Any suggestions? -
DRF: Nested serializers with depth > 1
I'm looking into "nested-nested" serializers, where there's a nested serializer nested in another one. It's a cooking service where a recipe has multiple directions, each having multiple ingredients. I set that up with foreign keys. Here are my models: class Category(models.Model): """Model representing a recipe category""" name = models.CharField(max_length=200, help_text="Enter a recipe category (e.g Baking)") def __str__(self): """String for representing the Model object.""" return self.name class Ingredient(models.Model): """Model representing an ingredient in a direction""" name = models.CharField(max_length=250, help_text="The ingredient's name") quantity = models.CharField(max_length=200, help_text="How much of this ingredient.") direction = models.ForeignKey("Direction", help_text="This ingredient's direction", on_delete=models.CASCADE, related_name='ingredients') def __str__(self): """String for representing this recipe ingredient""" return f'{self.quantity} {self.ingredient}' class Direction(models.Model): """Model representing a step in a recipe""" title=models.CharField(max_length=200) text=models.TextField(blank=True, help_text="Describe this step.") recipe=models.ForeignKey("Recipe", help_text="This direction's recipe", on_delete=models.CASCADE, related_name='directions') def __str__(self): """String for representing the Direction""" return self.title class Recipe(models.Model): """Model representing a recipe.""" title = models.CharField(max_length=200) notes = models.TextField(max_length=1000, help_text="Enter notes, reviews, ...") photos = models.ImageField(null=True, blank=True) category = models.ForeignKey(Category, help_text="This recipe's category", on_delete=models.CASCADE, related_name='recipes') def __str__(self): """String for representing the Model object.""" return self.title def get_absolute_url(self): """Returns the url to access a detail record for this recipe.""" I read the docs and thought I could just use a nested serializer … -
Django - get latest object in each relation
Let's assume I have a Product model in my project: class Product(models.Model): price = models.IntegerField() and I want to have some sort of statistics (let's say I want to keep track of how has the price changed over time) for it: class ProductStatistics(models.Model): created = models.DateTimeField(auto_add_now=True) statistics_value = models.IntegerField() product = models.ForeignKey(Product) @classmethod def create_for_product(cls, product_ids): statistics = [] products = Product.objects.filter(id__in=products_ids) for product in products: statistics.append( product=product statistics_value=product.price ) cls.objects.bulk_create(statistics) @classmethod def get_latest_by_products_ids(cls, product_ids): return None I have a problem with implementing get_latest_by_products_ids method. I want only latest statistic, so I can't do something like: @classmethod def get_latest_by_products_ids(cls, product_ids): return cls.objects.filter(product__id__in=product_ids) because this would return all statistics I have gathered through time. How can I limit the query to only most recent one for each Product? -
Django createview custom validation
I am using createview for creating few fields of a model. I want to provide custom validation to attributes in my form. I am not sure how to do it through the CreateView. I don't want to create a Modelform for it. Generally custom validation for the attributes is performed by clean_attr() method in forms. So, Is there any way to perform this in createview ? my createview class @method_decorator(never_cache, name='dispatch') class AppCreateView(CreateView): model = models.App fields = ['name', 'background', 'font', 'textcolor'] def get_context_data(self, *args, **kwargs): context = super(AppCreateView, self).get_context_data(*args, **kwargs) context['view'] = 'create' return context In the fields, I am excluding a fild called "date" (which has to be today). Is there any way to set the date attribute in CreateView ? Thanks -
How to autofill the ModelForm with data from database
I have this Model with X,Y and Z as unique_together fields , acting as a primary key. The object created will then have its data stored in sqlite3 . What I require now is, if one needs to make another object with same values , rather than creating a new object ,the user can click on duplicate button provided in the changelist view which will take him to the Model add form with X Y as pre-filled from the database and only Y field open to be modified. How should I proceed ? -
search results based on location (django)
I am creating a business listing app project. I want to display location-based search results. eg. I am a user. Right now, I am at the west street, Tucson, Arizona. I make a search query for the restaurants. The result should be all the restaurants on the west street, Tucson, Arizona first. I mean restaurant which is nearest to the user location should display first in the search results. Please give any suggestion, how can I create location-based search results in Django. Thank you -
Form not being submitted
It was all fine just an hour ago but now when I try to add data to form and save it is running the exception part Before the post method was called and the form used to save and redirect But I cannot figure out why the exception part is running. I haven't change anything In console it is giving "POST /forum/topics/9/reply HTTP/1.1" 200 523 class NewPostView(generic.CreateView): form_class = NewPostForm template_name = 'forum/new_post.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if 'pk' not in context: context['pk'] = self.kwargs['pk'] return context def post(self, request, *args, **kwargs): topic = get_object_or_404(Topic, pk=self.kwargs['pk']) form = self.get_form() try: if form.is_valid(): post = form.save(commit=False) post.topic = topic post.created_by = User.objects.get(pk=request.user.pk) post.save() return redirect('topic-detail', pk=topic.pk) except Exception as e: messages.warning(request, "Failed To Create. Error: {}".format(e)) messages.warning(request, "Failed To Create Check Errors") args = {'form': form, 'pk': self.kwargs['pk']} #print(args) return render(request, self.template_name, args) -
how to convert a dictionnary which contains an in memory model instance into a string using json.dumps
import json dict = {'username': u'Toto', 'staffTitle': u'Mr', 'staffName': u'Toto', 'company': <Company: Test1>, 'qualifications': [{u'dateObtained': u'2017-11-22', u'qualificationId': 1048,} convert_to_string = json.dumps (dict) sa_ = sanitize_data(conver_to_string) back_to_dict = json.loads(sa_) def sanitize_data(dirty_data): clean_data = re.sub('(<0x\w*>)|\s',"", dirty_data) return clean_data So what i'm trying to achieve something.To convert as dict into a string using json.dumps then use my made function to sanitize and remove non_ascii characters and convert it back to a dict and save it. Because ,there is an in memory instance ('company': ) part of the dict. I'm having an error, the dumps does not work. How can i sort out this and being able to convert this dict into string and process the data? Any ideas? -
Trouble with django-cors-header - ModuleNotFoundError: No module named 'corsheaders'
I'm trying to add the Django-Cors-Headers library to my Django REST Framework project, which is Dockerized. Running my project works fine without the library but after I add it by following the documentation on the django-cors-headers github - specifically: Install from pip: pip install django-cors-headers (Although in my case, since it's dockerized, I did:) docker-compose run --rm web pip install django-cors-headers and then add it to your installed apps: INSTALLED_APPS = ( ... 'corsheaders', ... ) You will also need to add a middleware class to listen in on responses: MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Okay, so knowing all of that, I then run: docker-compose up Which essentially just waits for postgres, migrates, and then runs the server. Here is my stack-trace: Traceback (most recent call last): File "./manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load … -
Web development using Python and Django with Sqlite3 (inbuilt db in Django)
I am building a web based Dashboard using Django framework with Sqlite3 database (inbuilt DB that comes in Django).I'm Using HTML, CSS for first end designs and plotly library for data visualization. I would like to know about the scalability of this project. My concern is since I'm using inbuilt db sqlite3, will it sustain if we dump millions of records into this db? What is the maximum size of data it can accommodate?. I don't want to compromise my data visualization library plotly with this. I am planning to use this dashboard project for dumping millions of records on a daily/weekly basis. Can I continue with this db or do I have to migrate to other db's like postgres or mysql? -
how to use locust for load testing a djnago application?
how to check the load test for a api call [i have tried with the following code and output on locust is like this][1] -
savingloan() got an unexpected keyword argument 'loanname'
I am trying to submit the form after entering the details but after submitting, it shows and error like unexpected arguments 'loanname' keywords in loanform(loanname = name, email = email, mobile = mobile, scheme = scheme, city = city, msg = msg) method. My Model.Py File class loanform(models.Model): loanname = models.CharField(max_length=50) email = models.CharField(max_length=30) mobile = models.CharField(max_length=15) scheme = models.CharField(max_length=20) city = models.CharField(max_length=20) msg = models.CharField(max_length=200) def __str__(self): return self.loanname My View.Py File def loan_form(request): print("Loan form is submitted successfully!") name = request.POST["name"] email = request.POST["email"] mobile = request.POST["mobile"] scheme = request.POST["scheme"] city = request.POST["city"] msg = request.POST["msg"] lnform = loanform(loanname = name, email = email, mobile = mobile, scheme = scheme, city = city, msg = msg) lnform.save() return render(request,'loanform.html') My Url.Py File path('loan_form/', views.loan_form, name='loan_form') -
Django api/signup not found
Created a user registration form for my React Django app and keep getting an error even before doing anything on the form. It keeps saying api/signup 404 (Not Found). I have added all necessary apps to my installed apps in settings. I have also added all necessary urls as well. For reference here are my urls.py urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/', include('articles.api.urls')), re_path('.*', TemplateView.as_view(template_name='index.html')) ] And my settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'c(s+3-(=_22lr86m)6km!kn&q9irg7fn$19=--wl*p=)k_bgl&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['djangoandreact.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'articles', 'rest_framework', 'corsheaders', 'rest_auth', 'rest_auth.registration', 'rest_framework.authtoken', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] 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', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'djangoroot.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djangoroot.wsgi.application' # Database # … -
GeoDjango - Switching the SRID of a models.PointField field gives makemigrations error
So I had the following model class modelEmp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) location = models.PointField(srid=4326,max_length=40, blank=True, null=True) objects = GeoManager() I wanted to change the srid to 3857. However after running makemigrations I got the error django.db.utils.DataError: Geometry SRID (4326) does not match column SRID (3857) So I thought that Django is just being Django so I removed all my migration files and removed the location column. As a result makemigrations ran fine. Then I added the location column again and changed the the SRID to 3857 and then after running makemigrations I get the error django.db.utils.ProgrammingError: column "location" of relation "Employee_modelemployee" already exists Any suggestions on how I can fix this ? -
Cannot get by ID Django rest
I'm very new to Django and Django rest but I'm currently running into problems getting detail views of anything that uses a UUID, rather than the built in PK. An example can be found in this repo https://github.com/agconti/cookiecutter-django-rest, where I'm unable to work out how to view a user by ID (because I just get a 404). Can anyone help explain why I'm getting a 404? -
Update User instance by form
I do not know why I cannot update the User instance by a form. I mean by updating: changing the value in the database and in the request The User model is not created by me but I use django.contrib.auth.models.User This is my code app/forms.py from django import forms from django.contrib.auth.models import User class ModificationForm(forms.ModelForm): class Meta: model = User fields = ['email'] app/views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from app.forms import ModificationForm @login_required def profil(request): if request.method == "POST": form = ModificationForm(data=request.POST, instance=request.user) if form.is_valid(): form.save() else: form = ModificationForm() return render(request, "profil.html", {'form':form}) profile.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Profil</title> </head> <body> <h1>Profil</h1> <a href='/deconnexion'> Logout </a> <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Enregistrer" /> </form> </body> </html> -
django allow_tags not working in changeview in sometimes
Django version:1.9.2 python version:2.7.5 my model: class User(models.Model): headimgurl = models.CharField(verbose_name=u"icon", default=None, null=True, max_length=512, blank=True) def head_img(self): default_img_url = "http://mat1.gtimg.com/bbs/life-admin/activity/assets/logo.png" html = u"<img style=\"height:50px; width:50px;\" src=\"%s\"/>" % (self.headimgurl or default_img_url) return html head_img.allow_tags = True head_img.short_description = u"icon" my admin: class UserAdmin(admin.ModelAdmin): fields = ( ('head_img', 'headimgurl',), ) readonly_fields = ("head_img", ) list_display = ('head_img', ) enter code here I run the program and visit the website, all the icon show in list view, but some icon not show in change view. All the icons show in list view. In change view the mokey icon was shown: But the cartoon boy icon not shown in change view: What is the problem? Why some icon shown in change view but others not shown? -
Django - Is it possible to do a queryset within Count()
I have the following models class Client(models.Model): ... class Request(models.Model): ... client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) completed = models.BooleanField() I want to get the count of all completed requests for a queryset of clients. The following statement gets me all the requests, but it does not check for whether the request is completed. clients = Client.objects.filter(...).annotate(Count('request')) What I want is this: clients = Client.objects.filter(...).annotate(Count(request__completed=True)) How do I achieve this? -
How to use Custom User Model for authentication Djoser - Django
Its not clear from the documentation, but I want to achieve 2 things: Use my custom user model which inherits from models.Model. It has a password field which stores password using sha1. I need to use model with that password field for authentication. Since, the tables were used as it is in the project earlier need to use those only. I need to use any token based authentication. Can someone please point to the correct direction. I read django-rest-framework documentation, it pointed out to use Djoser for custom user model. But I'm unable to figure this out. How.