Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django override CreateView with form_valid
I'm building a blog with Django that has a 'Create Post' page using CreateView. That requires three fields, an image, description, and author. I want the page to automatically assign the author to the logged-in user. the documentation says I should be using a form_valid method in the class I use to create a new post. I'm doing that, but... it's just not working. The actual error I'm getting is "IntegrityError at /new/ NOT NULL constraint failed: posts_post.author_id" ##models.py class Post(models.Model): image = models.ImageField() description = models.TextField(null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) And the views.py: ##views.py class PostCreate(LoginRequiredMixin, CreateView): model = Post fields = ['image', 'description', 'author'] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I've changed the PostCreate around a lot, by taking out the 'author' in the fields of the PostCreate class... but yeah. I don't get it, this is pretty much directly copying out of the docs and it's not working. -
Python3: Correct way of doing ORM using metaclass
The following source file created ORM Car to represent a database table. But Car.brand became None afterward. Due to TableMetaCls is setting to all the db fields to None. How do I persevered Car.brand to StringField()? What's the properly way of doing? This is similar to django ORM, please see https://github.com/django/django/blob/main/django/db/models/base.py#L477 for reference. class Field: pass class StringField(Field): pass class TableMetaCls(type): def __new__(cls, name, bases, attr): # backup field definition field_definitions = {} for x, y in attr.items(): if isinstance(y, Field): field_definitions[x] = y attr['field_definitions'] = field_definitions # set field val to null for x, y in attr.items(): if isinstance(y, Field): attr[x] = None return super(TableMetaCls, cls).__new__(cls, name, bases, attr) class Table(metaclass=TableMetaCls): def save(self): pass class Car(Table): brand = StringField() model = StringField() c = Car() c.brand = "BMW" print(Car.brand) -
Moving a Django app into production using Nginx and Gunicorn, there are no errors but the page doesn't show
I'm trying to setup an app on my Digital Ocean production server, I've followed these instructions, testing gunicorn and nginx,I could access the app in gunicorn and both services start fine with no errors logged. However when I go to the site it does not show anything. This is a subdomain of my main site. Mostly I'm looking to find a place to start troubleshooting this especially since everything looks fine. -
How to index Django models in ElasticSearch using elasticSearch_dsl (how to synchronise)?
im into a project for my master's degree so it's really urgent please, i have models in django containing foreignkeys and manytomany relations, i cant seem to find out how to index them in an elasticSearch document here's my Article model : manytomany fields are referencing a User model. class Article (models.Model): A_Id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) resume = models.CharField(max_length=1000) auteur = models.ManyToManyField(User,related_name="articlelist",blank=True) fichier = models.CharField(max_length=300,blank=True,null=True) urlfichier = models.CharField(max_length=300,blank=True,null=True) sauvegarde = models.ManyToManyField(User,related_name="sauvegardelist",blank=True) recommendationlist = models.ManyToManyField(User,related_name="recommendationlist",blank=True) recommendation = models.IntegerField(default=0) date_posted = models.DateField() if anyone could show me how a document for this model is written, it would really be lifesaving thank you. -
Django run migrations without models.py file
Have created some models in django app and also made the migrations files corresponding to it. Now, AFAIK at the time of deployment we can run the migrations even before the models.py file is pushed and deployed. Now additionally I have to provide initial data with the models so have created the data in migration files using migrations.RunPython(func) as an operation however in the func(apps, schema_editor): xyz_model = apps.get_model('app_name', 'xyz') we have used the model xyz so does it need to have the models.py file updated before running this migration? -
Can't import rest_framework in Django despite it being installed in my venv
Following tutorials and I cannot import rest_framework. I've activated my venv, run python and import rest_framework as suggested in many discussions on stack overflow, though no errors are thrown. I am fairly confident that djangorestframework is installed as it is in the environment directory: venv dir shows rest_framework installed I also restarted VS Code and my venv as suggested to no avail. The error I receive in VS Code: Import "rest_framework" could not be resolvedPylancereportMissingImports Settings.py: INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'EmployeeApp.apps.EmployeeappConfig', 'rest_framework', ] Immediately below INSTALLED_APPS: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } -
Setting a signed cookie for unit tests
In writing a unit test for my view, I am creating a request using the RequestFactory factory = RequestFactory() request = factory.get('/') Before I feed this request to my view for testing, I need to put a signed cookie in it (my view expects it). How can I do that? -
How to create a new user in Django using LDAP?
I'm using Django to create a REST API with LDAP. One of the endpoints gets a username (this is not the same username of the logged in user through IsAuthenticated). I want to check if that username exists in the system, even if he never logged-in. My current code was: try: user = User.objects.get(username=request.data['username']) except: return Response(data={"error": "User does not exist"}, status=status.HTTP_400_BAD_REQUEST) This of course does not work because the database contains users that have logged in at least once. How can I create the user if he does not exist? I know I can use User.objects.create but I want it to fetch the data from LDAP and not just to pass it the username. -
CSRF token issue when upgrading Django to version 4.*
I was using the Django version 3., but then upgraded it to Django version 4. (django==4.0.6). After logging to admin panel of Django project, it is said that CSRF token is invalid. I found this link in Django documentation: https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0 And tried to put such variable in settings.py ALLOWED_ORIGINS = ['https://', 'http://'] But it didn't help. What I am doing wrong? -
'utf-8' codec can't decode byte 0xb3 in position 10: invalid start byte
I am trying to import csv do django using function below in my View, but I am getting this error: 'utf-8' codec can't decode byte 0xb3 in position 10: invalid start byte I got this function for another project and there works fine as csv file is created from excel, so decoding utf-8 works. But here I have cvs directly from some webpage and decoding not working. I tried to use my function without method decode(), but then I am getting another error: TypeError at /sales, initial_value must be str or None, not bytes my function for import of csv file in Views.py: class SalesView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = "sales.html" form_class = UploadSalesData def test_func(self): return self.request.user.is_superuser def post(self, request, *args, **kwargs): form: UploadSalesData = UploadSalesData(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data["uploaded_file"] decoded_file = csv_file.read().decode('utf-8-sig') io_string = io.StringIO(decoded_file) reader = csv.DictReader(io_string, delimiter=",", skipinitialspace=True) record_count = 0 for line in reader: SalesData.create_from_csv_line(line=line) context = self.get_context_data() my_text = 'New data uploaded successfully.' messages.success(request, my_text) return render(request, self.template_name, context) else: return self.form_invalid(form) And my model: class SalesData(models.Model): date = models.DateField("Date", null=True, blank=True) product = models.CharField("Product", max_length=150, null=True, blank=True) sales = models.DecimalField("Sales", max_digits=10, decimal_places=2, null=True, blank=True) quantity = models.IntegerField("Quantity", null=True, blank=True) total = models.DecimalField("Total", … -
How to get an object by id in Django
I am trying to get a particular object from Django... When I use filter it returns more than one and I need just one and I don't want to my fields unique... Is there a way I can get object by id since id will be the only unique field by default in Django Sqlite -
Django App hosted on IIS suddenly starts to show "Object Moved" Page plus gibberish on 302 redirect
Screenshot It's an internal Django web app is hosted on a Windows Server 2008 with IIS 7.5, with Active Directory SSO enabled. Some links in the app response with a 302. For example, if the request is to go to myapp.com/change, the server will response with a 302 and redirect to myapp.com/change?user=5. In the browser, the url field shows the myapp.com/change?user=5, but the page looks like the picture above. If I hit enter on the url field, it goes to the correct page. I have tried to troubleshoot with DevTools. When clicking on /change, server responses with a 302 followed by a 200, nothing else. The 200 is blank, with no header or body, and says "Caution: request is not finished yet". Meanwhile, there's the spinning icon showing on the chrome tab meaning it's still loading. After a few minutes, the 200 times out and the spinning stops. Nothing in the code was changed in the last couple weeks, and two days ago people started reporting this issue. It didn't happen to me at first. I tried clearing cookie and cache, using different browsers and PCs, couldn't replicate it, then there's a scheduled PC restart yesterday, and I'm getting this … -
How to create an api request in python with apy key
I need to make an api call with api key in django ,this works in postman : i have tried it in python : header={"content-type": "application/json","Authorization": "X-Api-Key %s" %(self.api_key)} r = requests.post(email_meta_path,json=json,header=header) but i got authentication credintionals error , how can i create the postman request in python ? -
Django-Tailwind not working properly in Django
Django-Tailwind initially after setup works well with Django, but as soon as I start progressing with my project, it stops working!!! -
How can I Create Django Object after a Confirmation Form
I am working a Saving App where I want user to confirm Deposit before adding it in the database. I have tried all I could but after clicking on Confirm button in the Dailog Form the system redirects me back to deposit form displaying an error that Field Can Not be Empty. Model Code: class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Form Code: class CustomerDepositForm(forms.ModelForm): class Meta: model = Deposit fields = ['deposit_amount'] Views Code: def customer_deposit(request, id): context = {} form = CustomerDepositForm(request.POST or None) #Set Page Title page_title = "Customer Deposit" #Get Current Date current_date = datetime.now().date() #Get Current Month Name from Calendar current_month_name = calendar.month_name[date.today().month] try: #Check the Customer ID in DB customer = Customer.objects.get(id=id) #Customer Account acct = customer.account_number except Customer.DoesNotExist: messages.error(request, 'Customer Does Not Exist') return redirect('customer_create') else: #Get the Customer total deposit deposit = Deposit.objects.filter(customer_id = id).aggregate(total=Sum('deposit_amount') )['total'] or Decimal() if request.method == 'POST': #Deposit Form form = CustomerDepositForm(request.POST or None) if form.is_valid(): amount = form.cleaned_data['deposit_amount'] context.update( { 'deposit':deposit, 'page_title':page_title, 'customer':customer, 'current_date':current_date, 'current_month_name':current_month_name, 'form':form, 'amount':amount, 'acct':acct, … -
Download a file with axios that comes from an api Django
Im trying to download an xlsx that is generated in the backend in django but it seems that the credentials are not provided. axios.get request getPoResume = () => { axios.get( process.env.REACT_APP_IP + `/po/get_resume_pos/?client=${this.state.selectedClientPo}`, { headers: { "Authorization": "Token " + this.userToken }, }).then( function(response) { this.componentDidMount(); window.open(process.env.REACT_APP_IP + `/po/get_resume_pos/?client=${this.state.selectedClientPo}`) this.notify("tr", "success", "Resume downloaded!"); }.bind(this)).catch( function(error) { this.handleError(error, "getResume failed"); }.bind(this) ); }; and this is the answer when i try to download credentials error HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } -
Sublime Text 4: Support for Django autocompletion
I'm looking for a way to implement Django's autocompletion and hints. I'm aware that it's possible in Sublime Text 3. I'm looking at how to do it in the Sublime Text 4. For example, I'm unable to use Djanerio in Sublime package browser going: preferences -> Package Control: Djanerio. It doesn't find anything. -
Sign in with Google integration given origin not allowed on django
I am new to the google sign in api, and I am trying to create a simple app in which users sign up/sign in using google one tap sign in and then see their name and email. I was able to get google sign in working as a static webpage on my webserver(apache), but once I moved it to django(I am using django to store the emails in a database), I get the error: [GSI_LOGGER]: The given origin is not allowed for the given client ID. I have added the url tied to my webserver to the list of authorized js origins, hence it was working as a static page from that url, but it is not working when served through django. Is the origin different when it comes from django? Also, I know that there is a way to accomplish what I want using django social auth or django all auth, but I am looking to get the one tap sign in working using this code (heavily based on these docs from google: https://developers.google.com/identity/gsi/web/guides/migration , https://developers.google.com/identity/gsi/web/guides/handle-credential-responses-js-functions ) index.html: <script src="https://accounts.google.com/gsi/client" async defer></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <div id="g_id_onload" data-client_id=['my client id'] data-auto_select="true" data-login_uri=['the url which was added to js origins'] … -
Django parameters in URL
I am trying to write a delete function for my CRUD API with Python Rest Framework. In the delete I want to delete a specific item in the database, and I want it to be passed via link parameter like so: path/to/link/to/delete/post3. I did that in the url file: path("link/<int:link_pk>/", views.LinkView.as_view(), name="link_integration") Then, in the ApiView that is the code: @log_request_decorator def delete(self, request: Request, link_pk: int, **kwargs) -> JsonResponse: do_stuff() #print(social_integration_pk) return JsonResponse({}, status=204) And here is the code of the test that I am using to test it: link = "link/1/" factory = APIRequestFactory() request = factory.delete(link) view = LinkView.as_view() ---forced auth--- response = view(request) And I get this as output: TypeError: delete() missing 1 required positional argument: 'link_pk' Do someone know how to fix that? I need to have that parameter in order to do what I am supposed to. Maybe is something silly, but I don't know. If you can, please help me. Thank you -
Trying to revert from class based detail view to a function based view but I keep getting a NoReverseMatch error
I am creating a ticket project with some comment functionality and I know this sounds weird, since the tendency is usually to go from function based to class based. My problem lies in the fact that since the Detail View is designed to just be a Display View, trying to include a comment system on the same page proves to be rather difficult. Right now, I am simply trying to replicate the detail part of the ticket and I keep getting this error Traceback Traceback (most recent call last): File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\mikha\bug_env\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\mikha\bug_env\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 176, in render return self._render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 168, in _render return self.nodelist.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 977, in render return SafeString(''.join([ File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 978, in <listcomp> node.render_annotated(context) for node in self File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 938, in render_annotated return self.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\loader_tags.py", line 153, in render return compiled_parent._render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 168, in _render return self.nodelist.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 977, in render return SafeString(''.join([ … -
Docker and Nginx: port 80 and 403: address already in use
I have a VPS server runs on Ubuntu, I am running multiple Django projects with Nginx and Gunicorn. Recently, I decided to deploy my latest project with Docker. Everything is working, except the port 80. I can run the website on example.com:1330 but once I change it to 80, I get this error: err: ERROR: for nginx Cannot start service nginx: driver failed programming external connectivity on endpoint project-nginx (a4417bdb121b0afb1e57e11b68dd0eb74f770ed74f654a2722f4cd74121): Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use err: Encountered errors while bringing up the project. Here is a part of my: docker-compose.yml nginx: container_name: portfolio-nginx restart: unless-stopped build: ./nginx ports: - "80:80" # doesn't work - "1330:80" # works Nginx upstream project { server project-django:8000; } server { listen 80; server_name example.com; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { root /code; } location /media/ { root /code; } } I thought the problem is I have Nginx already running on port 80: sudo netstat -ntulp | grep 80 Once I kill the process the docker website works on port 80. But I lose the other Django projects that doesn't run on docker. Please, any idea? -
why function' object has no attribute 'user' showing up?
i tried to create 2 users in my project models.py class CustomUser(AbstractUser): user_type_choices = ((1, "Admin"), (2, "NotesUser")) user_type = models.CharField(max_length=10, choices=user_type_choices, default=1) class Admin(models.Model): user_id = models.OneToOneField(CustomUser, on_delete=models.CASCADE) class NotesUser(models.Model): user_id = models.OneToOneField(CustomUser, on_delete=models.CASCADE) @receiver(post_save, sender=CustomUser) def create_user_profile(sender, created, instance, **kwargs): if created: if instance.user_type == 1: Admin.objects.create(user_id=instance) if instance.user_type == 2: NotesUser.objects.create(user_id=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): if instance.user_type == 1: instance.admin.save() if instance.user_type == 2: instance.notesuser.save() and i wrote this middleware for checking user access LoginCheckMiddleWare.py from django.utils.deprecation import MiddlewareMixin from django.urls import reverse from django.http import HttpResponseRedirect, HttpResponse class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, view_func, request, view_args, view_kwargs): modulename=view_func.__module__ user = request.user if user.is_authenticated: if user.user_type == "1": if modulename == "todo_app.views" or modulename == "todo_app.AdminViews": pass else: return HttpResponseRedirect(reverse("admin_home")) elif user.user_type == "2": if modulename == "todo_app.UserViews" or modulename == "todo_app.views": pass else: return HttpResponseRedirect(reverse("user_home")) else: pass #return HttpResponseRedirect(reverse("log_in")) else: if request.path == reverse("log_in") or request.path == reverse("login_save") or modulename == "django.contrib.auth.views" or modulename == "todo_app.views": pass else: return HttpResponseRedirect(reverse("log_in")) i mentioned the middleware i created in app into settings.py file settings.py 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', 'todo_app.LoginCheckMiddleWare.LoginCheckMiddleWare', ] but an error is showing when i tried to access my login … -
How can I pass the values of the relevant row into the modal when a click event occurs on a table?
When a click event occurs on a table, I want to pass the values of the relevant row into the modal. I wrote a code like this, but the values of the top row are always passed into the modal. What I want to do is to show the values in the row I clicked in the modal. How can I provide this? my table codes here: <table class="table align-middle" id="customerTable"> <thead class="table-light"> <tr> <th class="sort" data-sort="name">Name Surname</th> <th class="sort" data-sort="company_name">Phone Number</th> <th class="sort" data-sort="leads_score">Note</th> <th class="sort" data-sort="phone">Status</th> <th class="sort" data-sort="location">Personal Name</th> <th class="sort" data-sort="tags">Data Name</th> <th class="sort" data-sort="action">Edit</th> </tr> </thead> <tbody class="list form-check-all"> {% for x in model %} <tr> <td class="table-namesurname">{{x.name}}</td> <td class="table-phonenumber">{{x.phonenumber}}</td> <td class="table-note">{{x.note}}</td> <td class="table-status">{{x.status}}</td> <td class="table-callname">{{x.callname}}</td> <td class="table-dataname">{{x.dataname}}</td> <td> <ul class="list-inline hstack gap-2 mb-0"> <li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Edit"> <a class="edit-item-btn" id="call-button" href="#showModal" data-bs-toggle="modal" data-id="{{x.id}}"><i class="ri-phone-line fs-16"></i></a> <!-- Here is the edit button --> </li> </ul> </td> </tr> {% endfor %} </tbody> </table> my modal here <div class="modal fade" id="showModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header bg-light p-3"> <h5 class="modal-title" id="exampleModalLabel"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="close-modal"></button> </div> <form action=""> <div class="modal-body"> <input type="hidden" id="id-field" /> <div class="row g-3"> <div … -
How can i make redirect when user login successfully with django-rest-framework
Urls.py from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView from InternetShop import settings from InternetShopApp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/products/', ProductsAPIList.as_view()), path('api/v1/products/int:pk/', ProductsAPIUpdate.as_view()), path('api/v1/productsremove/int:pk/', ProductsAPIRemove.as_view()), path('api/v1/auth/', include('djoser.urls')), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get country from (intl-tel-input) jquery
how can I get the name of the selected country from intlTelInput? I have a form with an input hidden this would get the name of the country as selected. but I don't know how to do this inttelephoneinput.js $(function() { $("#mobile-number").intlTelInput({ preferredCountries: ["us", "co"], }); }); template I clarify that the selection of countries and enter number works <div class="col-md-6 col-lg-6 mg-t-20 mg-md-t-0"> <input type="code" id="country" vale=" "> <label class="form-control-label">Telephone: <span class="tx-danger">*</span></label> <input class="form-control" type="tel" id="mobile-number" name='phone_number' placeholder="e.g. +1 702 123 4567"> </div> {% block extra_js %} <script src="{% static 'template/assets/plugins/telephoneinput/telephoneinput.js' %}"></script> <script src="{% static 'template/assets/plugins/telephoneinput/inttelephoneinput.js' %}"></script> {% endblock %}