Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save the first 10entries with a default value
Assuming we have an Article model with is_published BooleanField. How can I save the first 20entries with is_published value as True? -
Python/Django how to set model datetime field with html date field value
I want to assign values form a simple html form(I dont want to use Django model forms or widgets in this case). All of the fields work fine except the datetime one. Lets say the html form is as simple as this: <form action="{% url 'main:create' %}" method="post" class="row form"> {% csrf_token %} <div class="expense-block" id="expense-block-0" data-block="0"> <div class="col-md-2"> <div class="form-group"> <label for="id_name">Name:</label> <input type="text" name="name" class="form-control" required id="id_name"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="id_created_at">Date:</label> <input type="datetime-local" name="created_at" class="form-control" required id="id_created_at"> </div> </div> </div> <input type="submit"> </form> As you can see for the date input i am using type="datetime-local" because I want to select both date and time. The model is simple: class Expenses(models.Model): name = models.CharField(max_length=200) created_at = models.DateTimeField() However when i save model I get error: The Expenses could not be created because the data didn't validate. Now the reason I am getting this error is because the 'create_at' value that i get from the post looks like this: 2018-03-09T11:11 So the question is, is it possible with Python to format this date to a normal datetime object? If not, what else can I do in my case? -
Django createsuperuser error in console
I start new project with two app (customuser and client). In customuser I redefine default User model and in client make UserProfile with OneToOne field to User. Then I run makemigartions customuser makemigrations client migrate In this point all Ok Bun then I run createsuperuser The error is appear return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: client_profile.position_id customuser/models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User … -
Django AJAX call/url from template after dropdown change
Trying to learn/implement AJAX and in django url/router url(r'^recipe/AJAX/(?P<recipe_pk>[a-zA-Z0-9]+)/?', views.newRecipeAJAX, name='newRecipeAJAX'), in the template {% block script_inline %} $(function(){ $('#form-dropdown').change(function () { var recipe_pk = $(this).val(); {# This one doesn't know the recipe_pk yet, so it throws a NoReverseMatch error #} request_url = {% url 'recipes:newRecipeAJAX' recipe_pk=recipe_pk %}; {# This one will too, since it doesn't have the argument #} request_url = {% url 'recipes:newRecipeAJAX' %}; {# Tried to get a valid link, then JS remove it and add the correct pk, but it throws a JS console error of 'Uncaught SyntaxError: Invalid regular expression flags'#} request_url = "'' + {% url 'recipes:newRecipeAJAX' recipe_pk=1 %} + "'"; alert(requst_url) // AJAX Land }); }); {% endblock script_inline %} view def newRecipeAJAX(request, recipe_pk): if request.method == 'POST': return HttpResponseRedirect('/dashboard') # GET else: recipe_requested = get_object_or_404(Recipe, pk=recipe_pk) related_recipes = Recipe.related_recipes.all() return { 'recipe_requested': recipe_requested, 'related_recipes': related_recipes, } How do I properly have django tell me the url to send it to, so I can avoid hardcoding it, and how do I do it in JS, once its been served (like can i get the url with everything but the recipe_pk and then concat in JS later?) -
Override Django Base Widget
It is possible to modify the Django Base Widget <django.forms.widgets.Widget>? I want to add a new data attribute for every single field that I render in the front-end. Exemple: CharField(max_length=50) DecimalField(max_digits=50) # And then in the render I want to add attribute data-max-length=50 <input type="text" max-length="50"> For that I want to override the base Widget to generate others masks and validations using JQuery masks, based on my ModelField or FormField. -
django-urls browser preview error
Using the URLconf defined in WisdomPets.urls, Django tried these URL patterns, in this order: admin/ ^$ [name='home'] ^adoptions/(\d+)/ [name='pet_detail'] The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. when I run server there was a warning WARNINGS: ?: (2_0.W001) Your URL pattern '^$' [name='home'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^adoptions/(\d+)/' [name='pet_detail'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Here is the code.. from django.contrib import admin from django.urls import path from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.home, name='home'), path(r'^adoptions/(\d+)/', views.pet_detail, name='pet_detail'), ] -
Writing a test for a Django View get_context_data() method
I am writing a test for a View where I update context to pass additional information to the template. Problem In writing the test, I'm having trouble accessing context from the RequestFactory. Code View class PlanListView(HasBillingRightsMixin, ListView): """Show the Plans for user to select.""" headline = "Select a Plan" model = Plan template_name = "billing/plan_list.html" def get_context_data(self, *args, **kwargs): context = super(PlanListView, self).get_context_data(**kwargs) context.update({ "customer": self.get_customer() }) return context Test class TestPlanListView(BaseTestBilling): def setUp(self): super(TestPlanListView, self).setUp() request = self.factory.get('billing:plan_list') request.user = self.user request.company_uuid = self.user.company_uuid self.view = PlanListView() self.view.request = request self.response = PlanListView.as_view()(request) def test_get_context_data(self, **kwargs): context = super(self.view, self).get_context_data(**kwargs) context.update({"customer": self.view.get_customer()}) self.assertEqual( self.view.get_context_data(), context ) Question How can I test the view's get_context_data() method? -
I want to convert decimal numbers from western arabic (0,1,2,3,4,5,6) to eastern arabic(٠, ١, ٢, ٣))
Is there any package available in python library or any way that I can convert decimal numbers (99.3) to (٩ ٩ .٣ ) I can convert the simple integers to eastern Arabic but the issue is with decimal. -
Django: Get previous value in clean() method
I have a model CustomModel with an IntegerField. class CustomModel(models.Model): count = models.DateTimeField() When I create a new instance of CustomModel in the admin, I have to do validation, so I use the clean method and have access to the value with def clean(self): value = self.count ... My problem: When I change the instance of CustomModel, I only have access to the new, changed value but not to the original value. However, for my validation I have to compare the new value and the value before the instance got edited. I could not found a solution how to get access. Does somebody know? -
Django-url cmd server error
from django.contrib import admin from django.urls import path from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.home name='home'), path(r'^adoptions/(\d+)/', views.pet_detail, name='pet_detail'), ] this is my code when I run python manage.py runserver... It returns a syntax error.. saying third line in urlpatterns "name" error which is (name='home') here.. -
edit/update functionality on a page in django which also has ajax calls
Problem I want to provide edit functionality to user on a page which was created by him/her. This page also has few ajax calls. The main issue is how can I show the values as selected/marked which were previously chosen by the user and now while editing he can unselect those and choose new values if he wants? Details A teacher can make worksheet, which will be shared with other teachers and the creator of worksheet might need to edit that as per the feedback from others. Right now the worksheet creation flow is on two pages: First page to filter questions based on class, topic, difficulty etc. Second page to preview questions and put extra details like due_date, duration, sharing with others etc and save to database. views.py 1st page view def question_filter(request): if request.method == 'POST': request.session['question_pk'] = request.POST.getlist('question_pk') ## other values stored in request.session ## return HttpResponseRedirect(reverse('qapp:question_preview')) else: form = QuestionFilterForm() return render(request, 'apps/qapp/question_filter.html', {'form':form}) 2nd page view def question_preview_and_save_worksheet(request): question_pk_list = request.session['question_pk'] ## retrieve values stored in request.session ## if request.method=='GET': // some logic for get request // return render(request,'apps/qapp/question_preview.html',some_context}) elif request.method == 'POST': worksheet_data = {} worksheet_data['classroom'] = classroom [#other data required for worksheet creation#] … -
Build a webpage by Django ,funcitons dose not work
here's my html code: <span> <button onclick="indexOBJ.clear();return false;" class="resetButton">清空</button> </span> here's my js code: var indexOBJ={ clear: function () { $('#devSvnURL').val(''); $('#devVersion').val(''); $('#testExampleUrl').val(''); $('#testReportDemoUrl').val(''); $('#resultLocation').val(''); $('#username').val(''); $('#userpwd').val(''); $('#commitTextArea').val(''); $('#note').val(''); } }; function clearAA() { alert() } it works fine but when I change my html code to : <span> <button onclick="clearAA();return false;" class="resetButton">清空</button> </span> the function named clearAA() will never be called. I don't know why . PLZ tell me the reason. Thanks a lot Environment : Django 2.0.2 jquery-3.3.1.js -
Django: Minimum disqus comments integration example in development
I want to test disqus comments in development mode. I know that django-disqus is the package that helps integrate disqus comments but can't really figure out the way forward. I have a Post model in models.py as follows. class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=300, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL) body = models.TextField() publish = models.DateTimeField() In my templates I have, {% extends "blog/base.html" %} {% block title %} Blog | {{post.title}} {% endblock %} {% block content %} <p> <b>{{post.title}}</b> </p> <p> {{post.body}}</p> <p>Written by: {{ post.author }} on {{ post.publish }}</p> <hr> {% endblock %} {% block domready %} {% endblock %} So, my question is: Is it possible to integrate Disqus in development on my local machine? If yes, please provide reference/blog/hints so that I can integrate disqus comments in my blog. -
Visual Studio Code - Django Debug runserver doens't start
Im using Visual Studio Code under Debian. The debug works perfectly before changing python version due to virtualenv. { "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": true, // "pythonPath": "${config:python.pythonPath}", "pythonPath": "/usr/local/my_env/bin/python3", "program": "${workspaceFolder}/manage.py", "cwd": "${workspaceFolder}", "args": [ "runserver", "--noreload", "--nothreading" ], "env": { } , "envFile": "${workspaceFolder}/.env", "debugOptions": [ "RedirectOutput", "DjangoDebugging" ] }, You can see two rows in the config. The one commented was the working one poiting to Python 2.7 The new one point to absolute virtual-env python path (like suggested by googling). When it works, in the debug terminal I got: System check identified no issues (0 silenced). March 09, 2018 - 10:23:36 Django version 1.11, using settings 'conf.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Changing PythonVersion, the debug stop after: System check identified no issues (0 silenced). I've tried to set false on "stopOnEntry" but it doen't work. Where can I get some log to find out why runserver doesn't work? Obviously, if I start the server normally with: ./manage.py runserver it works. -
How can I tell Django not to cache when there is a an "Authorization" Header
I am using django with a DRF and JWT token to authenticate users. I am using caching to cache api response, but I do not want to do that for the logged in users. What I have in mind is something like using the from vary_on_headers which checks the request header Authorization and then not cache the response, but I cannot programmatically find a way to do this in python/django. Current way of doing caching is through a mixing class CacheMixin(viewsets.ViewSet): @method_decorator(cache_page(60*60)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
OpenWRT automate configuration over ssh
I'm trying to build simple web based wifi controller for OpenWRT devices using django framework and sqlite database. Unfortunately I can not find any information about this kind of projects (openWisp is too complex for me). For that instance, how can I build a script file and save it each time when user saves configuration? is it possible to have a template of file with variables for user input and then save it? Example: user going to web page, typing device SSID, new device password and hitting save should generate script file on server side, after that i would take that device ssh information from another data table, connect to it and pass the script over SCP protocol. Is it even possible? Maybe there are different ways that I am not familiar with. Would really appreciate any information and ideas on this topic! -
Django filter object for multiple args
The issue currently is filtering for all users that Are not the user Where model field == True If I remove the ".filter(model="True")" than the first requirement is met. How can I add more filters to the users? Current error message: FieldError at /explore/ Cannot resolve keyword 'model' into field. Choices are: date_joined, email, emailaddress, favorite, first_name, groups, id, images, is_active, is_staff, is_superuser, last_login, last_name, logentry, owner, password, profile, socialaccount, user_permissions, username, webhook I understand that the error means. However, I'm not sure how to implement it in the code. view.py def explore(request, pk=None): template_name = 've/cp/explore.html' users_list = User.objects.exclude(id=request.user.id).filter(model="True") paginator = Paginator(users_list, 16) # Show x per page page = request.GET.get('page') users = paginator.get_page(page) try: favorite = Favorite.objects.get(current_user=request.user) favorites = favorite.users.all() except Favorite.DoesNotExist: favorites = None args = { 'favorites': favorites, 'users': users, } return render(request, template_name, args) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, null=True) model = models.BooleanField(default=False) ... -
Django - Call API url that has Param
for example I need to call this API: /v2/json/status/{flight}/{date} and i have follow this Example Code But how can i get my code to read param flight and date to get the response/data. -
How to access raw ForeignKey value directly in Django ORM and use it in search_fields?
Let's say I have these models: class First(models.Model): id = models.SlugField(primary_key=True) class Second(models.Model): foo = models.ForeignKey('First') This technically means that Second.foo is a SlugField that points to the primary key of First model. The question is how can I access that raw value in foo without referencing and working with First model? Bonus question: How to make this field searchable in Django Admin panel without pointing to a sub model field? So how to do something like this? @admin.register(Second) class SecondAdmin(admin.ModelAdmin): search_fields = ['foo_id',] Instead of this? @admin.register(Second) class SecondAdmin(admin.ModelAdmin): search_fields = ['foo__id',] -
Libraries and extensions to make editable, interactive graphics in Django web app?
I'm building a Django app and would like a library, extension or way to create interactive graphs- bar, line, pie charts aside, I need to be able to move some things within the graph and lock those changes to be implemented into my system. For example, in a line chart, I need to be able to move and shift some of those lines within an allowable area by mouse-point-click-drag and set it in a new place where it needs to be set- and its new position needs to be interpreted and stored by my app. What options are available for this? -
How to make some authors post in a blog
Good afternoon! Now I understand with something like a blog on django. But I do not understand how you can make it so that you can put not one author of the post, but two, three, four, etc. Thank you so much -
How does djangoproject.com do its deploy to prod? Should I package my django project to deploy it?
I know this isn't exactly a SO-style question, but I think it would be very instructive to know the answer. The source for djangoproject.com is very helpful for understanding a possible layout for a Django project. However, the lack of a setup.py file suggests that this project is not "packaged" to put it into production. I am not interested in any of "how to setup nginx", "which DB to use", "how to <insert detail of hosting>". What I am interested in knowing includes: How do they deploy the djangoproject.com part to their production servers? Do they just do a git pull on their box to get the files in place? Or an scp/rsync/ftp? Who/what executes this step? I'm guessing it is automated, but does it trigger based on tags? or off .tar.gz files placed in a special location? (Given there are no tags/releases and only one master branch in the github project I'm guessing that whatever makes it onto master gets deployed?) How to they manage rolling back if they need to? / Is it automated?(the actual details are not necessary, but the general info would be good) Should I package my applications for deployment or not? I have always … -
how to mention password field in serializer?
I have a custom user for authentication and want to create a serializer class for it my custom user's model is like this : class User (AbstractUser): bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) image=models.FileField(null=True , blank=True) and my serializer is : class UserSerializer (serializers.ModelSerializer): class Meta: model = User fields = ('username' ,'email' ,'password' ,'firstname' , 'last name' ) how could I mention that the password field is a password and its content must be hashed? -
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'
In my Django project I have a user_manage app. I create a model named UserManage in my user_manage app's model.py: from django.db import models from django.contrib.auth.models import AbstractUser class UserManage(AbstractUser): username = models.CharField(max_length=12) Then I run: $ python3 manage.py makemigrations There comes the error: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserManage.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserManage.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserManage.user_permissions'. users_management.UserManage.groups: (fields.E304) Reverse accessor for 'UserManage.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'UserManage.groups' or 'User.groups'. users_management.UserManage.user_permissions: (fields.E304) Reverse accessor for 'UserManage.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'UserManage.user_permissions' or 'User.user_permissions'. -
AttributeError: 'tuple' object has no attribute 'permissions'. DJango groups
I did a bit of research and it seems that this is the correct code according to Django documentations but for some reason it returns. AttributeError: 'tuple' object has no attribute 'permissions'. DJango groups. Here is the code. admin_group = Group.objects.get_or_create(name='Admin') admin_group.permissions.add( add_token_permission, add_user_detail_permission, change_user_detail_permission, add_user_location_permission, ) admin_group.user_set.add(self.user) admin_group.save()