Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to add existing permission to a group in Django
I'm trying to add existing permissions (from auth_permission table) to an existing group (from auth_group) in Django. In Django shell I could do this by the following code: from django.contrib.auth.models import Group, Permission my_group = Group.objects.get(name='mygroupname') perm_change = Permission.objects.get(codename='change_specific') my_group.permissions.add(perm_change) The code above is working as expected, but how can I make it permanent? Should I modify the model or make a custom migration? I think that migration should work fine, but I can't figure out how to do it. (There is a way to turn my shell modifications in a migration?) Thanks. -
Calling all database table names to create a list || pyodbc
I currently have an MSSQL server that has about 60 databases in it. Does anyone know a way to list the database names with a for loop, so that I am able to access each table? The structure should be something like this : for each Database in Server MyList{} = MyList + DatabaseName endfor I can't seem to find any documentation that includes something like this -
FileNotFoundError: [Errno 2] No such file or directory: 'pyerp-master/installed_apps.py'
When i was installing pyerp I got this error. 2021-10-14 10:55:11,449 - DEBUG -settings.py:24 - hello world! Traceback (most recent call last): File "/home/erronny/running workspace/python/django/pyerp-master/manage.py", line 21, in <module> main() File "/home/erronny/running workspace/python/django/pyerp-master/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/erronny/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/erronny/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/home/erronny/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/home/erronny/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/erronny/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/erronny/running workspace/python/django/pyerp-master/pyerp/settings.py", line 80, in <module> with open('%s/installed_apps.py' % BASE_DIR, 'r') as ins_apps_file: FileNotFoundError: [Errno 2] No such file or directory: '/pyerp-master/installed_apps.py' I follow github instruction from here github And i got stucked never found a specific solution i founds after long time and searching on google but it took to much time. -
Django - Add swagger auto schema to DRF tagged functions with `@api_view`
Django - How to add swagger auto schema to DRF tagged functions with @api_view? I have this function view.py @api_view(['POST']) @swagger_auto_schema( request_body=PostSerializer, operation_description="Create a post object" ) def post_create_post(request): But the request body data requirements aren't showing up in Swagger UI. How do you add swagger documentation to endpoints created using @api_view? -
Is it possible to send data while authetication(login) with social-auth-app-django
I am using social-auth-app-django with my django app and everything is working fine but I want to send data to my app when user authenticate with social-auth-app-django for googlw-oauth2. For example: When user clicks on login button that social-auth-app-django uses to send request to google. There I want a text field and a login button. So when user click on login button the text in the text field also go to my django app so after authetication it I can save it in the database. -
How to create 2 types of users in Django?
I want to create 2 types of users in my Django project namely Customer and Company. Both the users have different attributes for registration process. Here is my user odel.py file - class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, is_staff=False, is_superuser=False, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', is_staff) extra_fields.setdefault('is_superuser', is_superuser) return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = None last_name = None first_name = None name = models.CharField(max_length=100) email = models.EmailField(_('email address'), unique=True) contact = models.CharField(max_length=100) USERNAME_FIELD = 'id' REQUIRED_FIELDS = ['contact'] objects = UserManager() @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) I want to create different registration pages for both the users. I searched nearly everywhere but couldn't find a proper solution. Can someone help? -
What is the use of "| safe" when passing variables from Django to React.js?
So from a few articles and few examples I've seen, when passing a variable context to javascript, one would use something like: const variable_name = {{ variable | safe }} I have tried to google but don't seem to find any answer. What is the use of "safe" here? And when do we use it? If you have any reference or articles I could refer to, that would be extremely helpful. Thank you so much! -
How to save django inlineformset default value
I have an inlineformset in which users set a value for ‘SeVsEff’ using a range slider, this saves if users adjust the slider, but I want it to also just save the default value if users do not adjust but this is not currently happening. models.py class SeVsEff(TimeStampedModel): value = models.IntegerField(default=20, blank=False) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py SevseffFormSet = inlineformset_factory( Patient, SeVsEff, fields=("value",), widgets={'value': RangeInput()}, extra=0, min_num=1, validate_min=True, labels=None, ) -
How to filter data in django template?
i have a django model as follows in which i defined categories CATEGORY_CHOICES = ( ('BS', 'Best Selling'), ('TP', 'Trending Product'), ('RP', 'Related Products'), ('NA', 'New Arrival'), ('F', 'Featured'), ('OS', 'on sale'),) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) **and in my Django home page there are multiples sections based on categories like trending product, on sale, featured, new arrivals etc ** what I wanted is to filter data based on that categories and show to the respective section and for that, I registred a template as follows: @register.filter def in_category(Item, category): return Item.filter(category=category) and on my home template i tried to use this filter as follows: {% for object_list in object_list|in_category:Featured %} <div class="col-3"> <div class="custom-col-5"> <div class="single_product"> <div class="product_thumb"> <a href="{{ item.get_absolute_url }}" class="primary_img"><img src="{{ item.image.url }}" alt="product1"></a> <a href="{{ item.get_absolute_url }}" class="secondary_img"><img src="{{ item.image.url }}" alt="product1"></a> <div class="quick_button"> <a href="{{ item.get_absolute_url }}" data-toggle="modal" data-target="#modal_box" data-placement="top" data-original-title="quick view">Quick … -
Django: I want to display the data of current month but i have not found a working query for it. Please assist
Django: I want to display the data of current month but i have not found a working query for it. Please assist. Following is the code for models.py and views.py Views.py def paymentfullreportarchived(request): date=datetime.now().strftime("%Y-%m-%d") allpayments=Payment.objects.filter(Date=date,Status="Archived").order_by('-Date') total= Payment.objects.filter(Date=date,Status="Archived").order_by('-Date').aggregate(Sum('Amount')).get('Amount__sum') or 0 context={ 'payment':'active', 'allpayments':allpayments, 'date':date, 'total':total, } return render(request,'paymentfullreportarchived.html',context) Models.py class Payment(models.Model): Date=models.DateField() User=models.CharField(max_length=50) PatientName=models.CharField(max_length=50) Dentist=models.CharField(max_length=50) Scheme=models.CharField(max_length=50) PaymentMethod=models.CharField(max_length=50) Amount=models.FloatField() Status=models.CharField(max_length=50,default="Pending") -
Total all the model instance's ManyToManyField values
I am building a BlogApp and I am trying to total and count all the ManyToManyField's views values. For Example :- blog_1's views are 50 and blog_2's views are 15, So I am trying to sum and show in one like 65. But when I use Sum then it is showing unexpected strange results like when a view increases from 50 to 51 then it is showing 57 or 67. it should show 51. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) views = models.ManyToManyField(User, related_name='views') views.py def page(request): show_all_views = BlogPost.objects.filter(user=request.user).aggregate(total_views=Sum('views')) context = {'show_all_views':show_all_views} return render(request, 'page.html', context) aggregate is showing or increasing 10 on +1 increase. then i used annotate like show_all_views = BlogPost.objects.filter(user=request.user).annotate(num_views=Count('views')) for total in show_all_views: print(total.num_views) But it is showing 3 3 1 1 1 1 0 I have no idea how I can sum all in for loop. I have tried many times but still not working, Any help would be much Appreciated. -
Weird Django & Angular "No 'Access-Control-Allow-Origin' header is present" when deployed on Cloud server with Nginx
I seem to have a problem with the "No 'Access-Control-Allow-Origin' header is present on the requested resource" on my deployed app. When I am testing these on my localhost:4200 which is angular and localhost:8000 with backend, it works perfectly fine. Below are the Localhost screenshots now this are the deployed angular app What's really weird is that, it only shows the error on this angular component while my other are also similar but works perfectly fine Like this for example I already did the normal cors configurations in django which is INSTALLED_APPS = ['corsheaders'] MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware'] CORS_ORIGIN_ALLOW_ALL = True -
How to enable validators in custom account manager for custom user model in Django?
I created a custom User model called Staff, so that I can login through an email. Doing so requires a custom create_user function, which I created following a tutorial. I also created a custom validator for the EmailField, so when I create a User, only certain domains are accepted. However, writing tests for this function, I found out that it allows creating users with domains outside what I want. This is the custom create_user function: class CustomAccountManager(BaseUserManager): def create_user(self, email, first, last, password, **other_fields): if not email: raise ValueError('You must provide an email address') email = self.normalize_email(email) user = self.model(email=email, first=first, last=last, **other_fields) user.set_password(password) user.save() return user And this is how I am making the test: def test_new_user(self): user = Staff.objects.create_user(email='testuser@sertronicsa.com', first='Test', last='User', password='password') self.assertEqual(user.email, 'testuser@sertronicsa.com') self.assertEqual(user.first, 'Test') self.assertEqual(user.last, 'User') self.assertFalse(user.is_superuser) self.assertFalse(user.is_staff) self.assertFalse(user.is_active) with self.assertRaises(ValueError): Staff.objects.create_user(email='', first='Test', last='User', password='password') with self.assertRaises(ValidationError): Staff.objects.create_user(email='test@user.com', first='Test', last='User', password='password') What is really weird is that from the admin page, if I do not use the domain sertronicsa.com, it doesn't allow me to create the user, like I intend to. What I need help with is figuring out how to make my create_user function use the validator, so it raises the error in the test. … -
My InlineRadios django crispy form doesnt work properly
I use InlineRadios for choice field, the default is using select option and i want to use radio button instead of select option this is my model.py class Member(TimeStampedModel): class Religion(models.TextChoices): ISLAM = 'islam', _('Islam') KRISTEN = 'kristen', _('Kristen') KATOLIK = 'katolik', _('Katolik') HINDU = 'hindu', _('Hindu') BUDHA = 'buddha', _('Buddha') KHONGHUCU = 'khonghucu', _('Khonghucu') LAINNYA = 'lainnya', _('Kepercayaan Lainnya') class Gender(models.TextChoices): MAN = 'man', _('Pria') WOMAN = 'woman', _('Wanita') def get_photo_file_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('uploads/photo/', filename) def get_id_card_file_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('uploads/card/', filename) location = models.ForeignKey(Location, verbose_name = _('member location'),on_delete=models.CASCADE) name = models.CharField(_('member name'), max_length=60) religion = models.CharField(_('religion'), max_length=10, choices=Religion.choices) gender = models.CharField(_('gender'), max_length=5, choices=Gender.choices, default=Gender.MAN) phone_number = PhoneNumberField(_('phone number')) university = models.ForeignKey(University, verbose_name = _('university'), on_delete=models.CASCADE) email = models.EmailField(_('email requested with domain aptisi.or.id')) photo = models.FileField(upload_to=get_photo_file_path, verbose_name = _('photo')) id_card = models.FileField(upload_to=get_id_card_file_path, verbose_name = _('id card')) this is my forms.py class MemberForm(ModelForm): class Meta: model = Member fields = [ 'location', 'name', 'religion', 'gender', 'phone_number', 'university', 'email', 'photo', 'id_card' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.disable_csrf = True self.helper.layout = Layout( 'location', 'name', 'religion', InlineRadios('gender'), … -
why is my workshop textbox not working django?
i have a webpage as shown in the picture below where the admin will select their role but i not sure why my workshop textbox is not working, everything looks perfectly fine to me and the code looks exactly the same. As can be seen from the image below, i can select all but not the workshop textbox register.html <!doctype html> {% extends "home.html" %} {% block content %} {% load static %} <html lang="en"> <head> <style> .button { background-color: #38d39f; border-color: #38d39f; color: white; padding: 10px 20px; text-align: center; display: inline-block; margin: 4px 2px; cursor: pointer; border-radius: 16px; width: 285px; } </style> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- Style --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>SCS staff registration</title> </head> <body> <div class="content"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6 contents"> <div class="row justify-content-center"> <div class="col-md-12"> <div class="form-block"> <div class="mb-4"> <h1>Staff Registration page</h1> </div> <p>Register Page</p> <form method="post"> {% csrf_token %} <div class="form-group first"> <label for="username">Username</label> {{ form.username }} </div> <div class="form-group first"> <label for="firstname">First Name</label> {{ … -
Deploy Django app to Heroku AFTER DATABASE?
I have deployed my django website to Heroku but since the website fields are dependent upon a database that is on my local machine. I've tried using Postgres but the database on Heroku doesn't populate with the data I need it to before the app runs. Has anyone experienced this? Do I need to use an exteranl database on AWS or something (in which case, what is the best way to do this?) -
Django - Django Swagger add custom list of request body params to expect
So for Django Rest Swagger you can add a way to list the params in the request body for example: @api_view(['POST']) @swagger_auto_schema( request_body=Serializer, ) How can I change it so that request_body takes in a list of expected request body attributes? Because I have a post endpoint that should take in a request body of lots of attributes and apply 2 serializers on it, where each serializer will only serialize the proper attributes that it requires. Is there a way to do this? -
Save Image from RSS Feed to Django Image Field
I have a model like this: #models.py class Post(models.Model): cover = models.ImageField(upload_to="news/", blank=True, max_length=255) Then, I pulled the image url from RSS feed using BeautifulSoup4: #views.py def pull_feeds(request, pk): source = Autoblogging.objects.get(pk=pk) url = requests.get(source.url) soup = BeautifulSoup(url.content, "html.parser") cover = soup.find('media:content')['url'] Post.objects.create(cover=cover) The content feed is something like this <media:content url="https://travelcommunication.net/wp-content/uploads/2021/10/Raffles-Hotels-Bring-Legendary-Hospitality-Experience-to-Romantic-Udaipur-TRAVELINDEX-TOP25HOTELS-500x300.jpg" width="500" height="300" medium="image" type="image/jpeg"/> But it only save the url, not the image file. How to save the actual image file instead of url to that image? -
Display items using checkboxes and POST only the checked ones
I am working on a sort of attendance check system which is a webpage. Actually I want a student when registering to be able to select the courses he is enrolled for through the use of checkboxes and then later get this data through POST. How can I achieve this using django modelforms?, how is the rendering done in the template? And how should I POST the data from the checkboxes in my views? Need help please. Thanks. -
Price start DateTimeField and End DateTimeField duration Show the price django models
I will Input start DateTimeField and End DateTimeField from Admin Panel. Offer Price will be shown when the start time will match now() time. I mean when the current time match starts DateTimeField The the price will be shown in the HTML form. similarly, when the End DateTimeField matches the current time the offer price will be shown OFF from the HTML form. model.py ------- class Product(models.Model): price = models.DecimalField(max_digits=6, decimal_places=2) offer_price = models.DecimalField(max_digits=6, decimal_places=2) duration = models.DurationField('duration') offer_price_start_date = models.DateTimeField(blank=True, null=True) offer_price_end_date = models.DateTimeField(blank=True, null=True) def duration(self): return self.offer_price_end_date - self.offer_price_start_date views.py -------- def product_detail(request): product_data = Product.objects.all() context = { 'product': product_data } return render(request, 'show.html', context) show.html --------- {% if product.duration %} <a> Before Price ${{ product.price }} </a> <a> Now ${{ product.offer_price }} </a> {% endif %} -
Change choices list in child model Django
I have a model that is being inherited by another one and has a field that has choices. Is there any way I can change the choices options, or append a new item to choices on the inherited model level? class ModelA(PolymorphicModel): choice1 = "choice1" choice2 = "choice2" CHOICES = ( (choice1, "Choice 1"), (choice2, "Choice 2"), ) method = models.CharField(max_length=30, choices=CHOICES) class ModelB(ModelA): # In this model, I have to exclusively add `choice3` to choices. -
Django algolia search: How to create search for multiple models
In Django I have 4 different models class Baby(model.Model): name = ... #(babys name) description = ... .... other fields not common class BabyStore(model.Model): name = ... #(name of the shop) description = ... .... other fields not common class BabySitter(model.Model): name = ... #(babysitter name) description = .... .... other fields not common class BabyDoctor(model.Model): name = ... #(babydoctors name) description = ... .... other fields not common As per https://github.com/algolia/algoliasearch-django we have to register each model import algoliasearch_django as algoliasearch from .models import YourModel algoliasearch.register(YourModel) This will create seperate index for each model. In my case i want to have a search UI for all of them together and use the model as the facet. eg: So how to use multiple indexes and create a single search I know within each index, we can have facets. But here Along with that i want to use each index as a facet itself -
How transfer data from on list to another in Django?
I'm doing a small to-to list, I'm stuck in views.py, there are to-do tasks, in-progress tasks and done tasks, I want to move a task from the to-do task list to the in-progress task list, I can't figure out how to delete the data in the to-to task and make new data same as to-do task in the in- progress task at the same time. It would be great if anyone can help, I'm totally new to Django. Thanks. ''' models.py class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.text[:60] + "..." class Progress(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.ForeignKey(Todo, on_delete=models.CASCADE) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.text ''' -
What's the difference between the trans tag and the _() function in templates?
I mean you can do: {% load i18n %} {{ trans 'some string' }} Or {{ _('some string') }} Both are discoverable by makemessages, and rendered correctly. At least with Django 2.0.2. -
Django migration not working properly on Heroku
I have deployed a Django App like 3 months ago and i was able to migrate changes easily on the heroku bash. Right now i'm trying this: heroku run python manage.py migrate Also tried this: heroku run python manage.py migrate --no-input And i tried accesing to the heroku bash like this: heroku run bash And then run: ~ $ python manage.py migrate All this commands seems to work: https://i.stack.imgur.com/JWW6S.png But they don't. When i tried to migrate again, i thought it would show me the typical No migrations to apply.. But this is not the case ¿What should i do to migrate changes?