Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No pylint warning "Redefining built-in" for a class local variable
I came across a Django model like this: class Car(models.Model): type = CharField() ... However, pylint does not issue any warnings about redefining the built-in function type. It is only when I move it out of the class to the global scope pylint warns about this, but not within the class. Is this the expected behavior? If so, how can I override it to show warnings within classes or functions as well? VSCode 1.61.0 Ubuntu 20.04 Python 3.8.10 -
WSL2 - pip install django takes a long time (around 4 minutes to complete)
I just activated WSL2 on Windows 10. I already activated virtualenv to install django using pip install django. But it takes around 4 minutes to complete the installation. Is it normal for WSL2 to takes that long time only pip packages? Any tweaks to speed up pip install on WSL2? Here is the screenshot -
C# operator \n for string in HTML not working
Website on Django 3.2, Visual Studio 2019. It is necessary to transfer the text of the link description - a text string in the HTML code. There are special HTML codes &#10; &#13; for line feed and carriage return. Their use does not give the desired result. <br> - is working: <a href="link">Text3.<br>Text4.</a>. But why HTML special codes not working? {% extends "/layout.html" %}<!--♕-->{% block content %}<div class="Jambotron"> <h1>Welcome!</h1> <p class="lead">Text1!&#10;&#13;Text2.</p> <a href="link">Text3.&#10;&#13;Text4.</a> </div>{% endblock %} Example: special codes HTML did not work out as intended -
Django making url with slug but "django.db.utils.IntegrityError: UNIQUE constraint failed:" error occurs
I want to make url with building name using slug. ex) api/buildingdata/Abuilding And this url has review data. urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view()) ] models.py from django.db import models # Create your models here. from django.utils.text import slugify class buildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(unique=True, allow_unicode=True) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): self.slug = slugify(self.building_name, allow_unicode=True) return super().save(*args, **kwargs) class reviewData(models.Model): building = models.ForeignKey(buildingData, related_name='reviews', on_delete=models.CASCADE, null=False, blank=False) review_content = models.TextField() star_num = models.FloatField() errors File "c:\Users\admin\Desktop\crawler\crawling.py", line 190, in button_clicked crawling(search_key, search_cnt, file_name) File "c:\Users\admin\Desktop\crawler\crawling.py", line 133, in crawling buildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call'], building_time = item['time']).save() File "c:\Users\admin\Desktop\crawler\crawling_data\models.py", line 17, in save return super().save(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "C:\ProgramData\Anaconda3\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:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\sql\compiler.py", line … -
Django custom registration form errors
Hope you have wonderful day. I've build custom register form, but when form is not valid, the form returns without error on it. Example: Im inserting incorrect password to "confirm password" input, and after sending the form, no error could be found on the form it self. It might because im not returning the form correctly? This is my form.py file: class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=50, help_text='Required. Inform a valid email address.', widget=(forms.TextInput(attrs={'class': 'form-control'}))) password1 = forms.CharField(label=('Password'), widget=(forms.PasswordInput( attrs={'class': 'form-control'})), help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label=('Password Confirmation'), widget=forms.PasswordInput(attrs={'class': 'form-control'}), help_text=('Just Enter the same password, for confirmation')) username = forms.CharField( label=('Username'), max_length=150, help_text=( 'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), error_messages={'unique': ( "A user with that username already exists.")}, widget=forms.TextInput(attrs={'class': 'form-control'}) ) class Meta: model = User fields = ('username', 'email', 'password1', 'password2',) the signup function using the Signup form: csrf_exempt def signup1(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid() is False: form = SignUpForm() return render(request, 'accounts/register.html', {'form': form}) if form.is_valid(): print(str(form.cleaned_data["email"])) email = str(form.cleaned_data["email"]) username = str(form.cleaned_data["username"]) p1 = str(form.cleaned_data["password1"]) p2 = str(form.cleaned_data["password2"]) try: user1 = User.objects.get(email__exact=email) except: form = SignUpForm() return render(request, 'accounts/register.html', {'form': form}) if p1 != p2: form = SignUpForm() return render(request, 'accounts/register.html', … -
In my html template a tag href doesn't work
I am developing a project using django.But in html template href function doesn'work.When ı come to area,link is showing on the bottom of the page.But url doesn't work.Not just django url.When ı write there https://www.google.com,again it is not working.How can I fix it? index.html <div class="chat-users-list" style="height: 112%;"> <div class="chat-scroll" > {% for user in users %} <a class="media {% if forloop.counter0 == 0 %} read-chat active {% endif %} " href="{% url 'startChat' user.slug %}" > <div class="media-img-wrap"> <div class="avatar avatar-away"> <img src="{% static 'assets/img/patients/patient.jpg' %}" alt="User Image" class="avatar-img rounded-circle"> </div> </div> <div class="media-body"> <div> <div class="user-name">{{user.get_full_name}}</div> <div class="user-last-chat">Hey, How are you?</div> </div> <div> <div class="last-chat-time block">2 min</div> <div class="badge badge-success badge-pill">15</div> </div> </div> </a> {% endfor %} </div> </div> style.css .chat-window .chat-scroll { min-height: 300px; max-height: calc(100vh - 224px); overflow-y: auto; } .chat-cont-left .chat-users-list { background-color: #fff; } .chat-cont-left .chat-users-list a.media { border-bottom: 1px solid #f0f0f0; padding: 10px 15px; transition: all 0.2s ease 0s; } -
I cannot make user admin in django rest framework
I work on next.js Django project. I m testing admin functionality so i try to make a user admin. in django admin interface, I checked in user.is_staff and user.is_superuser but i still get the user.isAdmin false. I tried to do change the isAdmin from shell $ from django.contrib.auth.models import User $ user=User.objects.get(username="user@hotmail.com") # 'User' object has no attribute 'isAdmin' $ user.isAdmin # I manually set it to be True $ user.isAdmin=True $ user.isAdmin # True $ user.save() now I currently user.is_staff and user.is_superuser is selected from admin interface, I manually set the isAdmin property to True in shell, I exit, restart the server. I still get it False: I interacted with user in shell again, when I enter admin.isAdmin, i get the error "has no attribute isAdmin" -
Django - New URL not working in working app
I have an app in my project wich is working fine. Now i added a new URL to the url.py with my new view, got an 'not found' error. Now I set the url at first place of the urls.py and used an other view wich is definetly working with the original URL. Same issue. So in the same app where other views are displayed without any issue, the new one could not be found, weather with a new (maybo faulty view) or one that works perfectly with an other url. in the example tritemphyg is working perfectly with its url. But when I want to direct cis/ to the same view, it can now be found. from django.urls import path from . import views urlpatterns = [ path('cis/', views.TriTempHygView.as_view()), path('tritemphyg/', views.TriTempHygView.as_view()), path('cistern/', views.SpuKasView.as_view()), path('quadtemphyg/penis/', views.PenisView.as_view()), ] -
How can I create django default group by using modelviewset
I know we can create group by admin panel of django and also can give them permissions. I am trying to create group without django admin panel. I dont want access from django admin for create group. I wish to generate group by api. I searched for it but didn't found anything. Can I create and view group by modelviewset and view them in api . I does this views.py from rest_framework import viewsets from django.contrib.auth.models import Group class UserGroupModelViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = Group urls.py from django.urls import path,include,path from .views import UserGroupModelViewSet from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register('', UserGroupModelViewSet) urlpatterns = [ path('',include(router.urls)), ] How can I create and view the list of groups I created by django admin -
Wagtail removes the accented chars but should maintain it
I'm working with Wagtail in a project in PT-BR and when I'm typing characters like an ã or an é they're removed from the RichTextBlock of a StreamField. Until here I've tried to add the pt-br langague in WAGTAIL_CONTENT_LANGUAGES and LANGUAGES of settings.py but the problem remains. PS: When I'm using TextField the problem doesn't occurs. Gif of problem -
django factory boy: How to create dummy data with imagefield
I have the following model class Test(models.Model): photo = models.ImageField( upload_to="profile_pics", default="profile_pics/blank-avatar.png" ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) How to add random images to photo using factory boy -
incorporate other py files in django views and render in html
I am new to working with django as a local server. Thus I don't get the logic. How do I incorporate my own customfile.py files in the views? How can I include them to have the results from the customfile1-calculations outputted to the views and rendered in the index.html? Let's say I have: project1 -app1 --views.py --customfile1.py ---templates\app1\index.html How and what do I need to change in the views.py or perhaps somewhere else, too? I don't want to have the whole logic of the whole app written in the views.py adn rather separated into sub-files. -
Django: I'm trying to save ip address in field by logging in user, after I go to check if this has been added in the admin page but this remains empty
I've extend the User standard model to add an ip field (it works), after that when trying login an user it works but when i check in admin page the ip address field is still empty, the ip address is not saved admin.py class IpaddressInline(admin.StackedInline): model = IpAddress can_delete = False verbose_name_plural ="ipaddress" class UserAdmin(BaseUserAdmin): inlines = (IpaddressInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) In models.py class IpAddress(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, null=True, blank=True) ip = models.GenericIPAddressField() This is my login forms class AuthenticationForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password,) if not user: raise forms.ValidationError('Wrong username or password') return super(AuthenticationForm,self).clean(*args, **kwargs) The view def login(request): context = {} form = AuthenticationForm(request.POST) if request.POST: if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') ip_address = request.META.get('HTTP_X_FORWARDED_FOR') if ip_address : ipaddress = ip_address.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') get_ip = IpAddress() get_ip.user = request.user get_ip.ip = ipaddress user = authenticate(username=username, password=password, ip=ipaddress) get_ip.user.save()# login(request, user) return render(request, 'bloggo/Dashboard.html', context) return render(request, 'bloggo/Login_form.html', {'form': form}) -
Check Django Custom permissions from react
It's my first time creating a project with Django in the backend and React frontend. I have a custom user model with boolean fields as is_moderator & is_admin & is_poster. In the frontend, there's a certain button that should only be visible to admins and moderators. So my question is how to make that button only visible to them, I made Django custom permission like that class IsModerator(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True def has_object_permission(self, request, view, obj): if request.user.is_moderator: return True if request.user.is_admin: return True return False and add it to the view. In that case, it is available to all kinds of users so when normal users other than moderators and admin click the button it will display an error in the console, to avoid that error I made a condition in the react component checking if the user is logged in and is admin or moderator then display the button, otherwise don't display it, but by that condition, there's no point of the custom permission. Is there a better way to achieve it? -
Django Test Client sends values as a list instead of strings
I have a problem, I am not sure whether I had overlooked something, or simply doing something wrong. I am trying to test an endpoint that allows a user to register. My model: class Account(User): objects = UserManager() balance = models.FloatField(blank=True, default=0) rank_position = models.IntegerField(blank=True, null=True) rank_title = models.CharField(max_length=255, blank=True, default="Novice") Serializer: class AccountSerializer(ModelSerializer): class Meta: model = Account fields = '__all__ View: @api_view(['POST']) def register(request): try: acc = Account.objects.create(**request.POST) acc_srl = AccountSerializer(acc) return Response(data=acc_srl.data, status=status.HTTP_201_CREATED) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) And I am trying to use a Django test client in a following way: class TestAuthentication(TestCase): def setUp(self): self.c = Client() def test_register(self): data = {'username': 'test_user', 'password': '1234'} response = self.c.post('/api/register/', data) print(response.json()) self.assertEqual(response.status_code, 201) acc = Account.objects.get(username="test_user") self.assertEqual(acc.username, "test_user") self.assertTrue(isinstance(acc, User)) The function works as expected, but a strange thing happens. When I inspect request.POST both username and password are a list as so: <QueryDict: {'username': ['test_user'], 'password': ['1234']}> I am puzzled as I dont understand what causes this behavior. -
get column name and values from cursor query in django
'''def getMessageDetails(table, phone_number_rec): sql = "SELECT customer_id , org_id , business_unit_id , campaign_id FROM messages where (case when length(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '')) = 11 then concat('+', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') ) when length(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '')) = 10 then concat('+1',REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') ) when length(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '')) = 12 and REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') like '%-%' then concat('+1', substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', ''), 1, 3), substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', ''), 5, 3), substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', ''), 9, 4)) else REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') end) ='" + phone_number_rec + "' order by created_on desc limit 1" print(sql) with connection.cursor() as cursor: cursor.execute(sql) row = cursor.fetchall() if row != '': response_data = {'status': 'Success', 'data': list(row)} else: response_data = {'status': 'Fail', 'message': 'Data not found.'} return response_data''' 1.try to get columm name and values 2.its same query work in php but in django dont return columm name 3.phone_no is maddotary -
Python - Django - Input validation
How can I make a validation for post fetch input? I manually validate is first digit has empty space or isalnum for update operation as below but I wonder is there better approach? def update_user_meta(request): if request.method == "POST": name = request.POST.get("name") if name is not None and name[0:1].isalnum() == True: selectedUser.name = name else: selectedUser.name = selectedUser.name -
Django: Download file as background task in client's machine
I have a working file download example that works fine: def download_file_view(request): output = download_file() response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename=file.xlsx' return response def download_file(): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() worksheet.write(0, 0, 'something') workbook.close() output.seek(0) return output But now I want the download process to continue as a background task. I did something with threading.Thread, but the download doesn't occur: def download_file_background_view(request): t = threading.Thread(target=download_file_background) t.setDaemon(True) t.start() return redirect('/') def download_file_background(): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() worksheet.write(0, 0, 'something') workbook.close() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename=file.xlsx' return response Can somebody help me how to trigger the download process in the background and let the user do other things in the web? -
Server Error (500) in django admin in particularly one model
I'm getting Server Error (500) particularly in one model in the admin page. The rest are all opening fine. Any idea what could be causing this issue . -
Run django server with poetry
I have installed Poetry in my computer and now trying to run my django server with it. As there were changes in the poetry I run poetry shell and then python manage.py runserver This raises the following error: Traceback (most recent call last): File "manage.py", line 13, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 24, in <module> main() File "manage.py", line 19, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I'm assuming that my virtual environment is already running by executing the first command and so far (without using any virtual environment) haven't had any problem with my Django, so I would say it is properly installed and available. Can you see my what may cause this issue? -
django - imbedding variables within tags
Using pycharm Django. I’m passing a dictionary "myDict" “{'id': 1, 'abvName': 'xyz', 'Name': 'ABCDEF'}”. I would like to use a template statement which requires the id value as follows: Get id Rec But apparently, I can’t imbed a tag or a variable within a tag. I can pass the id separately from views.py but maybe I’m missing a better way to do this accessing the dictionary. -
Can I download source code which has deployed with github from Heroku?
I have deployed my django-app on heroku with Github. It is test server so I am using sqlitedb. But because of the dyno manager, my sqlitedb resets everyday. So I am going to download only db on heroku. I tried this command. heroku git:clone -a APP-NAME But this clones empty repository. And when I run heroku bash run command, I got ETIMEOUT error. Is there any other way to download the source code on heroku? -
Django makemigrations always create RemoveIndex operation, but I can't migrate them
So, I don't know how I got into this looping situation honestly. I think awhile ago I might have done some manual operation on my DB with index, or even through django itself...but the current scenario now is that django is detecting changes need to be applied. When I run makemigrations, what it does is to create the same RemoveIndex operations: Migrations for 'metrics': metrics/migrations/0003_auto_20211012_0918.py - Remove index metrics_eve_session_527503_idx from event - Remove index metrics_ses_user_id_4cfc6b_idx from session - Remove index metrics_ses_trainin_9122a5_idx from session - Remove index metrics_tra_course__643338_idx from training Here is the migration generated: class Migration(migrations.Migration): dependencies = [ ('metrics', '0002_auto_20211012_0900'), ] operations = [ migrations.RemoveIndex( model_name='event', name='metrics_eve_session_527503_idx', ), migrations.RemoveIndex( model_name='session', name='metrics_ses_user_id_4cfc6b_idx', ), migrations.RemoveIndex( model_name='session', name='metrics_ses_trainin_9122a5_idx', ), migrations.RemoveIndex( model_name='training', name='metrics_tra_course__643338_idx', ), ] If I try to migrate I get: django.db.utils.OperationalError: (1091, "Can't DROP 'metrics_eve_session_527503_idx'; check that column/key exists") Guess the indexes already have been removed, but then from where django is detecting this instruction from my models? I tried adding db_index=True to these specific fields in those models to see if it forcing to create the index would help, but no success. Here is a screenshot of these table structures regarding index: metrics_training session event Question is: how do I … -
Annotate sum is doubling value
The annotate sum is doubling the value. please have a look at this code. order_list_cases = order_list.values('user_id', 'shipped_address__name', 'shipped_address__phone', 'shipped_address__pincode__district__district_name','invoice__original_amount',)\ .annotate(dcount=Count('user_id'), customer_paid_sum=Coalesce(Sum('invoice__transaction_invoice__transaction_amount'), Value(0)), customer_gross_sum=Sum('invoice__original_amount')-Sum('invoice__discount_amount')+Sum('invoice__tax_amount')) I need the value of customer gross sum, but the value which I'm getting is double the value of the desired value but not in every case. -
Django quill editor | field name displays inside quill editor widget border in Django admin
I am new to Django + Python. I can't really figure out why my field name get displayed inside the Quill Widget in Django admin. It would be great if someone who already figured out this problem share their solution. Django==3.2.4 | django-quill-editor==0.1.22 My code: # models.py class Post(models.Model): post = QuillField("Post", null=True, blank=True) # admin.py @admin.register(Title) class TitleAdmin(admin.ModelAdmin): pass image of the problem - Sorry, I don't have enough reputation to embed an image. Many thanks,