Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
showing am pm time in django to show when is morning when is evening
I want to show when a user log-in in my site he show when is Good Morning or When is Good Evening. django template either “good morning or afternoon” depending on time of day. Current template code is : {% if hour < 12 %} morning {% elif hour > 12 %} afternoon {% endif %} -
Django 3 rendering markdown break on newline
I have literally tried all the current markdown rendering libraries for Django (also not so current) Django Markdownify, Django Markdown 2 and Markdown Deux) and all have the same problem as described in this old question: How do I make django's markdown filter transform a carriage return to <br />? basically carriage returns is disregarded on rending. If I do {post.body|markdown|linebreaksbr}} it always results in 2 <p><p>1 line</p><br><br><p>1 line</p><br><br><p>2lines </p><br><br><p>2 lines </p><br><br><p> so my options are either none or 2 BR. I am confident that there is an easy solution for this. I can't believe that none of the Django libraries provides this minimal functionaly. -
How to make it possible to add more than one form for a user
I am having trouble creating a model for user availability I already have something like this models.py class Availability(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) date = models.DateField(null=True) starting_hour = models.TimeField(auto_now_add=False, auto_now=False, null=True) ending_hour = models.TimeField(auto_now=False, auto_now_add=False, null=True) def __str__(self): return str(self.user) When a user tries to add an availability for another day of the week, a message appears that the availability for that user already exists I would appreciate any help -
How to create delete button for deleting a record in django
I am trying to delete a record My views.py file is def AnnouncementDelete(request, pk): announcement = get_object_or_404(Announcement, pk=pk) if request.method=='POST': announcement.delete() return redirect('/') return render(request, 'classroom/announcement_confirm_delete.html') and my html file is {% extends "classroom/base.html" %} {% load crispy_forms_tags %} {% block content %} <form action="{% url 'classroom:AnnouncementDelete' announcement.id %}" method="post"> {% csrf_token %} <input type="submit" value="Delete cat"> </form> {% endblock content%} my url.py file has the pattern url(r'^delete/(?P<pk>[0-9]+)/$', views.AnnouncementDelete, name='AnnouncementDelete'), and the model from where I want to delete the record is class Announcement(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def __str__(self): return self.title when I am trying http://127.0.0.1:8000/classroom/delete/1/ it is giving me the following error NoReverseMatch at /classroom/delete/1/ Reverse for 'AnnouncementDelete' with arguments '('',)' not found. 1 pattern(s) tried: ['classroom/delete/(?P[0-9]+)/$'] Also i am a beginner to django and not very familiar with ```url(r'^delete/(?P<pk>[0-9]+)/$', views.AnnouncementDelete, name='AnnouncementDelete'),``` way. I generally use the ```path`` way. -
Get all items from one model on condition that is in other model
Hi i was snooping around stack but answers are confusing or not working, you can see my models how can I get all OrderItems made by user that have complete=True in Order. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_oredred = models.DateField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) transaction_id = models.CharField(max_length=200, null=True) -
How can I run a Django 3 project with a MySQL server set on a NAS (Synology DS120J) using phpMyAdmin and MariaDB 10?
I appreciate the fact that the topic is quite specific, but I have been struggling to find documentation on such setup. I am working on a Django 3 project using Python 3.9, instead of SQLite3, the application would be using a MySQL server hosted on a Synology DS120J NAS, this is done via phpMyAdmin and MariaDB 10. Basically, my objective is to run the Django 3 application from my PC (Windows 10), and the MySQL server from the NAS. Both are sharing the same local network. Is anyone using a similar setup? If so could you please provide with some guidance? At the moment here is the DATABASES section of the settings.py file from the application: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'gaia', 'USER': 'root', 'PASSWORD': [phpMyAdmin password], 'HOST': '127.0.0.1', 'PORT': '[port number of the MariaDB 10 server on phpMyAdmin]' } } I launch the application using the following command: python manage.py runserver 192.168.0.2:[port number of the NAS]. When doing so, I get the following error message: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (10061)"). I have searched for this error message but didn’t get anything very helpful as I wasn’t sure whether any of the … -
Cannot resolve keyword 'name' into field. Choices are: categoria, categoria_id, detalle_compra,
I don't understand what I'm doing wrong. I am trying to do an autocomplete with the data from the Product table, I don't know what the reason is since I mention the name of the product but toa it as "name". I've done it but I keep getting this error: Cannot resolve keyword 'name' into field. Choices are: categoria, categoria_id, detalle_compra, ... Models class Producto(models.Model): id_producto = models.AutoField(primary_key=True) categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) def __str__(self): return self.nombre def toJSON(self): item = model_to_dict(self) return item class Meta: verbose_name = 'Producto' Views def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'autocomplete': productos = Producto.objects.filter(name__icontains=request.POST['term']) for i in productos: data = [] item = i.toJSON() item['value'] = i.nombre data.append(item) else: JS $("#search").autocomplete({ source: function (request, response) { $.ajax({ url: window.location.pathname, type: 'POST', data: { 'action': 'autocomplete', 'term': request.term }, dataType: 'json', }).done(function (data) { response(data); }).fail(function (data) { alert("Error"); }).always(function (jqXHR, textStatus, errorThrown) { }) }, I have verified that it is not "name" however in none of the files I have made that equivalent. I hope you can help me -
Pylint-django raising error about Django not being configured when that's not the case (VSCode)
Pylint-django worked just fine up to version 2.3.x but since 2.4.0 it reports an error on every python-django file: Django was not configured. For more information runpylint --load-plugins=pylint_django --help-msg=django-not-configuredpylint(django-not-configured) This happens on VSCode and I believe I have it correctly configured: { "python.linting.pylintArgs": [ "--load-plugins", "pylint_django", "--load-plugins", "pylint_django.checkers.migrations", "--disable=C0114, C0115, W0222", "--disable=imported-auth-user", "--disable=invalid-name", "--disable=line-too-long" ] } This worked perfectly fine, as I said, up to v.2.3. I raised an issue on their repository but regrettably it was dismissed with little to no visible effort to address it. For the time being I'm staying with v.2.3.0, which lints with no issues with the above configuration, but would like to know if this is a bug or otherwise. Did any get into this issue or is it there anything else I'm missing? -
Prepend Serialized object with name
I have the following setup for my ListSerializer, which is called with a URL looking like "api/tax/2021-03-30": models.py class CityTax(models.Model): class Meta: verbose_name = "City Tax" verbose_name_plural = "City Taxes" season = models.ForeignKey(Season, on_delete=models.CASCADE, null=True) hotel = models.ForeignKey(Hotels, on_delete=models.CASCADE) EUR = models.DecimalField(max_digits=5, decimal_places=2) USD = models.DecimalField(max_digits=5, decimal_places=2) serializers.py class TaxSerializer(serializers.ModelSerializer): hotel = serializers.CharField(source="hotel.abbrev") season = serializers.CharField(source="season.title") class Meta: model = CityTax exclude = ['id'] api_views.py class TaxList(ListAPIView): serializer_class = TaxSerializer def get_queryset(self): """ Get city tax for appropriate season according to date of arrival """ url_date = date.fromisoformat(self.kwargs['start_date']) seasons = Season.objects.all() selected_season = Season.objects.get(start_date__lte=url_date, end_date__gt=url_date) return CityTax.objects.filter(season__title=selected_season) which returns a response that looks as follows: [ { "hotel": "DDC", "season": "A20", "EUR": "1.00", "USD": "1.19" }, { "hotel": "DSF", "season": "A20", "EUR": "1.13", "USD": "1.34" }, ] How can I prepend the result to look like this: [ "DDC" { "hotel": "DDC", "season": "A20", "EUR": "1.00", "USD": "1.19" }, "DSF" { "hotel": "DSF", "season": "A20", "EUR": "1.13", "USD": "1.34" }, ] I've been trying to figure out how to make this happen, but I feel like I'm looking in the wrong places (nesting serializers?) Thanks in advance! -
Not able to view/download Recipe 1m+ dataset
I have registered on: http://im2recipe.csail.mit.edu/dataset/login/ Post registration I am redirected to page saying verification failed with following error. "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 page generated by the handler for this status code." I did not get any verification mail too. Need help !! -
Load user from Firebase to Django
I am trying to load all the user from Firebase to Django Server. I have tried to read https://docs.djangoproject.com/en/3.1/howto/auth-remote-user/ but still can not figured out how to implement this function. How can I do that? or If anyone have a better idea can you suggest me. -
python3 django manage.py runserver
I'm running Django and I can't figure out why it's coming out like that. It turns out that Python and Django are installed. enter image description here -
Django rest-framework with mongodb not creating auto field primary key id
I am saving record in mongodb using django rest framework. Migration is as below - # Generated by Django 3.0.5 on 2021-01-17 10:39 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Demo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(default='', max_length=1000)), ('user_id', models.IntegerField()), ('published', models.BooleanField(default=False)), ], ), ] But the records in mongodb doesn't have auto created id in it { "_id" : ObjectId("6004354240e7097e5b392e5c"), "description" : "sdf asdaaaaaaaaaaaaaaaaaaaaaaaaaaa ass d", "user_id" : 11, "published" : false } Inserting records using serializer.save() -
How do I get pass "Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name" in Django
I have tried many of the suggested solutions show in previous questions but no success. I am trying a password reset but the error pop up each time the email form for the password reset is submitted. My files urls.py path( 'reset-password/', auth_views.PasswordResetView.as_view( template_name='account/reset_password.html', html_email_template_name='account/reset_password_email.html', success_url=settings.LOGIN_URL, token_generator=user_tokenizer), name='reset_password'), path( 'reset-password-confirmation/<str:uidb64>/<str:token>/', auth_views.PasswordResetConfirmView.as_view( template_name='account/reset_password_update.html', post_reset_login=True, post_reset_login_backend='django.contrib.auth.backends.ModelBackend', token_generator=user_tokenizer, success_url=settings.LOGIN_REDIRECT_URL), name='password_reset_confirm' ), reset_password_email.html {% autoescape off %} To initiate the password reset process for your Account {{ user.email }}, click the link below: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. {% endautoescape %} -
Media path not read in Django
I'm having a problem on how can I retrieve my images through using media file in Django. Currently I just want to display images based on their path in Database. Based on the console image below the {{MEDIA-URL}} does not recognize/read, it only read this tag {{img_photos.photos}}. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance I followed this documentation link but it seems it's not working. view_gallery.html {% for img_photos in photos %} <div class="card-body px-0"> <img src="{{MEDIA_URL}}{{img_photos.photos}}"/> #it seems {{media-url}} didn't read/recognize <h4 class="card-title">{{img_photos.photos}}</h4> <p class="card-text">This is a longer card with supporting text below.</p> </div> {% endfor %} App - urls.py urlpatterns = [ path('view_gallery/<int:pk>/',views.view_gallery, name='view_gallery'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def view_gallery(request,pk): path = settings.MEDIA_ROOT #I didn't use this don't know yet how to implement image = gallery_photos.objects.filter(gallery_info_id = pk) data = {'photos':image} #the output is like this PHotos/image.jpg return render(request, 'view_gallery.html', data) -
What kind of password does django-allauth put when registering through a social network?
When I register via social network, a new account is successfully created (with some kind of password). But if I want to enter the data of the created account through the forms, then because of the password, the account is not recognized. Django passwords: pbkdf2_sha256$216000$UHmkhzS870QX$FN7HfQDdbUvJ4GXJCIe2sPDGQTMuJjlPfUpiRxxGBc8= Django-Allauth passwords: !1ceV9EGvYkdbyAWNJZJ3n5KXLZ1K776oII6WJNhk -
Use Vue components in application at runtime
I am developing a small application using Vue which will have list of downloadable components available to the user. Downloadable components will be hosted somewhere on the webserver(compiled version of SFC's) seperately. List of components can be increased or decreased based on users permissions. This application will be shared with the user to download the components of their choice and add them to the list. Problem is am not getting any examples in the internet where compiled components are used inside compiled Vue apps at runtime. All the available examples need compiled components to be registered or to be imported in the applications in order to use it. The only way right now is to chuck the idea of using ES6 or (.vue) Single file Components luxury and use ES5 version which i don't want to. Can anyone help me out? Backend used is Django -
Django: How to realize App structure for specific program (picture)
I'm new to Python/Django and I would like to rewrite an old program as a web application The picture is a screenshot of the program. As you can see there are multiple tabs on the left and two on the top (marked red) so the programm ist kind of nested(?). All of the Tabs work together to calculate the end result. Im kind of overwhelmed so my first question is how to structure the Programm in Django using apps. Is each Tab one app and I link them all together? Also is there a template for tab-style menue? Thank you very much, hope ich can get it realized :D Programm_Image -
Design pattern of coupling/decoupling two apps in Django
I have two apps: app1 and app2. =>app1 has model A gets data with timestamps. =>app2 has model B with some computations that have to be made on the data that model A gets Usecase:. Every time we create model B, it has to check if we have enough data in model A => do an update. This same update is triggered every time we add data to model A. => My design is: since updates are having a place in model B then I import my model A in it and check if I have enough data while creating model B. on the other way around, if I add data to model A I prefer not importing model B in model A to avoid app circular dependencies and coupling. So my idea here is to send a signal from model A to model B and proceeds to the update, is it the best way to do it or you would think of some different design patterns? => I also read on some blogs that using signals is not always suggested, what's your take on this? -
How to delete a record only if the user posted is the logged in user
I have multiple users in my project my models.py file is class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Teacher(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,related_name='Teacher') name = models.CharField(max_length=250) subject_name = models.CharField(max_length=250) email = models.EmailField(max_length=254) phone = models.IntegerField() teacher_profile_pic = models.ImageField(upload_to="classroom/teacher_profile_pic",blank=True) def __str__(self): return self.name class Announcement(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def __str__(self): return self.title If the logged in user is a teacher it is allowed to create an announcement Now i want that only the teacher who posted the announcement should be able to see the delete button My html file is {% extends "classroom/base.html" %} {% block content %} <h1>Announcements</h1> {% for announcement in announcements %} <!-- starting loop (posts is keyword from view) --> <div style="border-style: solid;"> {% if object.teacher.id == request.teacher %} <div> <a href="{% url 'classroom:opt' %}">Delete</a> </div> {% endif %} <a class="mr-2">Posted by: {{ announcement.teacher }}</a> <h2><a class="article-title">{{ announcement.title }}</a></h2> <p class="article-content">{{ announcement.content}}</p> </div> {% endfor %} {% endblock content %} the if statement is supposed to be true if logged in teacher is the teacher who originally posted it. However the delete button is visible for every announcement my views.py has class AnnouncementListView(ListView): context = { … -
What is the Best way to get only 10 rows in django ORM
I have Grid-view it only show 10 records on time . What is the best way to get from database only 10 rows? Is MyModel.objects.all()[10:20] approprate . -
Django unit test remove Files created inside the tests
I'm using DRF view tests. Inside my tests I create files which I want to remove after the tests were running. I'm using addCleanup inside my setUp method to remove the directories. It basically works, but when I run my complete set of unit tests one dir won't be deleted (I think it's the first one created). Here is the relevant code: class BaseViewTest(APITestCase): client = APIClient() base_media_root = settings.MEDIA_ROOT def setUp(self): settings.MEDIA_ROOT = tempfile.mkdtemp(dir=self.base_media_root) # add test data self.addCleanup(shutil.rmtree, settings.MEDIA_ROOT) -
Django {% if object.foreignkey %} returns the opposite of the value
So I have two models. First one is Collection Title and second one is Title Status. In Title Status I have a foreignkey named collection_title_status that points to CollectionTitle. I have rendered the form TitleStatusForm inside my collection_title_detail.html with a DetailView and a FormMixin. The form is in a modal. Globally, this part works, meaning that I can fill the form, and it saves the data and creates a link between the Collection Title and the Foreign Key of Title Status (for example, if CollectionTitle id is 61, my collection_title_status value will be 61 as well). What I want to do : If Collection Title is not linked to a Title Status (meaning the user as not initiate the Status monitoring yet), then I want to display the button called 'Initiate' that opens the modal containing TitleStatusForm to initiate the Title Status model If Collection Title is already linked to a Title Status (which should be done after fulfilling the first step above), then I don't want to display the above mentionned button and modal. Instead, I want to display the values previously entered by the user for each field. So here is how I tried to do it : … -
Google blocks confirmation email sent from my blog
I'm creating a blog with django, and when I try to send the registration email to a user, Google blocks the sending. Here, the screenshot of the message: https://i.stack.imgur.com/faqV6.png acc_active_email.html: {% autoescape off %} Hi {{ user.username }}, Click here to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} Email configuration in settings.py: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_PORT = 587 I've tried with different emails, but the problem persists. Thanks in advance for the help. -
Why does docker-compose.local.yml can not run django app?
I am using docker-compose -f docker-compose.local.yml run django black apps common tests individual_service It is giving: python: can't open file '/app/manage.py': [Errno 2] No such file or directory