Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.DataError: value too long for type character varying(20)
I am trying to shift my database from sqlite3 to PostgreSQL in my Django project. my models.py: from django.db import models from django.contrib.auth.models import AbstractUser class myCustomeUser(AbstractUser): #id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) def __str__(self): return self.username class Student(models.Model): user = models.OneToOneField(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True) gmail = models.EmailField(null=True, blank=False, unique=True) def __str__(self): return self.name how after successful(first) makemigrations and migrate I run py manage.py create superuser and then enter superuser's username, email and password. then It says the following error: Traceback (most recent call last): File "G:\Python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.StringDataRightTruncation: value too long for type character varying(20) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Python\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "G:\Python\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "G:\Python\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "G:\Python\lib\site-packages\django\contrib\auth\models.py", line 158, in create_superuser return self._create_user(username, email, password, … -
How to click a button to add friends and show an alert without refreshing or redirecting to another page
What I want to do is for a user to add and get an alert without refreshing the page,but I'm not that experienced with ajax,I would be thankful if you can get me a way I can pass the username of the friend to be added as a json data then send it to views.py to actually add friend on backend -
django return 2 same results when search through model?
In my django app, I have a search functionality for users to search through my model. I'm using django's SearchVector and SearchQuery because I'm using Postgresql as database. Everything works fine except it returns 2 exact same results. shell >>> results = MyModel.objects.annotate(search=SearchVector('title', 'content', 'tag__name'), ).filter(search=SearchQuery("some words")) >>> results <QuerySet [<MyModel: MyModel object (7)>, <MyModel: MyModel object (7)>]> it's been almost a day now that i'm trying to fix this problem. It worked fine in development but this problem occurs in production. Thanks you! -
Django previous MySQL raw query still running after changes the database to PostgreSQL
I am facing a problem after replacing the database connection from MySQL to PostgreSQL. Everything works fine but the MySQL raw query still running while I change it to PostgreSQL. The new raw query works fine in PostgreSQL Query tool. def home(request): if request.method == 'GET': cursor = connection.cursor() # cursor.execute('''select (select Date from datepd where dateid=Datepd_dateid) as Date, # (select QCL from productioninfo where infoid=Datepd_dateid) as QCL, # round(AVG(Gap),2) as gap FROM dailyproduction GROUP BY Datepd_dateid ORDER BY Date ASC''') cursor.execute('''select (select "Date" from public.surmafloor_datepd where dateid="Datepd_dateid") as "Date", (select "QCL" from public.surmafloor_productioninfo where infoid="Datepd_dateid") as "QCL", round(AVG("Gap"),2) as gap FROM public.surmafloor_dailyproduction GROUP BY "Datepd_dateid" ORDER BY "Date" ASC''') avrg = cursor.fetchall() The code still running the previous query. Right now I am having this error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FKL_CIT-02\fkl\pdfloor\surmafloor\views.py", line 243, in homeChart cursor.execute('''select (select Date from datepd where dateid=Datepd_dateid) as Date, File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\FKL_CIT-02\Envs\mis\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\FKL_CIT-02\Envs\mis\lib\site-packages\django\db\backends\utils.py", … -
Django admin. Text does not fit into manytomany field widget
Inside my django admin i have a manytomany field in which i want to fit a string.The string does not fit inside the field Is there any way to fix this? -
django intra-model field dependancy
I'm using django Oscar and trying to extend the apps included models to add some fields from the django-imagekit library to a model. The issue is that my underlying app which controls the dashboards (oscar) populates the forms for the dashboard directly from the models using from django.forms.models import inlineformset_factory. I want the fields I'm adding to be based off one of the fields already in the model, so I don't want to change any forms. Thus I need to intercept the input into the apps basic django.db.modelsImageField and use if for my new fields. example of a fork, where I subclass the model I want to extend #code from app I'm forking #link to src: https://github.com/django-oscar/django-oscar/blob/1fd9f0c3379042e1594f0d9281a5c323b5bafba2/src/oscar/apps/catalogue/abstract_models.py#L1302 class AbstractProductImage(models.Model): """ An image of a product """ product = models.ForeignKey( 'catalogue.Product', on_delete=models.CASCADE, related_name='images', verbose_name=_("Product")) original = models.ImageField( _("Original"), upload_to=get_image_upload_path, max_length=255) caption = models.CharField(_("Caption"), max_length=200, blank=True) #my fork/subclass from imagekit.models import ImageSpecField class Product(AbstractProductImage): srcset_image_1 = ImageSpecField( source=self.origional.name, processors=[ResizeToFill(100, 50)], format=self.origional.name.split('.')[-1].upper(), options={'quality': 80} ) Of course this throws an error: NameError: name 'self' is not defined Not to mention there is a serious issue of how to keep the srcset_image_1 field from containing stale data. Is there a way to manage such … -
Can anyone post a serious of steps to upload Adsense ads.txt file?
Can anyone post a serious of steps to upload Adsense ads.txt file to my root level domain (it is a django website)? -
Django Knox-Rest Authentication Receives 500 Error on Login
I'm working on setting up a Django knox-rest framework for my rest api. I'm using Postman to test the login and after executing the request, my API returns a 500 error along with a stack dump. The dump returned to Postman is showing me the following error: AttributeError at /users/api/auth/login 'LoginSerializer' object has no attribute 'validated_data' a snippet from my api.py file: class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer permission_classes = () def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.valiated_data _, token = AuthToken.objects.create(user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": token }) the snippet from my serializers.py file: class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") The server starts clean and no errors are logged to the console other than the Post request and the 500 error. I have to go to Postman to see the dump with the above error. I've tried just about everything I can think of or find to try without getting it figured out. So any help would be appreciated. -
TimeoutError [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time
I wanna sent a email to users account to reset password. But whenever I enter the send it causes an error. TimeoutError at /accounts/reset_password/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond I do not know why I am having a lot of issue in doing reset password. Things which I have done or try I already enable "less secure" apps in my gmail account. I was also having a issue in password_reset_email.html and for that I use email_template_name=accounts/registration/password_reset_email.html and after adding this the error was TemplateDoesNotExist. And then I make a dir in my accounts app and add a password_reset_email.html Here is code. any help please urls.py from django.urls import path, reverse_lazy from . import views from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('register/', views.register, name='register'), path('signin/', views.signin, name='signin'), path('logout/', views.logout, name='logout'), path('user_profile/', views.edit_profile, name='edit_profile'), path('user_password/', views.change_password, name='change_password'), # Rest password section path('reset_password/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset.html', success_url=reverse_lazy('accounts:password_reset_done'), email_template_name='accounts/registration/password_reset_email.html' ), name='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_sent.html', ), name='password_reset_done'), path('reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_form.html', success_url=reverse_lazy('accounts:password_reset_complete') ), name='password_reset_confirm'), path('rest_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name='accounts/password_reset_done.html', ), name='password_reset_complete') ] settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = … -
django: how to add photo field to the User: User() got an unexpected keyword argument
I have extended the User to have one more field profile_image, however, when I try to register and upload the image I'm getting an error: User() got an unexpected keyword argument 'profile_image' views-register form> def register(request): if request.method == "POST": # Get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] profile_image = request.POST['profile_image'] # Check if passwords match if password == password2: # Check username if User.objects.filter(username=username).exists(): messages.error(request, 'Username exists') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request, "Email exists") return redirect('register') else: # if ok user = User.objects.create_user(username=username, password=password, email=email, first_name = first_name, last_name = last_name,profile_image=profile_image) # Login after register auth.login(request, user) messages.success(request, "You are now logged in." ) user.save() return redirect('dashboard') else: return render(request, 'pages/register.html') models>extended Profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to = 'profiles/%Y/%m/%d/', blank = True, null = True) How can I add photo_image to the User? Any help is appreciated! -
How can I represent a class of existing python api in Django?
I'm trying to integrate an existing python API, (it's not a web API, it's a python library called Datalad) into a Django application. Going deeper, I'd like do create a django model that represents a dataset class, that is the representation of a git/git-annex repository. What's the best way to do this? -
django user.photo_image url issue
I extended regular User to have a additional custom field - photo. So far, this photo I added from the admin panel and I want to display the photo into the profile img src. Any help is appreciated! This is the path I can get for the photo: http://127.0.0.1:8000/static/profiles/%7B%7Buser.profile_image.url%7D%7D html> <img src = "{% static 'profiles/{{user.profile_image.url}}' %}"> models> class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to = 'profiles/%Y/%m/%d/', blank = True, null = True) -
Django duplicate key when trying to send a form with foreign key
I need to save a form with listaflor and multiple instances of flora2estado,When i try to send this form i get: IntegrityError at /enviar_flora/ (1062, "Duplicate entry '99-10031' for key 'PRIMARY'") views.py: def CreateFlo(request): form = FloForm() if request.method == 'POST': form = FloForm(request.POST) if form.is_valid(): listafor = form.save() estados = form.cleaned_data.get('estados') for estado in estados: Flora2Estado.objects.create(especie=listafor, estado= estado) # or you can use bulk_create: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-create return render(request,'accounts/enviar_flora.html') models.py: class Listaflor(models.Model): especie_id = models.AutoField(db_column="especie_id",primary_key=True) familia = models.ForeignKey(Familia, models.DO_NOTHING, db_column='familia_id', blank=True, null=True) Especie = models.CharField(db_column='especie', max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'listaflor' class Flora2Estado(models.Model): estado = models.ForeignKey(EstadosM, models.CASCADE) especie = models.ForeignKey(Listaflor, models.CASCADE,default=99999) flora2estado = models.AutoField(primary_key=True, default=99999) class Meta: managed = True db_table = 'flora2estado' unique_together = (('estado', 'especie'),) class EstadosM(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) nome_abbr = models.CharField(max_length=2, blank=True, null=True) criadoem = models.DateTimeField(db_column='criadoEm') class Meta: managed = False db_table = 'estados' def __str__(self): return self.estado_nome -
Djnago template form render horizontal and vertical in pairs
I am trying to render the form items in pairs in horizontal. Below code does table rendering but in a completely vertical view. I want Filename, Lastname fields together then on the next line next 2 form elements together, and so on. How to do that rendering in Django forms? I want to be least dependant on CSS here. Template - <table border="0"> {% for item in order_form.visible_fields %} <tr> <td>{{ item.label_tag }}</td> <td>{{ item }}</td> </tr> {% endfor %} </table> HTML - <table border="0"> <tbody> <tr> <td><label for="FirstName">First Name:</label></td> <td><input type="text" name="FirstName" id="FirstName" max_length="25" required=""></td> </tr> <tr> <td><label for="LastName">Last Name:</label></td> <td><input type="text" name="LastName" id="LastName" max_length="25" required=""></td> </tr> <tr> <td><label for="OrderNumber">Order Number:</label></td> <td><input type="text" name="OrderNumber" id="OrderNumber" label="Order Number" max_length="25" required=""></td> </tr> <tr> <td><label for="G_0">Gender:</label></td> <td><ul id="G"> <li><label for="G_0"><input type="radio" name="Gender" value="M" label="Gender" id="G_0" required=""> Male</label> </li> <li><label for="G_1"><input type="radio" name="Gender" value="F" label="Gender" id="G_1" required=""> Female</label> </li> </ul></td> </tr> </tbody> </table> -
Django: Get names of fields of a model class
I want to make a method that returns the names of fields of a model class. I want the method to return a list of field names, like this: ["first_name", "middle_name", "last_name", "gender"]. I have tried this: @classmethod def get_fields_for_form(cls): fields = cls._meta.get_fields(include_hidden=True) return [field.__class__.__name__ for field in fields] But the result I get is not what I want: ["AutoField", "ForeignKey", "CharField"] How can I get the name of the fields of a model class? -
Multiuser Microservice Django Architechture?
I have written a small application that does some computing and talks to some APIs based on a configuration (file). This application runs indefinetly and works with live data. I want to set up a Django based web-application that enables multiple people with separate logins to: • create own configuration files • get (live) visualizations of their results My questions are: How do I handle spawning, monitoring and closing/restarting the new processes per user via a Django view+template and do this with concurrency? What should I do to stay as efficient as possible? My first take was to use a database for storing the settings and have the application loop over this database, doing one action for one user at a time. But with more users this would lead to significant lag for each user, waiting for all other users to complete their run. Are queues what I am looking for? But if they are, how do I fill tasks to those queues based on individual configurations? I have written quite some python for myself, but this is new ground for me, so any input would be highly appreciated. -
Graphene Django: Creating a mutation with list of users to create a chat room
I'm trying to create this mutation using graphene-django for this class. I have three models: Chat, Message, and User. How would I create a new chat by linking the users by their usernames as a mutation? # Models in models.py class BaseUser(models.Model): username = models.CharField(max_length=128, unique=True) customizable_name = models.CharField(max_length=128) class Chat(models.Model): users = models.ManyToManyField(BaseUser) name = models.CharField(max_length=128, blank=True) last_message = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to="uploads/chat/room", blank=True, null=True) class Message(models.Model): chat_fk = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name="chat") user_fk = models.ForeignKey(BaseUser, on_delete=models.CASCADE, related_name="sending_user") text = models.CharField(max_length=500, blank=True) created_time = models.DateTimeField(auto_now_add=True) Type in schema.py class BaseUserType(DjangoObjectType): class Meta: model = models.BaseUser fields = ['id','username', 'customizable_name','created_on'] class ChatType(DjangoObjectType): class Meta: model = models.Chat fields = ['id', 'users', 'name', 'last_message', 'image'] Mutation in schema.py class CreateChat(graphene.Mutation): name = graphene.String() users = graphene.List(graphene.String) image = graphene.String() class Arguments: name = graphene.String() users = graphene.List(graphene.String) image = graphene.String() chat = graphene.Field(ChatType) def mutate(root, info, name, users, image): #user = [] #for user in models.BaseUser.objects.all(): # models.BaseUser.objects.filter(username__in) chat = Chat(name = name, users = users, image = image) chat.save() return CreateLocation( id = chat.id, name = chat.name, users = chat.users, image = chat.image, ) GraphQL on GraphiQL mutation createChat { createChat(name: "Chat", users: ["user1", "user2"], image: "Image"){ name users image } … -
Selectable list of users in Django?
models.py class EmployeeReportRequestForm(forms.Form): EMPLOYEECHOICE = [] employees = User.objects.filter(group_name='rep') for employee in employees: EMPLOYEECHOICE.append([employee.get_username(), employee.get_full_name()]) employee_choice = forms.CharField(max_length=50, widget=forms.Select(choices=EMPLOYEECHOICE)) start_date = forms.DateField(widget=forms.SelectDateWidget()) end_date = forms.DateField(widget=forms.SelectDateWidget()) Trying make a form that allows someone to make a selection from a list of users in a particular group, I figured this would work, but it is not. The most info I'm able to get error wise is "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." I'm assuming my issue is trying to query the User database from within a Model and that I need to run the lines of code that generate the EMPLOYEECHOICE list in a view and then somehow pass that to the Model? Or just define the widget to be used in the View? -
How to fix error 'str' object has no attribute 'relative_url'
I am trying to pass some wagtail contexts to the search page of a django project. The post title appears but the image, description and other parameters do not appear in the search template. How do I pass these contexts to the search template? This is the search.view.py code from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from news.models import NewsPage, NewsCategory def search(request): posts = NewsPage.objects.live().public() categories = NewsCategory.objects.all() # Search search_query = request.GET.get('q', None) if search_query: search_results = NewsPage.objects.live().search(search_query) # Log the query so Wagtail can suggest promoted results Query.get(search_query).add_hit() reversenews = list(reversed(search_results)) # Pagination paginator = Paginator(reversenews, 16) #show 10 articles per page page = request.GET.get('page') try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) else: search_results = NewsPage.objects.none() # Render template return render(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, 'recent_posts' : posts, 'categories' : categories }) this is the search template search.html {% extends "news/news_index_page.html" %} {% load static wagtailcore_tags %} {% load wagtailembeds_tags %} {% load wagtailcore_tags %} {% load static wagtailuserbar %} {% load wagtailimages_tags %} {%load static%} {% load wagtailcore_tags %} {% load wagtailroutablepage_tags %} {% block content … -
Making changes on code doesn't reflect on django webapp
I'm trying to edit my code on my django but somethings really weird is happening and i don't know what's happening. making me crazy af. my chart code is inside static folder under js/chart1.js then on my django template, i have <script type="text/javascript" src="{% static 'js/chart1.js' %}"></script> now i edited the chart1.js but it wont reflect. i tried deleting staticfolder, restarting server, even deleting chart1.js under js directory just as long as <script type="text/javascript" src="{% static 'js/chart1.js' %}"></script> is there, the chart still there even tho chart1.js dont exists anymore. i dont know where the hell is django getting its data for my graph. can someone tell me whats happening? thanks! -
making gjango DeleteView generic?
I am using the django DeleteView class to delete different entries. The only thing that differs from call to call is the model attribute. It there anyway to have only one call for delete for different models? My sugggestion is something along these lines but I don't know how to implement it. Any suggestions? views.py: class Delete(DeleteView): template_name='kammem/delete.html' success_url=reverse_lazy('forl') model=super().get_context_data() def get_context_data(self,**kwargs): mod=self.kwargs['model'] if mod=='forening': model=forening elif mod=='person' return model urls.py: path('delete/<int:pk>/<str:model>',Delete.as_view(),name='delete'), -
django-crontab fails to run in background
I have setup a script that fetches offline Access Points from a Wireless Controller and saves data to DB. I am using django-crontab which runs well with the manage.py script. However, the cron job fails to execute in background. Would appreciate any guide. Thanks enter image description here -
How to implement user daily progress tracking in Django?
I'm building a web app that allows user's to write stories and track their word-count progress. I've got a working processor implemented and the ability to grab the word-count, but how do I track this word-count progress on the backend? I imagine if I were able to somehow save the user's daily word-count change and total word-count neatly in the database, I wouldn't have much trouble filtering it and then displaying it. My issue is how do you save something like this in the database? What if the user doesn't log in for a number of days and I don't run any view to add to my database? I still want those day's recorded as 0s. Any help would be greatly appreciated. Using PostgreSQL if that is relevant. -
How to share project to Github via PyCharm such that it does not include .gitignore files
I cannot figure out how to share my PyCharm project with Github so that it does not include .gitignore files. I have read solutions from other posts, and tried them, and the problem persists. What I've tried: Deleting the repository from Github Removing path to previously existing Github repo in PyCharm version control settings git remote remove origin git rm -r --cached . git add . installed ignore Then, sharing with Github... Yet it is still including files listed in .gitignore. What am I doing wrong? -
django code 400, message Bad request version ('î\x9el\x00$\x13\x01\x13\x03\x13\x02À+À/̨̩À,À0À')
I was trying to implement 'Securing Django Admin login with OTP', however I can't login into the admin panel now. I removed the app from everywhere but still doesn't work. Any solution for this? [05/Feb/2021 21:39:49] code 400, message Bad request version ('î\x9el\x00$\x13\x01\x13\x03\x13\x02À+À/̨̩À,À0À') [05/Feb/2021 21:39:49] You're accessing the development server over HTTPS, but it only supports HTTP.