Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import posts from Wordpress to Wagtail 2 (Draftail editor) including images?
I'm trying to import posts from Wordpress to Wagtail including images. I'm conscious about the fact that Draftail editor saves images with a dedicated tag, ex: <embed alt="fonctionnement-pim-schema-640.png" embedtype="image" format="fullwidth" id="412" /> When I import my posts from Wordpress, I convert img tags to embed tags. Bellow a snippet of my code: resp = requests.get(img["src"], stream=True) if resp.status_code != requests.codes.ok: print("Unable to import " + img["src"]) continue fp = BytesIO() fp.write(resp.content) image = Image(title=file_name, width=width, height=height) image.file.save(file_name, File(fp)) image.save() try: embed_id = image.get_rendition("original").id embed_alt = image.get_rendition("original").alt new_tag = soup.new_tag('embed', alt=f'{embed_alt}', embedtype="image", format="fullwidth", id=f'{embed_id}') img.replace_with(new_tag) It seems to work. When I check the database all img tags are replaced with a correctly formatted embed tag and all images are downloaded to the media folder. Unfortunately, when I check the admin area. The embed tag exists but the image is not recognized: When I a use a generic embed tag in my import script (I mean without using "format" but the same embed code for all images) the import is working well (including within Draftail). Could "format" or "f string" introduce something wrong? Any help would be much appreciated! Thank in advance. -
Django-Zappa deployment error: Error: Your app_function value is not a modular path. It needs to be in the format `your_module.your_app_object`
Zappa is not recognizing my django application I am getting this error: error While zappa init, zappa automatically get that its django application while in my case I am getting this: error source Thanks in advance! -
How do i display a ModelForm into HTMLtemplate?
I have a template in which i display a Form for users to upload images. In the same template i want the images uploaded from users to be shown so i can make a gallery from users uploads. The problem is that the Form is being displayed without any problem but i am struggling to display the photos uploaded. (They are uploaded to the Data Base withouh any error too.) My models.py looks like this class categoria(models.Model): nombre = models.CharField(verbose_name = "nombre categoria", max_length = 20) def __str__(self): return self.nombre class imagen(models.Model): titulo = models.CharField(verbose_name = "el titulo de la imagen", max_length = 20) imagen = models.ImageField(verbose_name = "imagen que se suba", upload_to = "galeria") descripcion = models.CharField(verbose_name = "descripcion de la imagen", max_length=60, null = True, blank = True) creada = models.DateTimeField(auto_now_add=True) categorias = models.ManyToManyField(categoria) def __str__(self): return "El titulo es: {}, la imagen: {}, la descripcion: {}, ha sido creada en: {}, y pertenece a las categorias: {}".format(self.titulo, self.imagen, self.descripcion, self.creada, self.categorias) class formulario_img(ModelForm): class Meta: model = imagen fields = ['titulo', 'imagen', 'descripcion', 'categorias'] The view for showing the images looks like this from .models import formulario_img, imagenfrom def imagenes_galeria(request): imagenes = formulario_img.objects.all() return render(request, "galeria/galeria.html", {"imagenes":imagenes}) … -
Django form – sending uploaded files as attachments over email
Basically, the title says it all. This is the code I'm using: documents = self.request.FILES.getlist('my_documents') mail = EmailMessage( 'Subject Line', 'Message Body!', 'from_email', ['to_email'] ) for d in documents: mail.attach(d.name, d.file.read(), d.content_type) mail.send() Sending the email works fine, and I do get the attachments. However, there seems to be a problem with the content of those attachments. Trying to open the files does not work. What am I doing wrong? I suspect it has something to do with the encoding of the second argument of the mail.attach function, but I can't seem to figure it out. Thanks! -
Why am I getting a No Reverse Match Error
HI working on a new site using Django. can't seem to figure this bug out. First the intended site will be structured as; Home page - Showing different languages with links to countries you can learn those languages in. Click on a country on home page -> Country page Country page will list all fo the schools that teach that language in that country. Click on a school on country page -> School page. I figured out this line of code in the Country page is causing the issue, but I don't know how to fix it <a href="{% url 'schools' schools.id %}"> <div class="left"><h4>Test Link</h4></div> </a> This is the error I get in the browser NoReverseMatch at /5/ Reverse for 'schools' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<country_id>[0-9]+)/(?P<schools_id>[0-9]+)/$'] Code from the project: Models.py from django.db import models class Languages(models.Model): language = models.CharField(max_length=100, blank=True, null=True) country = models.ManyToManyField('Country', blank=True) image = models.CharField(max_length=100, blank=True) def __str__(self): return self.language class Country(models.Model): country_name = models.CharField(max_length=50) country_image = models.CharField(max_length=100, blank=True) country_city = models.ManyToManyField('City', blank=True) def __str__(self): return self.country_name class City(models.Model): city_name = models.CharField(max_length=50) city_image = models.CharField(max_length=1000, blank=True) city_schools_in = models.ManyToManyField('Schools', blank=True) def __str__(self): return self.city_name class Schools(models.Model): school_name = models.CharField(max_length=100) school_image = … -
When I send a reset password email, my program closes
The problem : I am setting up the "forgot password" functionality for my website but whenever it is triggered it shuts down the website. (when I hit the "submit" it waits for a while and then shuts down.) I have checked all the code multiple times and I don't understand why you smart people are my last hope! URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), SETTINGS #SMTP Config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*****@gmail.com' EMAIL_HOST_PASSWORD = '********' the command line output that it gives out just before closing: [07/Feb/2021 15:51:31] "GET / HTTP/1.1" 200 25 [07/Feb/2021 15:51:40] "GET /reset_password/ HTTP/1.1" 200 1903 [07/Feb/2021 15:51:50] "POST /reset_password/ HTTP/1.1" 302 0 -
how to deleting extra OrderItems in Orders?
this is my order admin. when a customer reserve a product it goes to order item section in the down. but there are some extra order items that they are empty. i want to when a customer adds a product just that product be in the admin panel. how i can remove that empty order items??? model: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders') ref_code = models.CharField(max_length=20, blank=True, null=True) # products = models.ManyToManyField(OrderItem) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True, blank=True, related_name='addresses') created_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(null=True, blank=True) ordered = models.BooleanField(default=False) def __str__(self): return self.user.full_name class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='products') ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.product.name}" serializer: class OrderItemSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() final_price = serializers.SerializerMethodField() class Meta: model = OrderItem fields = ( 'id', 'product', 'quantity', 'final_price' ) def get_product(self, obj): return ProductSerializer(obj.product).data def get_final_price(self, obj): return obj.get_final_price() class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() total = serializers.SerializerMethodField() class Meta: model = Order fields = ( 'id', 'order_items', 'total', ) def get_order_items(self, obj): return OrderItemSerializer(obj.products.all(), many=True).data def get_total(self, obj): return obj.total_price() -
Not being able to upload image to django project
While I have the images stored into my 'img' file it isn't showing up inside of my virtual environment, I will provide a screenshot of both the images inside of my file plus the virtual environment folder structure. Below is the error message. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/projects/img/todo.png 'projects\img\todo.png' could not be found You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Django problems with static files on AWS S3 Bucket
I have a very weird situation with my Django Website. I put all my static and media files on an Amazon S3 bucket. The media folder is for profile, blog pictures and the static folder holds, all the css, js, img, scss etc. Everything is working fine except that the website is loading properly just when I use Safari, in Chrome it doesn't load my tags which have bootstrap classes for images and on firefox id doesn't load the tags and the js as well. The js is rendering my charts. What could be the problem. I'll put my cod configuration for AWS S3 and a screenshot from Safari, Chrome and Firefox. settings.py AWS_ACCESS_KEY_ID = aws_access_key_id AWS_SECRET_ACCESS_KEY = aws_secret_access_key AWS_STORAGE_BUCKET_NAME = aws_storage_bucket_name AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'ecomon.storages.MediaStore' storages.py which I use for DEFAULT_FILE_STORAGE (media folder): from storages.backends.s3boto3 import S3Boto3Storage class MediaStore(S3Boto3Storage): location = 'media' file_overwrite = False How it's on Safari: How it's on Chrome: How it's on Firefox: In case it's needed, the media folder it's working fine, … -
NoReverseMatch at /alumni/2/alumni_cv/ Reverse for 'alumni_profile' with arguments '('',)' not found
I am facing problem. code in template: alumni_cv.html___ <a href="{% url 'alumni_cv' user.alumniprofile.id %}" class="btn btn-primary btn-block"><b>CV</b></a> When I click this button the above NoReverseMatch at /alumni/2/alumni_cv/ Reverse for 'alumni_profile' with arguments '('',)' not found. 1 pattern(s) tried: ['alumni/alumni_profile/(?P[^/]+)/$'] models.py_____ class AlumniProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) phone = models.CharField(max_length=50) occupation = models.CharField(max_length=50) image = models.ImageField( upload_to='alumni/', null=True, blank=True, default="default_user_avatar.jpg") bio = models.TextField() date_of_birth = models.DateField(null=True, blank=True) district_of_birth = models.ForeignKey( TownCityDistrict, on_delete=models.CASCADE, null=True, blank=True) gender = models.CharField(max_length=20, choices=genders) present_address = models.CharField(max_length=254) permanent_address = models.CharField(max_length=254) blood_group = models.CharField(max_length=10, choices=blood_groups) university_bachelor_session = models.CharField(max_length=50) university_masters_session = models.CharField(max_length=50) university_hall = models.CharField(max_length=100) university_batch = models.CharField(max_length=20) slug = models.SlugField() facebook_url = models.URLField(blank=True, null=True) linkedin_url = models.URLField(blank=True, null=True) instagram_url = models.URLField(blank=True, null=True) twitter_url = models.URLField(blank=True, null=True) skype_id = models.CharField(max_length=100, blank=True, null=True) zoom_id = models.CharField(max_length=100, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) visible_to_public = models.BooleanField(default=True) def __str__(self): return str(self.phone) class Meta: verbose_name_plural = 'Alumni' class AlumniEducation(models.Model): user = models.ForeignKey(AlumniProfile, null=True, on_delete=models.CASCADE) exam = models.CharField( max_length=50, verbose_name='Examination/Degree', blank=True, null=True) exam_year = models.DateField( verbose_name='Examination Year', blank=True, null=True) institute = models.CharField( max_length=100, verbose_name='Institute Name', blank=True, null=True) board_university = models.CharField( max_length=50, verbose_name='Board/University', blank=True, null=True) result = models.CharField( verbose_name='Result/Grade', max_length=20, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) visible_to_public = models.BooleanField(default=True) def … -
Why are my users able to log in despite having is_Active set to false?
I am using abstractbaseuser and baseusermanager. Why are my users able to log in despite having is_Active set to false? I thought that is_active=False by default makes it such that users cannot login? If my undeerstanding is wrong, how can I make it a default? models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=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) objects = MyAccountManager() def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True -
Get Average of Date Range in Django Queryset
I have been beating myself with this for hours and now decided to put my hands up for help. Question: What I would like to show all the records from BBSO_Records which does not have a BBSO_Record_Actions as well as which has a BBSO_Record_Actions(SQL left Join). Then use this queryset to run a date difference on the date_record and today and calcuate the average on this new field. My models are as follows: # MODELS class BBSO_Records(models.Model): date_recorded = models.DateField() details_of_observation = models.TextField() class BBSO_Record_Actions(models.Model): bbso_record_ID = models.ForeignKey(BBSO_Records, on_delete=models.CASCADE, verbose_name="BBSO Record") recommended_action = models.TextField(verbose_name='Recommended Action') date_closed = models.DateField(blank=True, null=True) # views which i am testing is this def open_avg_records(): x = BBSO_Records.objects.filter(bbso_record_actions__date_closed__isnull=True)\ .aggregate(avg_diff=Avg(ExpressionWrapper(F('date_recorded') - date.today(), output_field=DurationField()))) return x.avg_diff if I do a print of x I get the following: {'avg_diff': datetime.timedelta(0)} Any guidance will be greatly appreciated. -
how to implement live page reload with ajax?
i am new to ajax. i created function where you can submit form without reloading the page. and it worked perfectly.but i want to extend it more further in my django ajax app, when i submit the form the template where the form details are stored should also be updated live. when i submit form and to see the post i need to reload the post page. i want to remove that.. basically when i submit form my other templace should update that template live so i don't have to update it add_post.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>hello</h1> <form id="post_form"> {% csrf_token %} <p>name:</p> <input type="text" id="name" name="name"><br> <p>email:</p> <input type="text" id="email" name="email"><br> <p>bio:</p> <input type="text" id="bio" name="bio"><br> <input type="submit"> </form> <script> $(document).on('submit','#post_form',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url:'create/', data:{ name: $('#name').val(), email: $('#email').val(), bio: $('#bio').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ } }); }); </script> </body> </html> views.py def create(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] bio = request.POST['bio'] new_profile =post(name=name,email=email,bio=bio) new_profile.save() success = 'user'+name+'created successfully' return HttpResponse(success) listview is temporary just for testing class posts(ListView): model = post template_name = 'ajax_app/posts.html' postpage.html <html … -
django.db.utils.ProgrammingError: (1146, "Table 'Project.django_apscheduler_djangojob' doesn't exist")
I am learning django-apscheduler on the window system, And used python manage.py showmigrations command in terminal but the result is 'django.db.utils.ProgrammingError: (1146, "Table 'Project.django_apscheduler_djangojob' doesn't exist")' My DB setting DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Product', # 数据库名称, 'HOST': '127.0.0.1', # 主机地址 'USER': 'root', # 数据库用户 'PASSWORD': 'password', # 密码 'PORT': 3306 # mysql的端口默认3306 } } Please help me, Thank you a lot -
Django decorators . Need help to find a solution for class based views
This is the files I'm working on. How do I restrict user to access this page? I want only admin to access this page. I've tried to use the custom decorators but it shows error for class-based-view. I'm a beginner so anyone can help?? views.py class student_register(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/student_register.html' def form_valid(self, form_class): user = form_class.save() # login(self.request, user) return redirect('datapage') forms.py class StudentSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) phone_number = forms.CharField(required=True) semester = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.email = self.cleaned_data.get('email') user.username = self.cleaned_data.get('username') user.password1 = self.cleaned_data.get('password1') user.password2 = self.cleaned_data.get('password2') user.save() student = Student.objects.create(user=user) student.phone_number=self.cleaned_data.get('phone_number') student.semester=self.cleaned_data.get('semester') student.save() return user urls.py urlpatterns = [ path("loginrequest/", views.login_request, name="login"), path("logoutrequest", views.logout_request, name="logout"), path('student_register/', student_register.as_view(), name='student_register'), path('teacher_register/',views.teacher_register.as_view(), name='teacher_register'), ] student_register.html <div class="container my-3"> <div class="form-group"> <h3>Register here!</h3> <br> <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {{ form.media}} <button type="submit" class="btn btn-success">Register</button> </form> </div> -
How can I solve this error with my reverse_lazy function?
I get the following error when using a CreateView: NoReverseMatch at /campus/NG Waverley Central/create Reverse for 'campus_page' with no arguments not found. 1 pattern(s) tried: ['campus/(?P[^/]+)/$'] I suspect is has something to do with the fact that I am passing campusid forward from my CampusPage view, and I do not know how to pass this campusid inside the reverse_lazy function. My urls.py looks as follows: urlpatterns = [ path('<str:campusid>/', views.CampusPage, name='campus_page'), path('login/', auth_views.LoginView.as_view(), name='login'), path('<str:campusid>/create', views.CreateStreamEvent.as_view(),name='create_streamevent'), ] My views.py looks as follows: def CampusPage(request, campusid): campusobj = CampusModel.objects.filter(campus_name=campusid) return render(request, 'campus/campus_page.html',{'campusid':campusid,'campusobj':campusobj}) class CreateStreamEvent(LoginRequiredMixin, CreateView): model = StreamEvent fields = ['title','campus'] template_name = 'campus/create_streamevent.html' success_url = reverse_lazy('campus_page') def form_valid(self, form): form.instance.user = self.request.user super(CreateStreamEvent, self).form_valid(form) return redirect('campus_page') I dont know if it is necessary, but my models.py looks as follows: class CampusModel(models.Model): campus_name = models.CharField(max_length=255, unique=True) description = models.TextField(blank=True,default='') banner = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100,null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.campus_name class StreamEvent(models.Model): title = models.CharField(max_length=255) date_added = models.DateField(auto_now=False, auto_now_add=True) date_published = models.DateField(auto_now=True, auto_now_add=False) campus = models.ForeignKey(CampusModel, on_delete=models.CASCADE) def __str__(self): return self.title class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) streamevent = models.ForeignKey(StreamEvent, on_delete=models.CASCADE,null=True) def __str__(self): return self.title -
Django Rest Framework: setting `'Access-Control-Allow-Origin': '*'` in Response object doesn't do anything
I want only one route in my API to be accessible to all origins, so I've set Access-Control-Allow-Origin: * in the Response returned by the view: from rest_framework.views import APIView class ExampleView(APIView): def get(self, request): return Response("hi", headers={ 'Access-Control-Allow-Origin': '*', }) This works fine when I deploy my code to Heroku, but for some reason it does nothing when I run it locally. Requests just get blocked and I get a 403 forbidden response every time. Also I'm using django-cors-headers CORS_URLS_REGEX for every route that starts with /api/, this shouldn't have anything to do with the above, but mentioning just in case: CORS_URLS_REGEX = r'^/api/.*$' -
AttributeError at /account/delete/testuser1: 'str' object has no attribute 'field'
I am trying to allow users to delete their own account but am faced with the error: AttributeError at /account/delete/testuser1: 'str' object has no attribute 'field' The user is not deleted too. Any idea why? I am trying to make it such that the delete button is in the account page and when i press delete, the user gets deleted and redirected back to the home page Will be nice if you can share how i can create a function to deactivate an account too..is it simply setting is_active = False? html <form action="{% url 'account:delete_account' username=request.user.username %}" method="GET">{% csrf_token %} <a class="btn btn-danger btn-sm deleteaccount ml-3" href="{% url 'account:delete_account' username=request.user.username %}">Delete Account</a> </form> views.py def delete_user(request, username): context = {} if request.method == 'DELETE': try: user = User.objects.get(username=username) user.delete() context['msg'] = 'Bye Bye' except Exception as e: context['msg'] = 'Something went wrong!' else: context['msg'] = 'Request method should be "DELETE"!' return redirect(request, 'HomeFeed/snippets/home.html', context) urls.py path('delete/<username>', delete_user, name='delete_account'), models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) -
django: image data not able to be save to db from form
I'm trying to fix this bug couple of days already. I extended User to have one more Image field, however, the image is not saving into the /media/profile path by itself. If I add an image from the admin panel the image will be shown in the front/user (profile image) as well it will be created into the wanted path /media/profile. I'm assuming my code is wrong where I'm creating user and additionally adding path since if I don't add the path it will look at the root media folder for the image. custom_user = Profile.objects.create(user = user, profile_image= 'profiles/'+today_path+'/'+profile_image) This is my first Django project its almost done, just this bug I'm not able to fix it. I will appreciate any help on how to fix it. Thank you, thank you, thank you! register form: <form action="{% url 'register' %}" method = 'POST'> {% csrf_token %} <div class="form-group"> <label class = 'fntmk color' for="first_name">Name</label> <input type="text" name="first_name" required> </div> <div class="form-group"> <label class = 'fntmk color' for="last_name">Surname</label> <input type="text" name="last_name" required> </div> <div class="form-group"> <label class = 'fntmk color' for="username">Username</label> <input type="text" name="username"required> </div> <div class="form-group"> <label class = 'fntmk color' for="email">Email</label> <input type="email" name="email" required> </div> <div class="form-group"> … -
Pug to django template engine Processor
I work with Django many days. I've been trying to learn node js and express. I introduced with pug. But pug has a many concept like indent have here any framework and library who like django template engine. Example: doctype html html(lang='en') head title Hello, World! body h1 Hello, World! div.remark p Pug rocks! -
pip command not found, virtualenv command not found on mac when installing django
Trying to learn python/django but cant even install django when i do virtualenv . or use the pip command, neither of them work on mac. python -V is 2.7.16, python3 -V is 3.8.2. pip command not found, virtualenv command not found on mac -
Multiple Django Dinja template
My view file context is return render(request, 'trail.html', {'form': form}) and My for loop on template is {% for fieldname in fieldset %}. I want to print form.fieldname. I used {{ form.fieldname }}, {{ form }}.{{fieldname}} and {{ form }}-{{fieldname}} nothing is printing the required field properly I am using {% for fieldname in fieldset%} {{form}}.{{fieldname}} {% endfor %} -
(Django) DataFieldTime always returns 00:00:00.000000
I'm trying to set a created_data and modify_data using datetimefield as follows: enter image description here but I added a value to the database, always return 00:00:00.000000 as follows: enter image description here Why is this? And I'd appreciate it if you could help me figure it out. I searched the web for an hour, but I couldn't find the answer... -
i have two models Chat and Message and how can i order the Chat with the pub_date of Message?
i have a chat and Message Model.How can i sort my Chat with the pub_date of Message example:consider that i am in two chats(A and B): i want that everytime i receive a message from B so that B should be the top of A and when i receive a message from A so that A should be the top of B. this is my models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class Chat(models.Model): DIALOG = 'D' CHAT = 'C' CHAT_TYPE_CHOICES = ( (DIALOG, _('Dialog')), (CHAT, _('Chat')) ) type = models.CharField( _('type'), max_length=1, choices=CHAT_TYPE_CHOICES, default=DIALOG ) members = models.ManyToManyField(User, verbose_name=_("Participant")) def __str__(self): return 'members:[{}] - {}'.format(', '.join(self.members.all().values_list('username', flat=True)),self.type) class Meta: ordering = ['???? by pub_date of message ????'] class Message(models.Model): chat = models.ForeignKey(Chat, verbose_name=_("chat de discussion"),on_delete=models.CASCADE) author = models.ForeignKey(User, verbose_name=_("utilisateur"),on_delete=models.CASCADE) message = models.TextField(_("Message")) pub_date = models.DateTimeField(_('date de creation'), default=timezone.now) is_readed = models.BooleanField(_('Lu'), default=False) class Meta: ordering=['pub_date'] def __str__(self): return self.message how can i implement it.i have spent much time on this.Thanks. -
Django - Can I make choices hidden/invisible in my ChoiceField?
I have several choices from two categories in my ChoiceField - [Red, Green, Blue, 1, 2, 3] In my form I have two boxes with dropdowns. First allows you to select Category - Colors or Numbers. I have ajax call that when you select Colors in first box, second will reload to show only colors and vice versa. But in the first state (when you enter page) second dropdown let's you see all choices (both colors and numbers). I would like it to stay empty or with one temp choice for example - "Please select category first". I am wondering if I can hide them somehow with django or I need to create some kind of second ajax call that will execute each time while user reloads page? Thanks.