Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access another field of a related ManyToMany table?
Let's say I have the following models: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) upload = models.ForeignKey(related_name='x1', Uploads) class Uploads(models.Model): topic = models.CharField(max_length=100) I want to select all the Articles of a specific upload topic along with their Publication title. So my output should be: <QuerySet [{'id': 1, 'headline': 'headline1', 'publications': 'publication title 1'}, {'id': 2, ''headline': 'headline2', 'publications': 'publication title 2'},] Currently I have this: Dataset.objects.filter(upload__topic='sports').values('id', 'headline', 'publications') which gives me the following: <QuerySet [{'id': 1, 'headline': 'headline1', 'publications': 1}, {'id': 2, ''headline': 'headline2', 'publications': 2},] I know I can loop over the QuerySet and for each publication fire another DB query towards the Publication table to get the relevant title, but I'm wondering if there's a better way to do that. Perhaps with a single query? -
Circular Dependency between Form and Model
Here is a form: class ToDoItemModelForm(forms.ModelForm): class Meta: from ToDoDashboard.models import ToDoItem model = ToDoItem fields = ['description', 'label', 'comment', ('start_date', 'due_date', 'time_estimate_hours')] def clean(self): start_date = self.cleaned_data.get('start_date') end_date = self.cleaned_data.get('due_date') if start_date > end_date: raise forms.ValidationError("Dates are incorrect") return self.cleaned_data and here is a model: class ToDoItem(models.Model): dashboard_column = models.ForeignKey(DashboardColumn, on_delete=models.CASCADE) description = models.TextField() label = models.CharField(max_length=128) start_date = models.DateTimeField(null=True) due_date = models.DateTimeField(null=True) from ToDoDashboard.forms.ToDoItemForm import ToDoItemModelForm form = ToDoItemModelForm Now it says ImportError: cannot import name 'ToDoItem' from partially initialized module 'ToDoDashboard.models' (most likely due to a circular import) How to solve the problem? -
URL Routing trouble in React + Django
I have the following urlpatterns configured for my Django app. This rule will route to http://localhost:8000/profile/. urlpatterns = [ path("profile/", test_frontend_views.profile), ] The views code: def profile(request): return render(request, 'frontend/Profile_temp_master.html') Within my React components that are dynamically creating HTML for the template, I am making requests to my Django backend API with the following scheme: fetch("api/profile", requestOptions).then(..).then(..) However, rather than this request routing to http://localhost:8000/api/profile/, it is routing to http://localhost:8000/profile/api/profile/ which is not a valid endpoint and returns and error. How can I solve this so that the URL routes to the correct endpoint? -
Why do I get a Key Error for 'post' in PostListView
I don't know why I got a Key Error message (KeyError at / 'post') when I def get_context_data in PostListView. But that was totally fine when I just def get_context_data in PostListDetailView. Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect('http://127.0.0.1:8000/') class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Admin Section with Users and Groups Disappeared
I want to add custom views and templates to Admin and wrote this: # in models.py class MyAdminSite(admin.AdminSite): def my_view(self, request): return HttpResponse("Test") def get_urls(self): from django.urls import path urlpatterns = super().get_urls() urlpatterns += [ path('my_view/', self.admin_view(self.my_view)) ] return urlpatterns admin.site = MyAdminSite() # and in apps.py class MyAdminConfig(AdminConfig): default_site = 'ToDoDashboard.admin.MyAdminSite' I have registered all the models and I see them in my custom Admin panel. However, the section with users and groups has disappeared. How to get it back? -
Query database in django using model procedure
I have created model with procedure that subtract two dates from fields in model returning days difference between them, for example: class Example: earlierDate=models.DateField() laterDate=models.DateField() def day_diff(self): return (laterDate-earlierDate).days Is it possible to query database including day_diff procedure ? in_views_query=Example.objects.filter(day_diff__gte=30) When i use this kind o query it shows me that there is no field 'day_diff' Regards -
How to redirect to post detail page after deleting a comment in Django?
Can someone help me out please. I want to redirect to a post detail page after deleting a comment of a given pk. I got an AttributeError when ever I hit the comment delete button. Error: function object has no attribute 'format' If I change my success_url of the comment delete view to redirect to post list page with no argument, it works well but that's not what I want. I need the user to be redirected to post detail page after deleting a comment. Here's my Post model STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.pk, self.slug]) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs)''' **Comment model** ```class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) comment = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.author} on {self.post}' def get_absolute_url(self): return … -
Unable to access static files in Django - Development server
I am trying to access static files in browser but unable to access them. My static settings insettings.py are below STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") My urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', FrontPage.as_view()), # url('', include(router.urls)) ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My folder structure projectname projectname settings.py urls.py app1_name static bootstrap css cover.css templates My template.html <link href="/static/bootstrap/css/cover.css" rel="stylesheet"> The above link isn't loading the static file. Please let me know where am I going wrong. -
TypeError: __init__() got an unexpected keyword argument 'instance' for custom user in Django
When I am trying to register a custom user or when i am trying to view profile of login user, i am getting this error. I am not sure why i am getting this error, Here is my code, please suggest where i am doing wrong. Thank you in advance. Url.py path('register/', RegisterView.as_view(template_name='users/register.html'), name='register'), path('profile/', user_views.profile, name='profile'), Model.py user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=254, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that is built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() ``` Form.py ``` class RegisterForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: Model = User fields = ('email',) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean_password2(self): # Check that the two password … -
Template extending not working properly - Django
i have 3 files, Base.html, Navbar.html and dashboard.html. im trying to extend base.html and include navbar.html in dashboard. its getting extended but the problem is then dashboard's content data is not visible. If i remove navbar.html it works but no navbars. Below are the files pls check and help to resolve. Navbar.html {% load static %} <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="dashboard" class="nav-link">Home</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fas fa-search"></i> </button> </div> </div> </form> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> <div class="dropdown-divider"></div> </ul> # Side configutarion {# <li class="nav-item">#} {# <a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#" role="button">#} {# <i class="fas fa-th-large"></i>#} {# </a>#} </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="dashboard" class="brand-link"> <img src="{% static 'img/AdminLTELogo.png' %}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">Acro Paints</span> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel … -
How to use string of <li> in django view?
I am building a blog where users can click on several <li> items in the sidebar to show blog posts according to the clicked category. So far I managed to show the five latest blog posts on the landing page (blog.html extends base.html) with a load more button to display another five so on and so forth until the pagination is done. Now I would like to extend this logic to use the same views (there are two views, one for the initial 5 posts and one for the pagination - load more logic) for the categories as well to avoid ending up with two views + 1x Ajax function for each category. Is there any dynamic solution to this? My basic idea is to get the string of the clicked <li> item and filter the queryset by the category then to get the correct objects from the database. So the general logic would be the same and each URL would be mapped to the very same view. If my general idea might work, how can I use the clicked string within the view function to adjust the queryset? views.py def render_blog(request): # Get 5 latest posts and order by … -
Django - Variable inside style not detected
{% if photos %} {% for photo in photos %} {% endfor %} {% else %} No images availble for the project. {% endif %} And I want to add a picture url inside the style tag. div class='image-block col-sm-4' style="background: url({{photo}}) no-repeat center top;background- size:cover;" How can I get the {{photo}} url inside the string? -
Blank field not working correctly in Django model
I have a Django model described as follows- class Building(models.Model): name = models.CharField(max_length=25,unique=True,blank=False) country = models.CharField(max_length=20,blank=False) city = models.CharField(max_length=20,blank=False) def __str__(self): return self.name All of the fields are required as blank is set to False in each of them but still, I am able to save objects for this model by leaving city and country as blank. -
virtualenv could not install on my machine due to permission denied
creating c:\program files\python38\Lib\site-packages\distlib error: could not create 'c:\program files\python38\Lib\site-packages\distlib': Access is denied ---------------------------------------- How do I fix this? I tried to install virtualenv and django but got the error above -
Elastic Beanstalk: /bin/sh: /opt/python/run/venv/bin/activate: No such file or directory
Trying to deploy a django app which uses channels following this https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 These are my config files: 01_env.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard.settings" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /websockets/* Process: websocket Priority: 1 aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP 02_setup.config container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' When I run eb create django-env it fails with Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. and in the logs, I found that the reason is: 2020-06-17 16:36:41,880 P4189 [INFO] Command 00_pip_upgrade 2020-06-17 16:36:41,883 P4189 [INFO] -----------------------Command Output----------------------- 2020-06-17 16:36:41,883 P4189 [INFO] /bin/sh: /opt/python/run/venv/bin/activate: No such file or directory So even though I'm following the guide, the directory seems to not exist. I'm also not being able to SSH into the EC2 instance to check this. Has the python venv directory in Amazon Linux 2 changed? -
Django Rest Framework : Nested Serializer not working
I have almost tried everything but am not able to reach at the point model.py file class RecievingImages(models.Model): """Original and Masked Images""" .... name = models.CharField(max_length = 100, unique = True, primary_key=True) area = models.IntegerField() number = models.IntegerField() agency_name = models.CharField(max_length=100, default='general') rawImage = models.ImageField(upload_to=imageNameForRawImage,) ... class UpdationImages(models.Model): """ Update Image wrt name""" .... name = models.ForeignKey(RecievingImages, on_delete=models.PROTECT, related_name='updated') updated_image = models.ImageField(upload_to=UpdatedImageFolder,) updated_image_url = models.TextField(default='None') .... serializer.py class UpdatedImageSerializer(serializers.ModelSerializer): model = UpdationImages fields = ('name', 'updated_image', 'updated_image_url') class RecievingImagesSerializer(serializers.ModelSerializer): updated = UpdatedImageSerializer(many= True, read_only=True) model = RecievingImages fields = ('updated','name','area','number','agency_name', rawImage) I have used related_name in the model and also following the documentation along with that with many = True But still in serializer.data updated does not show views.py class MappingSinglePhoto(APIView): """ Mapping Single Image """ def post(self, request): try: data = request.data # import pdb; pdb.set_trace() name_of_image = data['name'] mapped_images_qs = UpdationImages.objects.select_related('name').filter(name = name_of_image) for image in mapped_images_qs: serializer = RecievingImagesSerializer(instance = image) pdb.set_trace() serializer.data # return Response(serializer.data) except Exception as e: print(e) NOTE if I use depth=1 then it's working fine, but I am not looking for all the fields that depth displays. Thanks & Regards -
Django model order by custom algorithm Using the difference between the current time and creation time
Django version 2.1.15 Python version 3.7.4 Djngo settings.py LANGUAGE_CODE = 'ko-kr' TIME_ZONE = 'Asia/Seoul' I am not familiar with English.I will write in English as hard as possible. Django model order by custom algorithm Using the difference between the current time and creation time my model is models.py class Review(models.Model): title = models.CharField(max_length = 100) content = models.TextField() movie = models.ForeignKey(Movie,on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) like_users=models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='like_reviews') created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) i want to Descending order_by (Count(like_users)/(current_time - created_at + 60)) Review model (current_time-created_at) : I want to change the difference between two hours to minutes. (integer) I tested these things. from django.db.models import ExpressionWrapper,F,Value from django.db.models.fields import DurationField,DateTimeField def test(request): now = timezone.localtime() test = Review.objects.annotate(diff_time=(ExpressionWrapper(Value(now, DateTimeField()) - F('created_at'), output_field=DurationField()))).annotate(diff_value=F('diff_time')+60).values() But failed. How can I get the results I want? I used a translator to ask questions, but I hope my intentions are clearly communicated. I'm so sorry for my poor English. -
Django, accessing model methods
In the Django documentation, they recommend writing business logic in Model. How do the View layer or queryset access the methods in Model ? As per example in documentation (https://docs.djangoproject.com/en/3.0/topics/db/models/) from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" How do view layer access the baby_boomer_status ? I have a little experienced in Django development but I used to write logics in View itself. -
join the results of two query on each others with Django
I have 2 models, i simplify them for the example: class CustomerOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) isPaid = models.BooleanField(default=False) and class EventParticipant(models.Model): customerOrder = models.ForeignKey(CustomerOrder, on_delete=models.CASCADE) event = models.ForeignKey(Product, on_delete=models.CASCADE) What i need to do is to display in a table every participants for an event but link the order to the participant so i can display the isPaid status for each participant. I think its similar to a join on SQL. So i tried something like: participants = EventParticipant.objects.filter(event=event_pk).select_related('customerOrder') but when i try to access it like participants.cusomerOrder i get: 'QuerySet' object has no attribute 'customerOrder' so i guess is missunderstand something. Thanks -
Saving a form in a foreign key field
I have two models Order and a date model. The order model has a foreign key attribute of date model. I have made a form in which I can update the date fields of order, but when I click submit it creates a new date object in date model not in the order date field. The order model date field is empty. My views code seems to be alright maybe somethings wrong in my form.py.I want my form to save values in the date field in order. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if … -
What does "uWSGI is a self-healing application" practically mean?
According to Django Official Documentation: uWSGI is a fast, self-healing and developer/sysadmin-friendly application container server coded in pure C. What exactly are self-healing applications and how is this paradigm implemented by uWSGI? Last but not least, what is the importance of this aspect of uWSGI for django? -
Possible to have react + Django on pythonanywhere.com
Is it possible to deploy react front end app and Django as back end app on pythonanyhere.com? I have django API as back end and React as Front app. -
DICOM image display in Django
How to display DICOM image in my Django 3 template HTML file. I have pydiacom, Pil & Matplotlib installed. I want to send the dicom image from view to template. How can I do this, is it the correct process for I'm doing wrong. -
Find and delete content with BeautifulSoup
I have blog text (application in django) where I want to get rid of some content. I try to search for content using BeautifulSoup. I want to find and delete everything between wphimage tags. Below is my code. What doesn't work is the wphimage tag that appears when I display soup objects after running it, where I did write to obj.text my code class Command(BaseCommand): def handle(self, *args, **kwargs): article = Blogposts.objects.all() for obj in article: soup = BeautifulSoup(obj.text, 'html.parser') for i in soup.find_all('wphimage'): obj.text = str(i.replace_with('')) obj.save() content of blog post Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <wphimage data="{'FileId':6182,'Copyright':'John Smith','Alignment':'left','ZoomDisabled':false,'ImageOnly':false,'AlternativeText':'John Smith','ImageVersion':'conductorportraitlong','tabid':0,'moduleid':0}"> <span style="display:block; float:left;" class="DIV_imageWrapper"> <a data-lightview-title="Adela Frasineanu" data-lightview-caption="" class="lightview" href="//example.com/static/images/image.JPG"> <img src="//example.com/static/images/image.JPG" alt="John Smith"> </a> <a href="javascript:;">≡ <span>John Smith</span></a> <a class="A_zoom lightview" href="//example.com/static/images/image.JPG" data-lightview-title="John Smith" data-lightview-caption="">+ </a> </span> </wphimage> Lorem ipsum dolor sit amet, consectetur … -
Try to display images from a directory in Django
I try to display all images from a directory that is in the project. In the views.py def showimages(request): path='C:\\Users\Peter\PycharmProjects\displayimages\displayimages\display\static' img_list = os.listdir(path) return render(request, 'displayphotos.html', {'images':img_list}) In the html file {% for image in images %} <p>{{image}}</p> <img src="{% static '{{image}}' %}"> {% endfor %} But the display is <p>DSC_5390.jpg</p> <img src="/static/%7B%7Bimage%7D%7D"> <p>DSC_5392.jpg</p> <img src="/static/%7B%7Bimage%7D%7D"> If I print them in paragraph tag, all file names are correct, but all wrong in img tag. How can I fix it?