Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django graphene subscriptions keep loading without sending me the data
I followed the instrections here with an existed graphen api gitHub repo. Hoever, I tried all the three options graphql-python/graphql-ws datavance/django-channels-graphql-ws jaydenwindle/graphene-subscriptions. but non of them worked with me. problem: enter image description here as you can see here it is loading forever without sending the data. goal : I need to create realtime grapheql api (subscriptions) files: Note: in the repo you will see the original repo without the subscriptions code. -
Django view is not creating records in Database
i am not able to create record in a table FinTransDetail by admin: when I trying to add records I am getting errors. Please help to solve the issues. As I could not add by admin I can not add records by my View as well. But I can add record in FinTransHeader both by admin and by me view. Model: class FinTransHeader(models.Model): """Model representing a book (but not a specific copy of a book).""" fh_type = models.CharField(max_length=200) fh_code = models.CharField(max_length=200) fh_no = models.DecimalField(max_digits = 5, decimal_places = 0,unique=True) fh_dt = models.DateField() fh_detail=models.CharField(max_length=200,blank=True,null=True) fh_cust_code = models.CharField(max_length=200,blank=True,null=True) fh_user_code =models.CharField(max_length=200,blank=True,null=True) fh_ref=models.CharField(max_length=200,default='nil',blank=True,null=True) fh_status=models.CharField(max_length=1,default=0) fh_post_status = models.BooleanField(default=False) th_prt_status=models.BooleanField(default=False) def __str__(self): """String for representing the Model object.""" return str(self.fh_code) # return self.fh_no class FinTransDetail(models.Model): fd_no = models.ForeignKey( FinTransHeader,on_delete=models.CASCADE) fd_acct = models.ForeignKey(AccountMaster, to_field='AcctCode',on_delete=models.CASCADE) fd_debit = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_credit = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_detail=models.CharField(max_length=200, null=True, blank=True ) fd_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_posting=models.BooleanField(default=False, blank=True, null=True) def __str__(self): """String for representing the Model object.""" # return self.ToString(AcctCode)+"-"+self.AcctName return str(self.fd_no) when I am trying to add records in FinTransDetail i am getting Html error as below: TypeError at /admin/waccounts/fintransdetail/add/ __str__ returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/admin/waccounts/fintransdetail/add/ Django Version: 3.1.1 Exception Type: … -
How to add a form in an html page in django
I want to add comments form a specific html which has it's own views and models and I do not want to create a new html file like comment.html which will only display the form and its views. I want users to be able to comment right underneath a post, so that users don't have to click a button such as "add comment" which will take them to a new page with the "comment.form" and then they can comment. Basically want a page with all transfer news and their respective comments as well as a comment-form under the old comment. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance! My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py : class … -
django.core.exceptions.FieldError: Unknown field(s) (foo) specified for MyModel
Documenting my own mistake. Hope this could help others ! models.py class MyModel(models.Model): foo = models.CharField(max_length=50), bar = models.IntegerField() forms.py class MyModelForm(forms.ModelForm): class Meta: fields = ['foo', 'bar'] Error during system check: django.core.exceptions.FieldError: Unknown field(s) (foo) specified for MyModel Whereas the field foo is defined on MyModel... -
attempted relative import with no known parent package django
There are two models and a signal and I want to implement the AutoUpdateBio section but when I run the code I face the bellow error models from django.contrib.auth.models import User from django.db import models class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) nickname = models.CharField(blank=True, null=True, max_length=50) location = models.CharField(blank=True, null=True, max_length=50) weight = models.DecimalField(null=True, max_digits=5, decimal_places=2) signals from .models import * from django.dispatch import receiver from django.db.models.signals import post_save, m2m_changed @receiver(post_save, sender=User, dispatch_uid='') def receiver_func(sender, instance, created, update_fields, **kwargs): if created and update_fields == None: profile = Profile.objects.create(user=instance) @receiver(m2m_changed, sender=Website.users.through) def AutoUpdateBio(sender, instance, action, reverse, pk_set, **kwargs): if action == 'post_add': # ** Add user to website - instance: website if not reverse: print(instance) print(pk_set) # ** Add website to user - instance: user else: print(instance) print(pk_set) I got this error when I run the code to see the print outputs traceback Traceback (most recent call last): File "d:..\accounts\signals.py", line 1, in <module> from .models import * ImportError: attempted relative import with no known parent package -
Django FileResponse don't download HTML file
I'm trying to download an pre-generated HTML file, but all that i've tried doesn't work. Searching StackOverflow i found that return FileResponse(open(file_path, 'rb')) will download a file, but intead of download, the HTML just is rendered on the tab. I think the problem is the browser receive the HTML and instead of display the "Save as" dialog just render it to the current tab. In my main template i have a form with target="_blank" tag, and a submit button that open (without AJAX) a new tab who suposed to download automatically the file. What i want: After i submit the code a new tab appears, the view related to that URL do some code (not related to the download) and after that process (that is working fine) download an HTML file to the device. The HTML exists and don't have any problem, te only problem it's that i want to DOWNLOAD the file but the browser display it instead. Note 1: Yes, i know that with right clic -> download i can download the HTML that i see, but this system is for non IT people, i need to do it the easest way possible. Note 2: I put the … -
DRF identify user by Bearer Token
I'm using Django-restframework with django-oauth-toolkit. My model has a foreign key to my custom user model class DiseaseCase(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='daard_case_user', on_delete=models.CASCADE) My drf view: class DiseaseCaseViewset(viewsets.ModelViewSet): serializer_class = DiseaseCaseSerializer queryset = DiseaseCase.objects.all() http_method_names = ['get', 'post', 'head'] permission_classes = [IsAuthenticatedOrReadOnly] and my serializer: class DiseaseCaseSerializer(serializers.ModelSerializer): owner = serializers.SerializerMethodField('get_owner') # not working def get_owner(self, obj): from oauth2_provider.models import AccessToken tok_user = AccessToken.objects.get(token="GSY4QwID3NShVz7PoeeHSzsOg4naR9") return tok_user.user class Meta: model = DiseaseCase search_fields = ['name'] exclude = ['is_approved',] filter_backends = (filters.DjangoFilterBackend) As you see, I'm trying to identify the user based on the bearer token (as auth type) in get_ownerbut this fails asrequest` is empty in my serializer. NameError: name 'request' is not defined It feels like I'm reinventing the wheel or do not see the forest because of trees. How can I update the user field of my model based on token auth? -
'str' object has no attribute 'isComplete' when I try to reach foreign key attribute in DRF
First of all, I am new in DRF. I've searched about the error but I don't get where there is a str attribute. As far as I understand, it gets order and product in OrderItemViewSet as strings, but they are referring to other classes with a foreign key. This is my views.py class OrderItemViewSet(viewsets.ModelViewSet): queryset = OrderItem.objects.all() serializer_class = OrderItemSerializer detail_serializer_class = OrderItemDetailSerializer filter_backends = (DjangoFilterBackend, OrderingFilter, ) ordering_fields = '__all__' def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super().get_serializer_class() def get_queryset(self): queryset = OrderItem.objects.all() product = self.request.query_params.get('product', None) order = self.request.query_params.get('order', None) if product is not None: product = product.album_name() queryset = queryset.filter(product__album_name=product) if order is not None: order = order.isComplete() queryset = queryset.filter(order__isComplete = order) return queryset def create(self, request): #parse incoming request or add new order item message = request.data.pop('event') if message == "NewOrderItem": event = request.data.pop('event') product = event.pop('product') orders = event.pop('orders')[0] #only one order customer = orders.pop('order') #not sure about selections product = Product.objects.create(**product) orders = Order.objects.create(**orders, product=product) #not sure orders.customer.create(**user) order = Order.objects.create(**event, product=product, order=orders) return Response(status=status.HTTP_201_CREATED) models.py class Product(models.Model): model_no = models.CharField(max_length=200, blank=True, null=True) album_name = models.CharField(max_length=200, blank=True, null=True) artist_name = models.CharField(max_length=200, blank=True, null=True) description = models.CharField(max_length=200, blank=True, null=True) … -
Creating a request to the django model
I have a model class paidparking(models.Model): adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True, verbose_name='Адрес парковки') carnumber = models.CharField(max_length=150,verbose_name='Номер автомобиля') amountoftime = models.IntegerField(verbose_name='Количество времени') price = models.FloatField(verbose_name='Цена') telephone = models.CharField(max_length=20,verbose_name='Номер телефона') email = models.EmailField(verbose_name='Электронный адрес',null=True,blank=True ) datetimepaidparking = models.DateTimeField(auto_now_add=True, verbose_name='Дата и время оплаты') expirationdate = models.DateField(null=True,verbose_name='Дата начала срока действия') expirationtime = models.TimeField(null=True,verbose_name='Время начала срока действия') enddateandtime = models.DateTimeField(null=True,blank=True,verbose_name='Окончание срока действия') The form has 2 fields with date selection In the function, I get the value from these fields startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y') enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y') In the model, the expirationdate field. The date in this field is in the format %d.%m.%Y I need to form a request to the django model. If the date in the expirationdate field falls between startdate and enddate, then all records must be retrieved -
Cannot connect Django to existing MySQL database (Symbol not found: _mysql_affected_rows)
So, I am having trouble connecting Django to an existing MySQL database (created from a dump for dev purposes). Here is my steps and all the terminal output: Get database ready Install MySql 5.7 Start MySQL brew services start mysql@5.7 Open MySQL Workbench and connect via password Create new schema Open MySQL Database dump; insert use climate at the top of file, run script -> Database is ready Setting up Django create new python venv python3 -m venv good-env Activate venv source good-env/bin/activate Installing django python -m pip install Django Downloading Django-3.2.2-py3-none-any.whl (7.9 MB) |████████████████████████████████| 7.9 MB 3.8 MB/s Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting asgiref<4,>=3.3.2 Using cached asgiref-3.3.4-py3-none-any.whl (22 kB) Collecting pytz Using cached pytz-2021.1-py2.py3-none-any.whl (510 kB) Installing collected packages: sqlparse, asgiref, pytz, Django Successfully installed Django-3.2.2 asgiref-3.3.4 pytz-2021.1 sqlparse-0.4.1 WARNING: You are using pip version 20.1.1; however, version 21.1.1 is available. You should consider upgrading via the '/Users/aaronkurz/Dev/2/good-env/bin/python -m pip install --upgrade pip' command. Creating a project django-admin startproject climatevisual; cd climatevisual Connecting Django with the database Installing required drivers (I know only mysqlclient should suffice, but that led to the same result so I started trying to install both...) pip install mysqlclient Installing collected packages: … -
Strange behavior when sending file to django server in vuejs
When sending my audio files in vuejs I kept getting errors 'the submitted data was not a file, check the encoding type on the form.' So I tried giving it a file directly: let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'}); console.log(file) var audiopost = { id: "11", user: "username", room: "roomOne", "audiofile": file} this.$store.dispatch("audio/createAudio",audiopost); However, when analyzing in Burp the resulting post request, the audiofile field was empty.. Do you have any Idea what is happening ? Thanks for reading ! Empty Audiofield burp request -
How to "skip" submodule declaration on import
Starting with the structure (this is a Django project). root/ app_1/ views.py my_module/ __init__.py submodule/ __init__.py mixins.py I can normally import on app_1/views.py with the full declaration. from my_module.submodule.mixins import MyMixin But I wish to skip declaring submodule. from my_module.mixins import MyMixin I've tried some combinations of from x import y on both __init__.py files in my_module and sub_module but I've only managed to skip the submodules altogether. from my_module import MyMixin I don't love this option because it hides all my files. Is there a way to get it the way I want? -
How to retrieve a stripe subscription id after a checkout session in a django project?
Here is my problem. I made a stripe subscription for my django project, and I used the checkout session method. I would like to retrieve the stripe subscription id, after the payment, to put it on my customer model, so I can make a cancel subscription method for the customer, because the method given by stripe require to have this id : stripe.Subscription.modify( *sub_id*, cancel_at_period_end=True ) or stripe.Subscription.delete(*sub_id*) The problem is that I can't find the id anywhere else than in my stripe account, where I have every informations I can need, but I can't find how to retrieve it through code after the payment has been done. I need to fill the field 'stripe_sub_id' in my customer model so i can make the cancel method work. Here is the method that creates the checkout session @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'http://127.0.0.1:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'projets/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'projets/cancelled/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': sub_price_id, 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) And here is my script to activate the session //Get stripe publishable key fetch("/projets/config/") .then((result) => { return result.json(); }) … -
How to populate dropdown menu from Django database
I would like to create two dropdown menus from the data out of a database. I have been struggling with this for the past few hours and have no idea how to fix it. I have imported my CSV file to my database using Jupyter with sqlite3: import pandas as pd import sqlite3 lol = pd.read_csv('LeagueofLegends.csv') del lol['Address'] path = '#path to directory' cxn = sqlite3.connect(path + 'db.sqlite3') cxn.cursor().executescript('drop table if exists lol;') lol.to_sql('lol', cxn, index = False) cxn.close() As far as I know, everything went well, but now I'm at the point where I want to make a few dropdown menus from the data from the database. Down below I have included a snippet of the data. The two dropdowns I want to create are a blueTeamTag and a redTeamTag dropdown. I have tried this for hours but have no clue how to do this. Also, both the blueTeamTag and the redTeamTag contain duplicated, that I have to get rid of before putting it in a dropdown. I also included my views.py, models.py, and the HTML script where the dropdown menus should go. views.py: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Lol # Create … -
What's wrong with my Django Nginx configuration?
I've been having this issue for over the last two months, having deployed using multiple different platforms various times. I am at my wits end. So I am trying to deploy a website using Django, NGINX, GUNICORN to digital ocean. I keep getting a 404 error and have no idea what to do. Settings.PY File Django settings for django project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import mimetypes mimetypes.add_type("text/css", ".css", True) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['mysite.net','wwww.mysite.net','localhost',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', 'django.contrib.sessions.middleware.SessionMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], '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', ], … -
Created objects are not save through cmd in django python
from sabin.models import Task >>> Task.objects.all() <QuerySet []> >>> t=Task(title="dhiraj") t=Task(title="dhiraj") t.save() error says Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: table sabin_task has no column named title The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\sql\compiler.py", line 1410, in execute_sql cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, … -
Django On-Insert trigger
I have a model in Django which I want to be automatically populated with values once another model has objects inserted. This is the originator model Question: class Question(models.Model): question = models.CharField(max_length=200, null=False, blank=False) description = models.TextField('description', default=False) voters = models.ManyToManyField(User, related_name='+') votes = models.IntegerField(default = 0) created_by = models.ForeignKey(User, on_delete=models.CASCADE) Question View: class QuestionApiView(AuthenticatedAPIView): """ Lists all questions or creates a new question """ def post(self, request, format=None): vote_data = request.data vote_data["created_by"] = request.user.id data["created_by"]=request.user.id print(vote_data) print(vote_data["voters"]) voter_data = vote_data["voters"] result, valid = QuestionHelper.createQuestion(vote_data) Question Helper: class QuestionHelper(object): @classmethod def createQuestion(klass, questiondata): """ creates a question """ createdQuestion = QuestionSerializer(data=questiondata) if createdQuestion.is_valid(): createdQuestion.save() return createdQuestion.data, True return createdQuestion.errors, False Question Serializer: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' This is my Choice model which I want the values Yes, No and Abstain added onto choice_text once a Question object is created: question = models.ForeignKey(Question, on_delete=models.CASCADE, default=1) choice_text = models.CharField("choice", max_length=250) This way, each Choice will be linked to a Question using the question_id -
Couldn't find that process types (web)
I was trying to host my django app on heroku when I saw the error stating web processes are not working so when searched for I saw that I have to use command: heroku ps:scale web=1 after that I got error: (djangoProject1) C:\Users\USER\PycharmProjects\djangoProject1>heroku ps:scale web=1 Scaling dynos... Couldn't find that process type (web). -
Django see all user information in admin panel
After creating the member record in the application, only the username is reflected in the admin panel, but I want to get the name and surname as well. I specify this in the codes, but there is no reflection. views.py from django.shortcuts import render,redirect from .forms import RegisterForm from django.contrib.auth.models import User from django.contrib.auth import login from django.contrib import messages def register(request): form=RegisterForm(request.POST or None) if form.is_valid(): name=form.cleaned_data.get("name") lastname=form.cleaned_data.get("lastname") username=form.cleaned_data.get("username") password=form.cleaned_data.get("password") #newUser=User(name=name) newUser = User(username=username) newUser.set_password(password) newUser.save() login(request,newUser) messages.info(request,"Başarıyla Kayıt Oldunuz...") return redirect("index") context={ "form":form } return render(request,"register.html",context) Form.py from django import forms from django.contrib.auth.forms import UserCreationForm class RegisterForm(forms.Form): name=forms.CharField(max_length=50,label="Adı ") lastname=forms.CharField(max_length=50,label="Soyadı ") username=forms.CharField(max_length=50,label="Kullanıcı Adı ") password=forms.CharField(max_length=20,label="Parola",widget=forms.PasswordInput) confirm=forms.CharField(max_length=20,label="Parolayı Doğrula ",widget=forms.PasswordInput) def clean(self): name=self.cleaned_data.get("name") lastname=self.cleaned_data.get("lastname") username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") confirm=self.cleaned_data.get("confirm") if password and confirm and password != confirm: raise forms.ValidationError("Parolalar Eşleşmiyor...") values = { "name" : name, "lastname" :lastname, "username" : username, "password" : password, } return values Although I specify the name and name fields, it is not reflected in the panel -
How to assign a user to a new object with Django?
I'm trying to assign the current logined user to an account model object in Django but for some reason the user is not assigned. I did try with form.user = User.objects.get(username=request.user) but problem is the same. How could I do that ? This is my code, a logged in user is able to create a new instance of the model but instance.user remains empty. models.py class Account(models.Model): name = models.CharField(max_length=100, null=True, blank=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True ) forms.py class AccountForm(ModelForm): class Meta: model = Account fields = ['name'] view.py def create_account(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): form.user = request.user print('user', request.user) # Return the user name correctly form.save() return redirect('accounts') else: form = AccountForm() return render(request, 'account/account_create.html', { 'form': form }) account_create.html <h1>Create new account</h1> <form action="{% url 'account_create' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button class="button" type="submit">Create</button> </form> -
Django page not found (404) error I think there is some mistake in urls and in edit.html in forms action
enter image description hereThis is my edit.html <form method="POST" action="update/{{i.id}}" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="noticeperiod">Notice Period (in Days) :</label> <input type="text" class="form-control" value ={{i.noticeperiod }} name="noticeperiod" id="notice_period" placeholder="Notice Period"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="preferredlocation">Current Location :</label> <input type="text" class="form-control" value ={{i.preferredlocation}} name="preferredlocation" id="preferred_location" placeholder="Enter Current Location"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="expectedlocation">Expected Location :</label> <input type="text" class="form-control" value ={{i.expectedlocation}} name="expectedlocation" id="expected_location" … -
How to trace code in a Django production system
My code behaves different in the production code, than on my development machine. I would like to debug/trace it. Since it runs on Heroku. I use PyCharm. AFAIK I can't insert import pydevd_pycharm; pydevd_pycharm.settrace(... into the code. I don't need a fancy GUI a command-line tool would be fine, too. I would be happy if I could see all lines which get executed during a particular http request. How to solve this for production systems? -
Converting .csv string data into DateField type in Django models.py
I am using Python 3.7 on Debian 10 I have a number of pre-existing .csv files with these columns: first_name, last_name, birthdate, phone, email I am importing them into a postgres database with Django as the framework. My Django model: from django.db import models class User(models.Model): first_name = models.TextField(blank=False, null=False) last_name = models.TextField(blank=False, null=False) birthdate = models.TextField(blank=True, null=True) phone = models.TextField(blank=False, null=False) email = models.TextField(blank=False, null=False) Custom Django Management Command to import file import_users.py: class Command(BaseCommand): def handle(self, *args, **options): users_file = open(f'{settings.DATA_IMPORT_LOCATION}/users.csv', 'r') for counter, line in enumerate(users_file): line_fields = line.split(',') first_name = line_fields[0] last_name = line_fields[1] birthdate = line_fields[2] phone = line_fields[3] email = line_fields[4] u = User() u.first_name = first_name u.last_name = last_name u.birthdate = birthdate u.phone = phone u.email = email u.save() Output sample when running the following Django ORM query : > for u in User.objects.all(): print(u.birthdate) Output: birthdate 2015-05-28 2009-06-14 2007-01-01 2007-02-17 2008-05-16 2013-01-19 2008-07-24 2015-05-01 2007-06-03 2007-01-17 When birthdate = models.TextField is set to TextField, I can import these .csv files into my Postgres database successfully with my management command. This makes sense because all the .csv data are strings. However, I want to correctly set the model to read as a date, … -
What shall I use for full text search and fuzzy search on a social network django site with a postgresql database?
So, I was looking for a search engine for my new django project with a postgresql database and I ended up with elasticsearch and sphinx. I've chosen the second one, because I thought that if you're searching in a lot of posts you need a fast search, which uses less memory, but after looking at realization of sphinx I went up like, "How do I do that on python and can I do fuzzy search with it?". I've found few django-sphinx libraries, but they seem to be abandoned (last update was 5 years ago), and in sphinx documentation I didn't find anything about django, just few mentions of python. So, is sphinx still alive and how can I use it with django, or should I choose another engine for my tasks? -
"Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers." ValueError: Input is not valid
I am using Bert tokenizer for french and I am getting this error but I do not seems to solutionated it. If you have a suggestion. Traceback (most recent call last): File "training_cross_data_2.py", line 240, in <module> training_data(f, root, testdir, dict_unc) File "training_cross_data_2.py", line 107, in training_data Xtrain_emb, mdlname = get_flaubert_layer(data) File "training_cross_data_2.py", line 40, in get_flaubert_layer tokenized = texte.apply((lambda x: flaubert_tokenizer.encode(x, add_special_tokens=True, max_length=512, truncation=True))) File "/home/getalp/kelodjoe/anaconda3/envs/env/lib/python3.6/site-packages/pandas/core/series.py", line 3848, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas/_libs/lib.pyx", line 2329, in pandas._libs.lib.map_infer File "training_cross_data_2.py", line 40, in <lambda> tokenized = texte.apply((lambda x: flaubert_tokenizer.encode(x, add_special_tokens=True, max_length=512, truncation=True))) File "/home/anaconda3/envs/env/lib/python3.6/site-packages/transformers/tokenization_utils.py", line 907, in encode **kwargs, File "/home/anaconda3/envs/env/lib/python3.6/site-packages/transformers/tokenization_utils.py", line 1021, in encode_plus first_ids = get_input_ids(text) File "/home/anaconda3/envs/env/lib/python3.6/site-packages/transformers/tokenization_utils.py", line 1003, in get_input_ids "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers." ValueError: Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers. I look around to fond answer but whaever is proposed do not seems to work. Texte is dataframe. here the code : def get_flaubert_layer(texte): # teste is dataframe which I take from an excel file language_model_dir= os.path.expanduser(args.language_model_dir) lge_size = language_model_dir[16:-1] # modify when on jean zay 27:-1 …