Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to import data into Django
I am currently working on a project for scraping flight data from websites using python and storing that data in a database using Django. I was just wondering what is the best way to take the scraped data and import it into the Django models. thanks in advance for any help. -
How to fix 'TypeError: __init__() got an unexpected keyword argument 'sender''
I am trying to create a django model instance with a django-rest-framework serializer ModelSerializer class. This is my Serializer code: class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ['sender', 'chat_room', 'content', 'sending_date'] and this is my view when I try to make a model instance out of it: message_serializer = MessageSerializer(sender=request.user, chat_room=ChatRoom.objects.get( id=request.data['chat_room_id']), content=MessageContent(text=request.data['text'])) message = Message(message_serializer.data) However, when I run this code, I get TypeError: init() got an unexpected keyword argument 'sender' If I delete the sender argument I get TypeError: init() got an unexpected keyword argument 'chat_room' and so on. I checked if my ModelSerializer was making the right serializer fields with print(repr(MessageSerializer())) in the django python shell, and I got MessageSerializer(): sender = PrimaryKeyRelatedField(queryset=User.objects.all()) chat_room = PrimaryKeyRelatedField(queryset=ChatRoom.objects.all()) content = PrimaryKeyRelatedField(queryset=MessageContent.objects.all(), validators=[<UniqueValidator(queryset=Message.objects.all())>]) sending_date = DateTimeField(read_only=True) which means that my serializer has these fields (sender, chat_room, etc.) Why do I get this error and how do I fix this? Thank you for your time! -
Not a valid regular expression
I cannot understand why i'm getting this error: django.core.exceptions.ImproperlyConfigured: "^customers/(?P<pk>[0-9]+)$" is not a valid regular expression: unknown extension ?P& at position 12 Here is my code of the file urls.py from django.conf.urls import url from customers import views urlpatterns = [ url(r'^customers/$', views.customer_list), url(r'^customers/(?P&lt;pk&gt;[0-9]+)$', views.customer_detail), url(r'^customers/age/(?P&lt;age&gt;[0-9]+)/$', views.customer_list_age), ] -
Django: Passing arguments to class-based view
I'm trying to pass arguments to a class-based view in Django. I've tried the various methods explained on this page but I can't get any of them to work. Django class-based view: How do I pass additional parameters to the as_view method? For example I've tried this but it doesn't work. url(r'^$', YourView.as_view(), {'slug': 'hello_world'}, name='page_name') I'm using Django 2.2.3 and I thought maybe things have changed since those answers were posted, but it still mentions this method in the Django docs: https://docs.djangoproject.com/en/dev/topics/http/urls/#passing-extra-options-to-view-functions So what am I doing wrong? -
django select_related Cannot resolve keyword
I'm trying to optimize my ORM queries in django. I use connection.queries to view the queries that django generate for me. Assuming I have these models: class Template_folder(models.Model): tf_id = models.AutoField(primary_key=True) tf_foldername = models.TextField(max_length=100) tf_parent = models.IntegerField() tf_seq = models.IntegerField() tf_sorter = models.TextField() class Meta: db_table = 'template_folder' class Templateforein(models.Model): tp_id = models.AutoField(primary_key=True) tp_idfolder = models.ForeignKey(Template_folder, to_field='tf_id', db_column='tp_idfolder') tp_title = models.TextField(max_length=45) tp_contents = models.TextField() tp_created = models.DateTimeField(default=timezone.now) tp_updated = models.DateTimeField(default=timezone.now) tp_iduser = models.IntegerField() class Meta: db_table = 'template' So should I use: template = Templateforein.objects.select_related().filter(Q(tf_id=tp_idfolder) | Q(tf_parent=tp_idfolder)) I have to use the template_folder model. Error content: django.core.exceptions.FieldError: Cannot resolve keyword 'tf_id' into field. Choices are: tp_choice, tp_confolderid, tp_contents, tp_created, tp_flowid, tp_id, tp_idfolder, tp_idfolder_id, tp_iduser, tp_pagenum, tp_title, tp_updated I think you should use the template model. I should use the template_folder model. How do I hang a filter with template_folder? -
Django button update DB and reloads the page
I'm fairly new to Django. I have a need for a button/s on my home page acknowledge the tasks and refresh it. Once acknowledged I need the status in my task model updated I don't have a variable to pass, it's home page it just needs to get refreshed. I tried with the path in url patterns but I need to pass a variable. And whenninpass on the variable I land on the individual task page. Is there a way I can call the views myfunction straight from html page to do the DB update? -
Reverse_lazy To URL Where Bootstrap Modal is Launched From
I have a page where the user can launch a bootstrap modal to update information on that page. I am using a class based update view to accomplish that within the modal. I would like for the user to submit on the modal form and then have them remain on the same page as where they originally launched the modal from. I am struggling to do this, because technically you're never leaving that page in the first place due to the modal - any help? The modal is launched from the 'manifest' url and I would like to reverse back to that after submission of the modal. urls.py url(r'^manifest$', manifest, name='manifest'), url(r'^manifest_update/(?P<pk>\d+)$', views.ManifestUpdate.as_view(), name='manifest_update'), views.py class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') When I do the above, the bootstrap modal simply doesn't submit, because as I mentioned I technically haven't navigated away from the 'manifest' url (or so I think). Not sure how I can make this happen successfully. -
Data not filling in with Edit Profile form Django
I'm using the following line to fill in data into the form. form = EditProfileForm(request.POST, instance=request.user) However, no data fills into the form. I just get the empty form. Not sure what's going wrong. I have a profile html where the data from each user shows up, but the line above is not working on the edit page. The model is the default user model. Django version 2.2.3. #views.py def editprofile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): agree = form.save(commit=False) agree.save() args = {'form': form} else: form = EditProfileForm(request.POST) args = {'form': form} return render(request, 'profile_edit.html', {'form':form}) Here is my forms.py: class EditProfileForm(UserChangeForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': "form-control"})) last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': "form-control"})) email = forms.CharField(label= 'Email', widget=forms.EmailInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] def save(self, commit=True): user = super(EditProfileForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user -
How to chain select_related functions in Django?
I have the following tables in my database: class A(models.model): ... class B(models.model): a = models.ForeignKey(A) class C(models.model): b = models.ForeignKey(B) data = models.TextField(max_length=50) What I want to do is get the C object with a pk of 215, and select the related B object, and also select the related A object of the B object. Right now, what I am doing is this: c = Models.objects.select_related('b').select_related('a').get(pk=215) However, I get the following error: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'a'. Choices are: b Is this possible to actually get all 3 objects with just one database hit? Thanks for any answers. -
In Django, is it better to store complex chaining save methods in models, or in views?
Lets say I have models similar to something like this: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... def save(self, *args, **kwargs): super(Y, self).save(*args, **kwargs) self.x.do_something() self.x.save() class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Z, self).save(*args, **kwargs) self.y.do_something() self.y.save() In other words, if a Z object is saved, its referenced Y object is updated and saved, which in turn saves its referenced X object. Right now, as it clear from the code, the complex save process is stored entirely in the models module. In production, the save method of Z should be ideally made atomic. Anyway, my question is this: should this sort of logic be stored in views instead? Like there could be a view like so: @transaction.atomic def my_view(request, z_pk): z = Z.objects.select_related('y').select_related('x').get(pk=z_pk) z.save() y = z.y y.do_something() y.save() x = y.x x.do_something() x.save() ... Obviously, for the above scenario, the model module would be simplified into something like this: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) Which one of … -
Where I should to put the "firebase_admin.initialize_app" command in a django application?
I'm a beginner in this field. My question is basically, where do I need to put the following code Like in the settings.py archive or views.py? I'm using it in the views.py but I'm not sure where. Do I need to create a new .py archive? Also, I'm trying to add some information to the cloud firestore. import firebase_admin from firebase_admin import auth, credentials, db from firebase_admin import firestore cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': 'xxxxx', }) db = firestore.client() -
No 'Access-Control-Allow-Origin' header on the requested resource in Django
I have read relevant question and understand what is cors. I followed each step. Install pip install django-cors-headers Add MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'a9.core.access.middleware.AccessMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = ['corsheaders','otree'] And python3 manage.py migrate However, I still get the error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.1 Is there something I am missing to make it work correctly? -
Django authentication failed with error 'csrf token missing or incorrect' when logon from cellphone
I implemented custom authentication in my django app. I was able tto logon from several different devices: desktop, cellphone, etc. The problem is if I have a logged in session running from desktop, I will get the CSRF verification failed error on my cell. But not the other way around. I I already logged on in my cell phone, I do not have any problem logging on from my PC. Here is my login view def login_page(request): form = LoginForm(request.POST or None) context = { "form": form, 'namespace':'accounts', } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None # if redirect_path == '/': redirect_path = '/dashboard/' if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/") # return redirect("dashboard/") else: # Return an 'invalid login' error message. print("LOGIN FAIL: Someone is trying to login and failed!") print("LOGIN FAIL: Username: {} and password: {}".format(username, password)) return HttpResponse("invalid username or password") else: return render(request, "accounts/login.html", context) -
How to form a queryset from two fields(columns) of the same model(same object)?
I'm trying to form a query set to load into a select form. This queryset has values that come from 2 fields of the same model(same object) from another model. For example, I have a GameId(object) stored in my database with a slug = 1sunariatl. This game id has GameId.home = ari and GameId.visitor = atl. I want to create a new form (PlayForm) with a select field(driving) that lets the user choose between the home team and the visitor team. (Select field in form will show "atl" and "ari") How do I form a new queryset based on these specific field values of the same object? models.py class GameId(models.Model): week = models.CharField(max_length = 100) day = models.CharField(max_length = 100) home = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='home') visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='visitor') class Play(models.Model): driving = models.CharField(max_length = 100) forms.py class GameIdForm(forms.ModelForm): class Meta: model = GameId fields = [ 'day', 'week','home', 'visitor' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['home'].queryset = Team.objects.all() class PlayForm(forms.ModelForm): def __init__(self, round_list, *args, **kwargs): super(PlayForm, self).__init__(*args, **kwargs) self.fields['driving'].queryset = #insert code here class Meta: model = Play fields = [ 'driving' ] -
Is auth customization secure in django?
I've extended user model with o2o relationship model (UserProfile). I want to make logging in with email/password instead of username/password. So I customized the auth backend. Is logging in vulnerable with that way of authentication? from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmAuth(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None -
Problems with saving and showing data with using from multiple checkboxes
Oay, let's start from the beginning ... I create a blog in Django. And I want to create something like a "playlist" containing several related posts (I hope you will understand) . But I have problem because I don't know how to display all posts in this "playlist". What is more I don't even know if I save all data in correct way, so if something is wrong please help. models.py: class Queue(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ManyToManyField(Post) def __str__(self): return self.title forms.py: class QueueForm(BSModalForm): post = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=((x.id, x.title) for x in Post.objects.all())) class Meta: model = Queue fields = ['title', 'description', 'post'] views.py: class QueueCreateView(BSModalCreateView, LoginRequiredMixin): template_name = 'blog/queue_form.html' form_class = QueueForm def form_valid(self, form, **kwargs): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): reverse_user = self.request.user return reverse('profile', kwargs={'username': reverse_user}) html file: {% for queue in queues %} {{queue.title}} {{queue.post}} {% endfor %} -
Define & Use Custom renderer Django Rest Framework View
I'm trying to override a CSV renderer import for a django rest framework view. Here's how so: class CustomCSVRenderer(BaseCSVRenderer): def render(): do something def tablize(): do something I've defined the CustomCSVRenderer in the same python class views.py as the view in question: class MyView(ListAPIView, CustomMixinSet): renderer_classes = (CustomRenderer, JSONRenderer) When I try to debug this implementation, my pdb debugger never hits the CustomCSVRenderer and instead I get a response based on some underlying renderer used by django restframework. What could be the issue? How do I know what renderer django rest framework is using? -
Add a django like system to posts
I am attempting to add a like system so users can like a post. I am unsure how to do this at the moment, and need some suggestions on the way to approach this. I need a user to be able to like/dislike posts. And that the colour of a button changes depending on whether a user has liked a post or not. -
Python/Django and services as classes
Are there any conventions on how to implement services in Django? Coming from a Java background, we create services for business logic and we "inject" them wherever we need them. Not sure if I'm using python/django the wrong way, but I need to connect to a 3rd party API, so I'm using an api_service.py file to do that. The question is, I want to define this service as a class, and in Java, I can inject this class wherever I need it and it acts more or less like a singleton. Is there something like this I can use with Django or should I build the service as a singleton and get the instance somewhere or even have just separate functions and no classes? -
How to import model classes while using click cli
I want to create a command line interface for manage some of user-management actions inside a django project. But when I need to import my models, click errors: from .models import UserGroup ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package" I have tried replacing .models to my_app.models but it sends the same error. I'm using python 3.6 and django 2.2 and click 7.0. my models: class UserGroup(models.Model): pass class AccessRule(models.Model): pass and my click code is simple. its just: @click.command() def list_user_groups(): for user_group in UserGroup.objects.filter(): click.echo(user_group.title) if __name__ == '__main__': list_user_groups() I expect to use below command to get list of my user groups for now. $ python3 cli.py list-user-groups Admin Customer Seller -
Django-guardian: safe to delete GroupObjectPermission and UserObjectPermission tables if using direct foreign keys?
The docs of Django-guardian mention the option to use Direct foreign keys as a performance improvement suggestion. As the initial migrations that come with the app have similar models but with a Generic foreign key, I'm wondering if I can just remove the migrations from the package as they would just be two unnecessary tables, if I choose to go with the Direct FK approach. Is there a cleaner way of doing this? Are the migrations required for other functionality within the app or can I just remove the models and migrations and use Direct FK for all my models? -
applying tags to multiple models in wagtail
The Wagtail documentation on tagging states the net effect is a many-to-many relationship between your model and a tag class reserved for your model But what if you have multiple models that need to share the same tag class? Details: I'm building a Wagtail site where I've got two models (ModernPost and LegacyPost) that both need to be tagged with taggit. I also need a reverse-chron listing of all posts (i.e., both models), filterable by tag. I know how to generate the unfiltered listing, but the tag-filtered listing baffles me, because Wagtail's tagging recipe gives each model its own tag class, and I don't know how to construct a query that would, for example, return all ModernPosts and LegacyPosts tagged as "foo". It seems like the models would need to share a tag class for this to work. The taggit documentation mentions "GenericTaggedItemBase allows using the same tag for different kinds of objects" but swapping that class into the standard Wagtail recipe leads to errors -- apparently because modelcluster does not support GenericTaggedItemBase? So what's my best path forward? Am I thinking about this all wrong? -
Django user.save() fails on Column 'is_superuser' cannot be null
I am trying to update user password using this code: from django.contrib.auth.models import User u = User.objects.get(username='test') u.set_password('test') u.save() but it falis everytime on these errors (without long messages from whole error message): _mysql_connector.MySQLInterfaceError: Column 'is_superuser' cannot be null mysql.connector.errors.IntegrityError: 1048 (23000): Column 'is_superuser' cannot be null django.db.utils.IntegrityError: Column 'is_superuser' cannot be null AttributeError: 'NoneType' object has no attribute 'strip' I am confused because this code is from official site so error is probably somewhere between django and mysql. Thanks for advance -
Django REST giving a 403 forbidden on DELETE methods, but not POST
I am trying to delete an entry using an ajax call. when I am using the default 'delete' method from generics.DestroyAPIView, I am getting a 403 Forbidden, but if I add a post method, call the delete method immediately and change the ajax type to 'post' it works fine. Would anyone have an idea what causes this? Note that I overwrite the get_object function to get the object based on posted data. (could it be due to delete methods not allowing to post data? If so, why? And how would you pass the CSRF token??) ajax: $.ajax({ url: '{% url "account:api:post_details_delete" %}', type: 'delete', data: { csrfmiddlewaretoken: "{{ csrf_token }}", name: json.name, value: json.value } }); } url: path('post_details/delete/', PostDetailDeleteApiView.as_view(), name='post_details_delete'), view: class PostDetailDeleteApiView(generics.DestroyAPIView): serializer_class = PostDetailSerializer # the code below allows it to work if uncommented and type in ajax changed to 'post' # def post(self, request, *args, **kwargs): # return self.delete(request, *args, **kwargs) def get_object(self): """ Returns the post detail object to be deleted based on the name:value pair provided by the ajax call. """ data = self.request.data obj = Post_Detail.objects.filter( name=data.get('name', ''), value=data.get('value', '') ).filter( post__account__user=self.request.user ) if obj.exists(): return obj.get() else: raise Http404 serializer: class PostDetailSerializer(serializers.ModelSerializer): … -
django rest framework- serializers, read_only, and drf-nested-routers, how to set parent?
I have the following simple models for a todo list: class TodoList(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) class Todo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) todo_title = models.CharField(max_length=64) todo_body = models.TextField() completed = models.BooleanField(default=False) list = models.ForeignKey(TodoList, on_delete=models.CASCADE, related_name='messages') What I am trying to do is set up a nested route using drf-nested-routers. E.g.: /api/v1/todo-lists/ <- List Todo Lists /api/v1/todo-lists/{LIST_ID}/ <- CRUD a Todo list /api/v1/todo-lists/{LIST_ID}/todos/ <- List todos for a particular list /api/v1/todo-lists/{LIST_ID}/todos/{TODO_ID}/ <- CRUD for a particular todo I've got a Todo Serializer: class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'todo_title', 'todo_body', 'completed', 'list',) read_only_fields = ('id', 'list',) And a TodoByList Viewset: class TodoByListViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = TodoSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): return Todo.objects.filter(list_id=self.kwargs['todolist_pk']) def create(self, request, todolist_pk=None): todo_list = get_object_or_404(TodoList, pk=todolist_pk) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) The list view works great, however for create I am in a bit of a catch-22. The list parameter for my Todo model is required (rightfully so), and thus perform_create doesn't work since list is not set. But if I remove list from the read_only_fields in my serializer, .is_valid fails since I am not passing the list …