Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use Django admin panel as the only view for the admin of the site not for developer?
I am creating an E-Learning system (similar to Udemy) where I have instructors, students and admins. I was thinking to create a panel for each one of these stakeholders. My question is, can I use Django's admin panel, where I need this panel to block users and block a course and so on? Thank you. -
l'utilisation d'un channels_layer dans un models django [closed]
hello I want to communicate my Notification class with my websocket so that I register a new instance of the notification object that I can retrieve a message via my websocket unfortunately my code does not work as I expected Class notification here my : class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) notification = models.TextField(max_length=300) is_seen = models.BooleanField(default=False) def __str__(self): string = f'{self.user} ({self.notification}): {"False" if self.is_seen is False else"True"}' return string def save(self, force_insert=False, force_update=False, using=None, update_fields=None): channel_layer = get_channel_layer() notification_count = Notification.objects.filter(is_seen=False).count() data = {'count': notification_count, 'courrent_notification': self.notification} async_to_sync(channel_layer.group_send)( 'notification_groupe', { 'type': 'disconnect', 'value': json.dumps(data)}) super(Notification, self).save() my model consumer: class Notification_consumer(WebsocketConsumer): def connect(self): self.room_group_name = 'notification_groupe' self.room_name = 'notification_consumer' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.room_name ) self.accept() self.send(json.dumps({"status": "connected to notification consumer!"})) def receive(self, text_data=None, bytes_data=None): print(text_data) self.send(json.dumps({"status": "notification consumer a votre service"})) def send_notification(self, event): print('send_notification') print(event) print('send_notification') def disconnect(self, code): self.send(json.dumps({"status": "déconnexion effectuée!"})) print('déconnecxion') -
How can i load .tar and do predictions in django
I am building a web application to make predictions using PyTorch. I have trained a model and saved the model weights in the .tar file and now I want to load the model and do predictions in Django how can I do it. need help I am attaching my prediction code below def predicting(model, device, loader): model.eval() total_preds = torch.Tensor() total_labels = torch.Tensor() print('Make prediction for {} samples...'.format(len(loader.dataset))) with torch.no_grad(): for solute_graphs, solvent_graphs, solute_lens, solvent_lens in tqdm(loader): outputs, i_map = model( [solute_graphs.to(device), solvent_graphs.to(device), torch.tensor(solute_lens).to(device), torch.tensor(solvent_lens).to(device)]) total_preds = torch.cat((total_preds, outputs.cpu()), 0) # total_labels = torch.cat((total_labels, data.y.view(-1, 1).cpu()), 0) # return total_labels.numpy().flatten(),total_preds.numpy().flatten() return total_preds.numpy().flatten() -
Django docker-compose-prod isn't work correctly
I'm trying to prep a Django application for production. I created an alternate docker-compose YML file where I specify DEBUG=False. However when I run the Django check for deployment, it says that DEBUG is set to True. $ docker-compose down $ docker-compose -f docker-compose-prod.yml up -d --build $ docker-compose exec web python manage.py check --deploy but in local server it is worked(I mean the debug is Turn off) How can I fix it? -
How to use reverse with optional parameters in django?
I have the below URL in which I pass an integer value (pk) now when I am calling reverse on this URL I am getting the below-mentioned error. urls.py urlpatterns = [ path('batch-postpone/<int:pk>/', postpone_batch, name='batch-postpone'), ] tests.py class ABCTestCases(APITestCase, TestCase): self.postpone_batch_url = reverse('batch-postpone') Error that I am getting... django.urls.exceptions.NoReverseMatch: Reverse for 'batch-postpone' with no arguments not found. 1 pattern(s) tried: ['batch\\-postpone/(?P<pk>[0-9]+)/$'] -
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?