Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Submitting 2 custom Crispy Forms with 1 button Django
I have 2 forms with the second form referencing the first form. I can get the forms to execute correctly using crispy forms, however, when I customize each form using helper = FormHelper() they will no longer submit together. Essentially one form is submitted and the other form thinks it is missing all of its input data. Forms.py from django.forms import ModelForm, forms from .models import Item, Item_dimensions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column # Create the form class. class List_Item_Form(ModelForm): class Meta: model = Item exclude = ('id','creator','created_on','updated_on' ) helper = FormHelper() helper.layout = Layout( Row( Column('item_name', css_class='form-group col-md-6 mb-0'), Column('price', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), 'short_description', 'description', Row( Column('main_image', css_class='form-group col-md-2.5 mb-0'), Column('image_2', css_class='form-group col-md-2.5 mb-0'), Column('image_3', css_class='form-group col-md-2.5 mb-0'), Column('image_4', css_class='form-group col-md-2.5 mb-0'), Column('image_5', css_class='form-group col-md-2.5 mb-0'), css_class='form-row' ), 'quantity' ) helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) helper.form_method = 'POST' class List_Item_Dimensions(ModelForm): class Meta: model = Item_dimensions exclude = ('id','item_id') helper = FormHelper() helper.layout = Layout( Row( Column('x_dim_mm', css_class='form-group col-md-4 mb-0'), Column('y_dim_mm', css_class='form-group col-md-4 mb-0'), Column('z_dim_mm', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), 'weight_grams', Submit('submit', 'add_listing') ) helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) helper.form_method = 'POST' I have tried removing helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) and using just one submit button but … -
How to give access for a model object to a specific user in Django
I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to design this as the teacher who creates a class only he can see this after login another teacher shouldn't see his classes and how to add students into that particular class I created the course model class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): form.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) forms.py from django import forms from .models import course class add_course(forms.ModelForm): class Meta: model = course fields = ('course_name', 'course_id', 'course_sec', 'classroom_id') -
Django: How do I check if a User has already read/seen an article?
I am building a web-application for my senior design project with Python and Django. I have a user model that is able to read/write articles to display on the website. I want to make it so that if an article is accessed (read) by a user, it is indicated for only that user that the article has been previously accessed. If I were to log into a brand new user account, the same article wouldn't be indicated as "accessed" for the new account. How can I go about implementing this? Below are my models and views User model class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True, max_length=255, blank=False) university = models.CharField(max_length=200, null=True, blank=True) newsletter_subscriber = models.BooleanField(default=False) is_email_verified = models.BooleanField(default=False) is_staff = models.BooleanField( default=False, help_text=( 'Designates whether the user can log into ' 'this admin site.' ), ) is_active = models.BooleanField( default=True, help_text=( 'Designates whether this user should be ' 'treated as active. Unselect this instead ' 'of deleting accounts.' ), ) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email Article model class Article(models.Model): user = models.ForeignKey( User, on_delete=models.DO_NOTHING, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=False) author = models.CharField(max_length=200, null=True, … -
How can I sum up and display a model method field and also display it on the dashboard without looping through the template in Django
How can I sum up and display a model method field and also display it on the dashboard without looping through the template in Django. I aim to display two values on my dashboard. Total Invested and total Earned. I am able to display total Invested by using the code below. My view investments = Investment.objects.all() total_invested = Investment.objects.aggregate( total_invested=Sum('amount_deposited ')) context = { 'investments': investments, 'total_invested': total_invested, } return render(request, 'list-investments.html', context)``` Then displaying it in my template ```{{total_invested.total_invested}}``` Note: I didnt use **for loop** in my template but I was able to get the total sum invested. I tried repeating the same procedure to get the total amount earned but Its not working. Any idea how to go about it? I also want to know how I can save these model methods values in the database. **My Model Class** ```class Investment(models.Model): PLAN_CHOICES = ( ("Basic - 4% - max 6", "Basic - 4% - max 6"), ("Premium - 5% - max 12", "Premium - 5% - max 12"), ) plan = models.CharField(max_length=50, choices=PLAN_CHOICES, null=True) duration = models.IntegerField(max_length=50, null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) active_investment = models.BooleanField(default=True) amount_deposited = models.IntegerField(null=True) def __str__(self): return self.plan def basic_profit(self): self.basic_pro = … -
How to "open" locked terminal when Django server is running on VSCode?
I am trying to do this Django tutorial and came a cross problem where I cannot write to terminal when Django server is running. Here is excact spot on tutorial: https://youtu.be/uhSmgR1hEwg?list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&t=552 Tuotorial teacher clearly presses some hotkey to "enable" writing to terminal (that reveals PC: C:\Users... line). But what might that hotkey be? -
How to create individual id's per model per user account [Django]
I have come across an issue where everytime a different account that is logged in creates a new collection, the id for that collection is id '1' (127:0.0.1/collections/1), but when you log into another account the and that user creates a new collection, the collection id is '2' (127:0.0.1/collections/2) when I want that one to start as a id = 1. I want each user to have their own ID when creating collections. Same goes for the items inside of the collection. It's like all users on the website are sharing ID's. I wasn't sure what exactly it is I should search up online so I was unable to find any suggestions. Also I am using a built-in user profile instead of a custom one. Any resources or ideas would be great. My Django version is 4.0.3 Models.py class Collection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="collection", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Input(models.Model): name = models.ForeignKey(Collection, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text views.py def create(response): if response.user.is_authenticated: username = response.user.username if response.method == "POST": form = NewInput(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = Collection(name=n) t.save() response.user.collection.add(t) return HttpResponseRedirect("/collections/%s" % username) else: form … -
What in this python program can make my memory goes to sky and freeze the program?
I have written a python program that connect to my mqtt server and process the data! BUt the memory start very low and get higher and higher over time! I would says pretty fast like in 2 hours it goes from ~20% to ~80% if i don't restat the process, it will just hang and stop the program. It does over a week i am looking at the code searching for my errors trying different things and nothings seems to fix the problem!! This code is where i am at now! Thanx a lot! #!/usr/bin/python from __future__ import unicode_literals import os, sys, django, json, time, datetime, socket, _thread, multiprocessing, queue import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import django.db BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) #here store is root folder(means parent). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "EraIoT.settings") django.setup() from vac300s.models import vac300, vac300Stat from vac200sV1.models import vac200V1 from shared.utils import * mqtt.Client.connected_flag = False clear = lambda: os.system('clear') messagesReceivedQ = queue.Queue() messagesQueuedQ = queue.Queue() activeThreadQ = queue.Queue() processingTimeQ = queue.Queue() processingTimeMysqlQ = queue.Queue() processingTimeMemcachedQ = queue.Queue() processedRequestQ = queue.Queue() topics = ["data/vac300s/#", "message/vac300s/#", "alarm/vac300s/#"] q = queue.Queue() def on_disconnect(mqttc, userdata, rc): print("*****************************************") print("Disconnected from MQTT server:") print(str(rc)) print("*****************************************") mqttc.connected_flag = False def on_connect(mqttc, obj, flags, … -
Populate/filter one <select> with another <select>
I have a form to create projects in my app. In this form the user must select a client in a and then a farm in another . How do I when selecting a client, the next only offers options from farms that are from the selected customer? I believe it's impossible to do this with just Django, am I right? simplified models.py class Project(models.Model): farm = models.ManyToManyField(Farm, related_name='farm_name',verbose_name='Propriedade beneficiada') client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='project_client',default=None,null=True, verbose_name='Cliente') class Farm(models.Model): client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='client', null=True, default=None) name = models.CharField(max_length=100, verbose_name='Nome') forms.py class NewProjectForm(ModelForm): class Meta: model = Project fields = ['owner','farm','warranty','modal','harvest_year','culture','value','final_date'] def __init__(self, *args,**kwargs): super(NewProjectForm, self).__init__(*args,**kwargs) self.fields['value'].required = False self.fields['final_date'].required = False self.fields['owner'].queryset = Owner.objects.all().order_by('name') farm_query = Farm.objects.all().order_by('name') self.fields['farm'].queryset = farm_query self.fields['warranty'].queryset = farm_query self.fields['final_date'].widget.attrs['data-mask'] = "00/00/0000" for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' -
H14 Error regarding favicon when deploying Django app to Heroku
Attempting to deploy my Django web application to Heroku. This is the first time I have ever deployed the app on Heroku however the app works as expected when running at localhost:8000. I have followed the documentation and can confirm the presense of 'Procfile' in the root directory of the app. The contents of Procfile are as follows: web: gunicorn my_app.wsgi This is consistent with the name of the app as referened everywhere in the project directory/folders. The 'requirements.txt' file is also present, with the necessary dependencies stated within it. When I deploy the app I get a success message as illustrated below. Yet, when I navigate in the browser to the url I see this... If I then consult the logs using the commmand heroku logs --tail --app myapp I see the following at=error code=H14 desc="No web processes running" method=GET path="/" host=myapp.herokuapp.com request_id=[REDACTED] fwd="51.9.111.101" dyno= connect= service= status=503 bytes= protocol=https 2022-03-19T19:07:35.123190+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=[REDACTED] fwd="51.9.111.101" dyno= connect= service= status=503 bytes= protocol=https Further investigaton leads me to believe that that there are currently no dynos assigned to the app, so I then attempt to spin up some resources using the following command … -
Real time chat application with Django Channels
My real time chat application refuses to send message. no errors at all. I have tried tracing the errors by logging to the console at every stage passed and also tried printing to the terminal. I think the problem might be from consumers.py here is my consummers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_name, self.channel_name, ) await self.accept() async def disconnect(self): print('\nOguh... disconnecting\n') await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def recieve(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] print('\nOguh... recieving a message\n') await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username, 'room': room } ) async def chat_message(self, event): print('\nOguh... Chat message\n') message = event['message'] username = event['username'] room = event['room'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'room': room, })) Here is my room.html: {% extends 'core/base.html' %} {% block tittle %} {{ room.name }} | {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-3xl lg:text-6xl text-white">{{ room.name }}</h1> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id='chat-messages'> <div class="p-4 bg-gray-200 rounded-xl"> <p class='front-semibold'>Username</p> <p> A sample … -
django image form does not save image
hey i got a issue with saving image. when i use the admin side it works well, but when i add a employee with frontend form it save evrything exept the image. <form id="form" method="POST" action="{% url 'addForm' %}" enctype="multipart/form-data" > {% csrf_token %} {{form | crispy}} <input type="submit" name="submit" value="submit" > </form> def index(request): employe = Employe.objects.all() form = EmployeForm teamFilter = Employe_Filter(request.GET, queryset=employe) employe = teamFilter.qs count = employe.count() context = { 'employe': employe, 'form': form, 'teamFilter': teamFilter, 'count': count } return render(request, 'managements/index.html', context) class EmployeForm(forms.ModelForm): class Meta: model = Employe fields = '__all__' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
Why 'pip' stopped working even though it was working fine before?
I am a bit new to programming and have been learning for a few weeks now. I am following Corey Schafer basic python videos and in the middle of his Django Series. To run the server, I run a virtual env. In cmd (in the project directory) I type: 1-pip shell 2-python manage.py runserver The server runs and I work on the project. Not Today. When I wrote pip shell, it gave me an error that: 'pip' is not recognized as an internal or external command, operable program or batch file. enter image description here I reinstalled Python after uninstalling it. pip is installed on my system. I added a new variable from the python folder (scripts) in my system. I did not work and it's still showing me the same error. -
Django Streaming
I just started with django and I want to make a spotify clone. I want to make it so then when you click on an album it shows the songs for that album. this is my models.py from django.db import models class album(models.Model): title = models.CharField(max_length=50) artist = models.IntegerField() genre = models.CharField(max_length=20) id = models.AutoField(primary_key=True) artwork = models.CharField(max_length=1000) class artist(models.Model): name = models.CharField(max_length=50) id = models.AutoField(primary_key=True) class song(models.Model): name = models.CharField(max_length=60) artist = models.IntegerField() album = models.IntegerField() id = models.AutoField(primary_key=True) This is my views.py from django.shortcuts import render from .models import album, song def home(request): context = { 'albums': album.objects.all(), } return render(request, 'main/index.html', context) Thank You -
StaticLiveServerTestCase with Selenium: ERR_CONNECTION_REFUSED
I'm running the default snippet from the docs for testing with selenium but 'm using Chrome driver. When I run the tests using python manage.py test it can't connect to the server seems it won't start, throwing the error ::ERR_CONNECTION_REFUSED. Any ideas? Here is the snippet: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver class MySeleniumTests(StaticLiveServerTestCase): # fixtures = ['user-data.json'] @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = webdriver.Chrome(executable_path='./chromedriver') cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_login(self): self.selenium.get('http://localhost:8000/accounts/login') -
Django: How to autopopulate foreign key with the corresponding model class instance
Working on my first Django project and could use some help. I have 2 models (Decisions, Votes) linked by the foreign key called 'decision'. The template, vote_list.html, shows the user a list of decisions (generated by other users) that are contained in Decisions. The user taps a particular decision and is re-directed to a second template to vote on options pertaining to that decision. How do I autopopulate the foreign key 'decision' in Votes with the corresponding instance of Decision so that the second template, vote_form.html, displays the options for the decision they tapped on? I assume it's coded in views.py (I commented an attempt below that doesn't work), but how might it be done? Thank you! urls.py path('vote-list/', views.VoterView.as_view(), name='vote_list'), path('vote-list/<pk>/vote-form/', views.VoteForm.as_view(), name='vote_form'), models.py class Decisions(models.Model): custom_user = models.ForeignKey(CustomUser, default=None, null=True, on_delete=models.SET_NULL) description = models.CharField(default="", max_length=100, verbose_name="Decision Summary") class Votes(models.Model): decision = models.ForeignKey(Decisions, default=None, null=True, on_delete=models.SET_NULL) vote = models.CharField(default="", max_length=100, verbose_name="Your vote") views.py class VoteForm(LoginRequiredMixin, CreateView): model = Votes form_class = VotingForm template_name = 'users/vote_form.html' def post(self, request, *args, **kwargs): super() form = self.form_class(data=request.POST) if form.is_valid(): instance = form.save(commit=False) # instance.decision = Decisions.description instance.save() return redirect('users:vote_list') forms.py class VotingForm(forms.ModelForm): class Meta: model = Votes fields = ['vote'] vote_list.html {% … -
Django Related model 'vendor.newuser' cannot be resolved
NewUser app in the settings.py ALLOWED_HOSTS = [] LOGIN_URL ='login' LOGIN_REDIRECT_URL ='vendor_admin' LOGOUT_REDIRECT_URL ='home' AUTH_USER_MODEL = 'vendor.NewUser' models.py its only the app and also dont pay attetin to the (-() its just diffren languge class NewUser(AbstractBaseUser,PermissionsMixin): email = models.EmailField(_('ایمیل'),max_length=255,unique=True) username = models.CharField(_('نام کاربری'),max_length=255, unique=True) realstate= models.CharField(_('نام املاک'),max_length=80) date_joined= models.DateTimeField(_('تاریخ ثبت نام'),auto_now_add=True) last_login = models.DateTimeField(_('اخرین_ورود'), auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_pic = models.ImageField(_('عکس پروفایل'),max_length=255 ,upload_to=get_profile_image_filepath,null=True ,blank=True, default=get_default_profile_image) objects = CustomAccountManger() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] def __str__(self): return self.username def get_profile_image_filenames(self): return str(self.profile_pic)[str(self.profile_pic).index(f'uploads/{self.pk})/'):] this happens when i try to migrate -
Local and heroku database out of sync (Django/Heroku)
I have been having challenges with my migrations from local to heroku. It appears that the schemas are out of sync. Here is my local database schema from python manage.py showmigrations account [X] 0001_initial [X] 0002_email_max_length admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique socialaccount [X] 0001_initial [X] 0002_token_max_lengths [X] 0003_extra_data_default_dict testingland [X] 0001_initial Here is the heroku schemas from heroku run python manage.py showmigrations account [X] 0001_initial [X] 0002_email_max_length admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique socialaccount [X] 0001_initial [X] 0002_token_max_lengths [X] 0003_extra_data_default_dict I believe the problem stems from deleting the migrations folder in my testingland app earlier. I ran python3 manage.py makemigrations testingland and the migrations folder came back but when I run: python manage.py makemigrations git commit -a git push heroku main … -
Overwrite django rest default validation errors handler
I am using django-rest for my back-end and want to overwrite default errors for fields. My current code looks like this. class DeckSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( "id", "title", "get_absolute_url", "description", "price", "image", "category_id", "category", "title" ) extra_kwargs = { 'title': {"error_messages": {"required": "Title cannot be empty"}}, 'image': {"error_messages": {"required": "Image cannot be empty"},} } After writing these 2 kwargs i realised i would just be repeating something that could be solved by code. By default the serializer validation returns this when the field is missing {title:"This field is required"}. Is there any way that i can overwrite the current message so it can display directly the name_of_the_field + my_message . Example {title: Title is required} I am not looking on how to write custom error message for a single field , im looking on how to write generic costum messages for every field that for example is missing or null. -
Object has no attribute for Django Foreign key reverse lookup
I have a many to one relationship between Ticket and Project. I am trying to reverse lookup to see all the tickets that belong to a specific project. class Project(models.Model): title = models.CharField(max_length=100, blank=False) description = models.TextField(default='', blank=False) created_on = models.CharField(max_length=20, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='created_by') assigned_users = models.ManyToManyField(User, related_name='assigned_users') def __str__(self): return self.title class Ticket(models.Model): PRIORITY_CHOICES = [ ('Urgent', 'Urgent'), ('High', 'High'), ('Medium', 'Medium'), ('Low', 'Low') ] title = models.CharField(max_length=100, blank=True) description = models.TextField(default='', blank=True) created_on = models.CharField(max_length=20, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) priority = models.CharField(max_length=6, choices=PRIORITY_CHOICES, default='low') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tickets', null=True) history = HistoricalRecords() def __str__(self): return self.title If I try to project = Project.objects.get(id=4) print(project.tickets.all()) I get "AttributeError: 'Project' object has no attribute 'tickets'". Any ideas what I'm doing wrong? Thanks -
NoReverseMatch error with unicode characters in the URL
Here's my model: class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published')) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, allow_unicode=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') lead = RichTextField(config_name='lead') body = RichTextUploadingField(config_name='body') created_on = models.DateTimeField(auto_now_add=True) published_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') is_featured = models.BooleanField(default=False, verbose_name='Featured Post') objects = models.Manager() published = PublishedManager() featured = FeaturedManager() class Meta: ordering = ('-published_on',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.slug]) Project's urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), ] and app's urls.py: app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<slug:slug>/', views.PostDetailView.as_view(), name='post_detail'), ] And my views: class PostListView(ListView): model = Post class PostDetailView(DetailView): model = Post Here's the template: {% for post in object_list %} <p><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></p> {% endfor %} And I get this: Reverse for 'post_detail' with arguments '('فایل-gitignore-برای-پروژههای-جنگو',)' not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] when browsing blog/. What I'm missing here? It's in the early stage of the development and first time I'm working with unicode characters in the slug. It's Django 4.0.3. -
Changing the format of a field depending on another fiel in the same model
Using Django I'm trying to change the format of a field depending on another field in the same model. I have a group of persons who give me a detail which could be in two different formats: time, or decimal. I would like to have all the results in the same table. Is that possible? This is what I tried in models.py: class Time_manager(models.Manager): def get_queryset(self): return super().get_queryset().filter(result_format='T') class Kilo_manager(models.Manager): def get_queryset(self): return super().get_queryset().filter(result_format='K') class Guest(models.Model): name = models.CharField(max_length=30) result_format=models.CharField(max_length=5, default="K") result= models.DecimalField(max_digits=6,decimal_places=2) class Guest_time(Guest): objects=Time_manager() class Meta: proxy = True def formato_resultado(self): self.resultado=models.DurationField() But when I try to add a new Guest_time I'm not able to do it. I get an error asking me to introduce a decimal data. Is there a way of doing this using the same table? -
How to download generated python docx file using Ajax
I need to get some data from my template and send it back to my Django function using ajax, create a docx file and download it Django Function def download_docx_file(request): if request.method == 'GET': language = request.GET['lang'] data = request.GET['data'] converter = {'data': 'This is the real data'} document = Document() document.add_heading(f'{language} -- {converter[data]}', 0) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response return HttpResponse("hello") AJAX $("#dwnBtn").click(function(){ $.ajax({ url : "docx/", type:"GET", data : { lang : 'lang', data:'data' }, success : function(data){ console.log(data) } }) }); I am getting sth like the below response from AJAX response: Response console.log(data) �ܝBp��݂�;|C�ھ�w������=O���]]�%�N�����#+�reup����������Y������̉�J����3)� O��C����F�M�P�&�����rA�@��7T.��z(%h��x�x0�0Z�-i��%q�e�M�����i�"�c��-/��j��齔/ļL瞄�0� �� >�o��[��6 멆�n��s�$� �#>˘ '��wT�� ���3�36DK�+�̓�t6 ��r��sA:���x�<>n������'U��RLqA+���ݺ�BM��:4ĞP�}���:�}ߣP����?F)�9-�W0���2�{x��#2v8N.$V�>X=/�+�c}���ּ�\y���*�J\�� ���90�T�L� 3p���*Sfj(���PWWz��O�s�9]&����iO|�9�;�5��ʘdW�cl% �%;����u���%[�5������Q]$��[L>���yXg�9��2+&,iFs�Q�����u�.�E(�>W��+��M ؟E������i|���k�k�c蟴CcG�j��4s|x �F1�}��Y��,29�0M=-O����m\L��y��^On^���\���u��a���F9:zc�Sy�-�g��fu�n�C�T:{ ��4&/ ��LM9�98� �&Pnc�!��m�r�~��)74�04��0�0������M�~"��.ikjG��M� how can I save this binary data as a .docx file? Thank you in advance -
Django regex start with 3 characters followed by digits
I'm trying to have a regex in djagno form to match 3 characters followed by 3 digits : XXX000 here's what I did so far : validator import re def number_code_validator(value): if not re.compile(r'^[a-zA-Z]{3}.*[0-9]{3}').match(value): raise ValidationError('Organization key format : XXX000.') form field key= forms.CharField( required=True, validators=[number_code_validator] ) yet it's not working and it accepts any value, is there something wrong with the regex ? thanks -
Django web app not work on AWS, There is a ERROR=TemplateDoesNotExist and {% extends 'index2.html' %} not working
My web app work on local server but it is not working on AWS. 1 {% extends 'index2.html' %} 2 3 {% load static %} 4 5 {% block title %} Who am I? {% endblock %} 6 {% block content %} 7 8 9 10 <section class="space-sm mt-3"> 11 <div class="container"> I am sorry it my first questioan, how can i solve this problem? -
Django - request to database Postgres (inside Django code)
Where exactly inside the Django code is the execution of a query to the postgres database? Can someone show me and explain? When I use debug, I see several database queries (in the postgres docker logs), but I know that the actual query is one (the last one). And there is no way I can catch the line of code inside Django that makes the actual request. If you can show me the script and function/method, thanks!