Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to read pdf file in Django
This is my view.. In the blank space after open I want to read a file but I dont to what to write to make it dynamic.. def home(request): image_data = open('', 'rb').read() return HttpResponse(image_data, mimetype='application/pdf') This my model here file is uploaded .. Its is either pdf or .doc .. I want to read the file uploaded from django.db import models class CV(models.Model): file = models.FileField(upload_to='media') -
What technologies are currently being used for web development? [closed]
Are Django (python), express (node.js), laravel or symfony (php) better for the backend? What is the best stack today? -
How to Extract values of diffrent from foreign key in django models
I have made a model to make friends using Django model. Now I am unable to get the friend id through the model. The model is as follows class Friend(models.Model): users = models.ManyToManyField(User) #following users current_user = models.ForeignKey(User, related_name='owner', null=True,on_delete=models.CASCADE) #followers @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.remove(new_friend) How can I extract the friend id -
Create custom url wagtail
I have a site that I've structured like so: Top Page: Animals Subpage: Cat Subpage: Dog Top Page: Cat Subpage: Food Top Page: Dog Subpage: Food That way, a user can go to site/animals or site/cat. Animals is high-level info, Cat and Dog are more detailed parts of the site. What I want to do: Occasionally, I want to be able to reuse pages from Cat or Dog and reuse them under Animal. But I don't want the url to switch from one section to another. Example: If the user is under Animal, and they click a food article, the url should be: animals/cats/food_article If they click on that same article under cats, the url should look like: cats/food_article What I've tried: I've tried using RoutableRouteMixin. But that works for subpages, not for pages at the same level. I tried overwriting the get_url_parts method for the article models. But then I got 404 errors because the pages didn't actually exist at the url I created. Can this be achieved in Wagtail? Or is there a Django solution I can use with Wagtail? -
Run django app through ip address (ALLOWED_HOST)
im stuck in hosting my Django app. Can you guys help me to sort it out. settings.py DEBUG = True ALLOWED_HOSTS = ['http://127.0.0.1:8000', 'localhost', '127.0.0.1', '192.168.1.190',] and my ifconfig is I tried this python manage.py runserver 0:8000 python manage.py runserver 192.168.1.190:8000 I got the following result in my browser Correct me if I am wrong. Thanks in advance. Have a great day. -
Nested AbstractUser model failing during update operation with "null value in column "user_id" violates not-null constraint"
I am creating nested abstract user "Teacher from User", My use case is "Create User" -> "Then make user to teacher" I am able to create user and make the user to Teacher, but I am unable to update the field, In below case want to update "teacher_cost" Model.py from django.contrib.postgres.fields import JSONField from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): uid = models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True) TEACHER = "Teacher" STUDENT = "Student" user_type = models.CharField(max_length=30, default=STUDENT) contact_number = models.CharField(max_length=20, null=True, blank=True) address = models.TextField(null=True, blank=True) photo = models.ImageField(null=True, blank=True) image = models.ImageField(upload_to='users/', default='default/avatar.png') approved = models.BooleanField(default=True) def save(self, *args, **kwargs): if self.user_type == User.TEACHER and self._state.adding: self.approved = False super().save(*args, **kwargs) @property def dishes(self): ret = self.teacher.dish_set.all() if ret: return ret else: return '' class Teacher(models.Model): uid = models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) teacher_cost = models.DecimalField( max_digits=5, decimal_places=2, null=True, blank=True) languages = models.CharField( max_length=50, null=True, blank=True) address = models.TextField(null=True, blank=True) def __str__(self): return self.user.username Serializer.py from rest_framework import serializers, exceptions from django.contrib.auth.forms import PasswordResetForm from django.conf import settings from .models import * from rest_auth import serializers as rest_auth_serializers from django.utils.translation import ugettext_lazy as _ class UserDetailsSerializer(serializers.ModelSerializer): """ User model w/o β¦ -
Displaying name of the month instead of a number in Django admin panel
I want to display month's name instead of a number. How do I do that? -
MEDIA_URL not working in img tag of template file Django
I am working on uploading picture of a product from users on my ecommerce site project. However after I got the upload to work when I add the url in the templates, it refuses to load, and in VS code the error message is showing wrong url when I have it set up correctly(I think). This is the main url: urlpatterns = [ path('admin/', admin.site.urls), path('login/', include('login.urls')), ] This is the url im using for my page urls.py: urlpatterns = [ path('', views.loginpage, name='login'), path('logged/', views.loggedpage, name='logged'), path('products/', views.productlist, name='products'), path('products/<int:product_id>/', views.productdetail, name='product_detail'), path('post_product/', views.post_product, name='post_product'), path('cart/', views.cart, name='cart'), path('add_to_cart/<int:product_id>/', views.add_to_cart, name='add_to_cart'), path('delete_from_cart/<str:product_name>/', views.delete_from_cart, name='delete_from_cart'), path('register/', views.register, name='register'), path('logout/', views.log_out, name='logout'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is what I have in settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, "product-pic") MEDIA_URL = '/pictures/' models.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) image = models.ImageField(upload_to='product/', null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post_date = models.DateTimeField('post date:', default=timezone.now) My template in products.html: <li class="list-group-item d-flex justify-content-between align-items-center"> <img src="{{product.image.url}}"> </li> <p>{{ product.image.url }}</p> The correct url address for the picture is http://127.0.0.1:8000/login/pictures/product/car.jpg which I have tried in my browser, it is displaying picture. However when I run my products page, vs code is showing Not Found: β¦ -
Django Long process in view
I need about 50 seconds to run my processes in some views of my Django app . So The Browser should not wait long time , so i decided to start my jobs in a thread before The view returns any render or HttpResponse . The problem is with uwsgi & nginx the thread processes will be killed after view returns its response . Here is My view : def some_view(request): def save_file(): ...long process ... t = Thread(target = save_file) t.setDaemon(False) t.start() return render() whats the best way to do this ? Can thread stays alive after view returns a response ? -
Django annotation resulting in cartesian product
I have a model where a particular class will have multiple child classes. Sample design: class ParentModel(models.Model): ParentName = CharField(max_length=50) class ChildModelA(models.Model): FK1 = ForeignKey(ParentModel, on_delete=models.CASCADE) ChildAValue = IntegerField(default=0) class ChildModelB(models.Model): FK2 = ForeignKey(ParentModel, on_delete=models.CASCADE) ChildBValue = IntegerField(default=0) What I'm trying to do is sum up, per 'ParentName', the sum of all ChildAValue and ChildBValue. The issue I'm running in to is when I do both in the same query, I get a cartesian product between ChildA & ChildB. Sample query: ParentModel.objects.all().values('ParentName').annotate( ChildASum = Sum('childamodel__ChildAValue), ChildBSum = Sum('childbmodel__ChildBValue), ) The resulting query set gives me the summation of ChildBValue multiplied by the total number of ChildA objects in the FK... meaning 6 ChildA objects pointing to that particular Parent will multiply my ChildB value by 6. And vice-versa for the ChildASum. Are there any ways to aggregate multiple child models of the same parent without a multi-join? Thanks! -
Evaluate Query Expression as Django model function and as filter of QuerySet subclass
I'd like to make a function (or pair of functions) for a Model that can either return an integer (fully-evaluated) or a Query Expression. (below example code may have syntax errors) class Square(Func): arity = 1 function = "square_me" class PeopleQS(QuerySet): def by_bmi(self, target_bmi: int) -> "PeopleQS": return self.filter(bmi__lte=target_bmi+1, bmi__gte=target_bmi-1) class Person(models.Model): height = models.FloatField() weight = models.FloatField() people = PeopleQS.as_manager() # can't be a @property in the real code def bmi(self) -> int: return F("weight")/Square(F("height")).convert_value() However, when I try something like this, I get <lambda>() missing 3 required positional arguments: 'value', 'expression', and 'connection' or some other error in the output. What I assume I'd want are two functions, bmi_qe and bmi_int (that simply takes bmi_qe and tacks on .convert_value() to it so I can both do Person.people.by_bmi(23) and Person.people.get(pk=1).bmi_int() -
group permission Django based on roles linked to login
I am trying to set up a group based permissions with Django. my requirements are so basic. I just want to need to enable/disable some content based on groups user belong to, however, our silver group permission it should be able to view for logged and no logged people, and everything after Silver content it should be logged, and be part of a group (gold or Platinum). I Have a separate app managed account everything related to user accounts (logins, passwords, etc), and website (landing page, and course content), but how can I do this in Django? Silver (starter) Gold Platinum Tree view project βββ apps β βββ account β β βββ admin.py β β βββ apps.py β β βββ forms.py β β βββ helpers.py β β βββ __init__.py β β βββ migrations β β β βββ 0001_initial.py β β β βββ __init__.py β β β βββ __pycache__ β β β βββ 0001_initial.cpython-36.pyc β β β βββ __init__.cpython-36.pyc β β βββ models.py β β βββ __pycache__ β β β βββ admin.cpython-36.pyc β β β βββ forms.cpython-36.pyc β β β βββ helpers.cpython-36.pyc β β β βββ __init__.cpython-36.pyc β β β βββ models.cpython-36.pyc β β β βββ urls.cpython-36.pyc β β β βββ β¦ -
UnboundLocalError Increment View Count Django App
I'm working on creating my own little auction style app similar to eBay, and I am simply trying to increment the viewCount variable I have set, and display that value as the number of times the page has been viewed. In the views.py file, since I have a reference to my model, I thought I could invoke the incrementViewCount() in the model.py in this way: views.py class AuctionItemDetailView(DetailView): model = AuctionItem model.incrementViewCount() model.py viewCount = models.IntegerField(default=0) def incrementViewCount(): viewCount += 1 The error message in the console is as follows: UnboundLocalError: local variable 'viewCount' referenced before assignment I'd appreciate your guidance. Thanks. -
The views that render "general" templates where they should be (home.html, about.html, etc)? | Django
I have templates for example like home.html, about.html, etc. Which are "general." Where should the views that render these views be located? I am not convinced to place these views in the applications of my project, since each one has a very specific purpose. It occurs to me to create an application specifically for these "general" views, but what should this application be called? Is it good practice to do it? Another solution would be to put the views in the urlconf, as follows: from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name = 'pages/home.html'), name = 'home'), # here ... ] But is this alternative of good practice? Is there a much better alternative? -
Assign currently logged in user as default value for a model field
This is my code models.py class Expense(models.Model): category=models.CharField(verbose_name=u"Category:", choices=cat, default=0, max_length=50) description=models.CharField(verbose_name=u'Description:', max_length=50) cost=models.DecimalField(verbose_name=u'Cost:', max_digits=5, decimal_places=2) date=models.DateField(auto_now_add=True) createdBy=models.ForeignKey(User, on_delete=models.CASCADE, blank=True) class Meta: ordering = ['date'] admin.py class ExpenseAdmin(admin.ModelAdmin): list_display=('category', 'description', 'cost', 'date', 'createdBy') list_filter=('category', 'description', 'date') search_fields=('category', 'description', 'date') fieldsets = [ (None, { 'fields': [('category', 'description', 'cost')] } ), ] def save_model(self, request, obj, form, change): if getattr(obj, 'createdBy', None) is None: obj.createdBy = request.user obj.save() views.py def newExpense(request): form=ExpenseForm(request.POST or None) if form.is_valid(): form.save() return redirect(monthExpense) context={ 'form':form } return render(request, 'newExpense.html', context) forms.py class ExpenseForm(forms.ModelForm): class Meta: model = Expense fields=['category', 'description', 'cost'] In django admin site works fine but in my HTML site doesn't work. Displays an error: IntegrityError at /newExpense/ NOT NULL constraint failed: expense_expense.createdBy_id -
Vagrant, Centos7, Nginx, Uwsgi, Django. SSH + Nginx Connection Reset then Connection Refused
Versions VirtualBox Version: 6.0.0 ( I think ) Vagrant Version: 2.2.3 CentosBox: "centos/7" Nginx Version: 1.16.1 uWSGI Version: 2.0.18 Django Version: 2.2.1 Background I have two vagrant boxes running, a test and a production. The only difference is IP and core count. I've set up both so I can ssh directly into the boxes, instead of having to ssh into the host machine and then run 'vagrant ssh' General Issue The production version will randomly boot me out of the ssh (Connection reset by IP port 22) and then i'll get Connection Refused. If I ssh into the Host machine and then 'vagrant ssh' I can still get in and everything seems to be fine, I can even still ping other computers on the network. But I can't access it from outside the host, this goes for the nginx server as well (IP refused to connect.) on chrome The issue will occasionally fix itself in a couple minutes, but the majority of the time requires a 'vagrant destroy' and 'vagrant up --provision' / recreate the box. I also occasionally get booted out of the Host Machine and well as the test box, but both I can still access externally after β¦ -
How to load an instance in class based views using form_valid
I'm trying to build a form that automatically fills some fields in a class based create view that lets logged in users create a Job. However, I can't seem to find the correct way of doing this for fields that aren't the user (eg. request.user). So the create view is trying to get a company_name from the logged in user, company_name field belongs to a model called Company. Each Company has an owner with a foreign key to the User model. All the reuest I've tried so far have led to a 'WSGIRequest' error. So far I've tried to request: company_name user.company_name company.company_name company user I don't understand how these requests work, I have seen examples for getting the logged in users name and I'm not familiar how to do this otherwise. Please can someone help me understand how this works and how I should be doing this? I'm using Django 2.2 with python 3.6 Auth Models: class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField(max_length=15) email = models.EmailField(max_length=250, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' def __str__(self): β¦ -
Email only going through sometimes from SendGrid/Django Contact Form?
As stated in the question. On the SendGrid site, it shows that all of the requests (when submit is pressed on the contact form) have been received but only 1/3 of the requests are actually delivered. Anyone have any insight into why this might be happening? -
Cinema booking system in django - advice
I'm working on web cinema. I've already stoped on booking system as I cannot figure it out where to start. I already have one model made which represents single Movie. class Movies(models.Model): title = models.CharField(max_length=100) age = models.CharField(choices=AGE_CATEGORY, max_length=2) kind = models.CharField(choices=MOVIE_CATEGORY, max_length=3) price = models.FloatField() date = models.DateField() max_seats = models.IntegerField(default=100) description = models.TextField() def __str__(self): return self.title def absolute(self): return reverse("movie", kwargs={ 'pk':self.pk }) def order(self): return reverse("movie-order", kwargs={ 'pk':self.pk }) Along with it I've already made individual pages for each movie. May goal is to display "max_seats" in table structure 10x10 (columns/rows) and each td would be an individual numeric span for instance: A1, B7 etc. I thought about making each span an object of new model BookSeat with reference to user and Movies model. Would it be a good solution ? I'm kinda new in django so I prefer to verify if my way of thinking is good. -
Using pure HTML forms in Django views
SO I'm tryng to create a Django site using HTML forms.The form takes in vendor choice and amount, which is then needed to be passed into views. The employee table's balance needs to be updated, with the amount paid deducted from the balance of the current logged in user, and an entry needs to be added to the transaction table stating the details, with credit = 0, rest info taken from form. How can this be done? Given below are my files: html: <form method="POST" action=""> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultUnchecked" name="defaultRadios"> <label class="custom-control-label" for="defaultUnchecked">Vendor 1</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultUnchecked" name="defaultRadios"> <label class="custom-control-label" for="defaultUnchecked">Vendor 2</label> </div> <input type="" class="form-control" id="amount1" name="amt" aria-describedby="emailHelp" aceholder="Enter amount"> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> Models.py: from django.db import models from django.contrib.auth.models import User import django import datetime # Create your models here. class vendor(models.Model): id = models.CharField(max_length=20, on_delete=models.CASCADE, primary_key=True) name = models.CharField(maxlength=30, on_delete=models.CASCADE) class employee(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) id = models.CharField(max_length=20, on_delete=models.CASCADE, primary_key=True) balance = models.IntegerField(default=0) class transaction(models.Model): vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE) emp_id = models.ForeignKey(employee, on_delete=models.CASCADE) debit = models.IntegerField() credit = models.IntegerField() timestamp = models.DateField(_("Date"), default=datetime.date.today) I am confused as to how data can be taken from β¦ -
When should you use @property in a model class?
When reading the docs, there is very little information how and why to use @property in a class. All I can find is: Also known as βmanaged attributesβ, and a feature of Python since version 2.2. This is a neat way to implement attributes whose usage resembles attribute access, but whose implementation uses method calls. When I have a function inside a model like def get_absolute_url(self): should I be decorating it with @property? @property def get_absolute_url(self): pass What is the difference between an un-decorated def and one decorated with @property? When should I use it and when not? -
Stop Concatenating HTML hrefs to address bar
I have a btn-group with some buttons, each of which will lead to a different page. The btn-group will be visible in every page. Here is the html for the btn-group, <div class="btn-group-lg text-center" role="group" aria-label="Basic example"> <a class="btn btn-outline-primary" href="" role="button">Home</a> <a class="btn btn-outline-primary" href="view_schedule/" role="button">Schedule</a> <a class="btn btn-outline-primary" href="view_syllabus/" role="button">Syllabus</a> <a class="btn btn-outline-primary" href="view_records/" role="button">Records</a> <a class="btn btn-outline-primary" href="view_achievements/" role="button">Achievements</a> <a class="btn btn-outline-primary" href="view_gallery/" role="button">Gallery</a> <a class="btn btn-outline-primary" href="view_contact/" role="button">Contact</a> <a class="btn btn-outline-primary" href="about/" role="button">About Us</a> </div> But whenever I press a button, it modifies the url in the address bar. Example:- From http://127.0.0.1:8000/shotokankaratebd/, if I press the Schedule button, it changes the url to http://127.0.0.1:8000/shotokankaratebd/view_schedule. After that, if I press the schedule button again, it changes it to http://127.0.0.1:8000/shotokankaratebd/view_schedule/view_schedule which is an invalid url and I get an error. How can I write it so that whenever a button is pressed, only the part after http://127.0.0.1:8000/shotokankaratebd/ is affected? -
How to have multiple urls.py in django app?
I want to split the django app urls into two urls with different names, urls.py and reset_urls.py. First one, urls.py works as expected, but the second does not. I tried the obvious approach but it seems not to be working. I want the reset_urls.py to be an endpoint for a password reset, but after creating, it seems not to be working. I know django allows for renaming and having multiple urls.py in single app, but I'm not sure exactly how it should be done, even after checking the docs(not sure I checked the right one) Here the source code for the urls: URLconf: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('blog.urls', namespace='blog')), path('accounts/', include('users.urls', namespace='account')), path('accounts/reset', include('users.reset_urls')), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py Works as expected. no issue here. from django.urls import path from users import views from django.contrib.auth import views as auth_views app_name = 'account' urlpatterns = [ path('profile', views.profile, name='profile'), path('register', views.register, name='register'), path('login', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] reset_urls.py Does not work as expected from django.urls import path from django.contrib.auth import views as auth_views urlpatterns = [ path('password_reset/', β¦ -
Is there a way to add more than one model to a class based view?
Is there a way to add more than one model to a class based view ?! This is my detail view. class ArticleDetailView(DetailView): model = Article I want to add another model to my view . I know i can use function based views in order to to have multiple models in my view. But i'm wonder that is there any way i can do this with my class based view ? -
How to create a multi-step form in django where steps are dependant on each other
disclaimer: I know that this question is mostly about asking for an opinion, but I don't know how to turn it into something with 'real' code. context I'm currently building up a form (or a set of forms) that will allow users to fill in time tracking information. Process The process can be decomposed in 3 steps: provide some base information (date and activity type - e.g. working on a project, meetings, being with a customer, ...) depending on type of activity, provide more details (e.g. name of the project, name of the client, time spent, ...) submit the form Model All the information is stored into a single model. Therefore, only the information provided at step 1 (date and type of activity) are required. current approach I currently have 1 django ModelForm that is displayed on screen. All the data are validated at the model level (so the business logic is also enforced if users want to enter data through APIs). On the front end, the various steps are managed through tabs and Javascripts (that toggle the visibility of additional information to provide based on the radio button on the first tab). current pain points some of the validation β¦