Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Ajax + dependent dropdown
In my Django project I need dependent dropdown input (registration form: date & timeslot). However, AJAX does not display the dependent dropdown menu correctly (timeslot). I have based everything on This example, but I can't find out what I am doing wrong. The variable (id_timeslots) that is passed to AJAX by load_timeslots() in view.py has the correct length throughout. The timeslot dropdown menu, however, is empty (not even a "---" and very small in size. Hope someone can point me in the right direction. models.py class Day(models.Model): day = models.CharField(max_length=30) def __str__(self): return self.day class TimeSlot(models.Model): day = models.ForeignKey(Day, on_delete=models.CASCADE) timeslot = models.CharField(max_length=30) reserved = models.BooleanField(default=False) def __str__(self): return self.timeslot class Person(models.Model): name = models.CharField(max_length=100) email = models.EmailField() day = models.ForeignKey(Day, on_delete=models.SET_NULL, null=True) timeslot = models.ForeignKey(TimeSlot, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py class TimeSlotForm(forms.ModelForm): class Meta: model = Person fields = ('name','email', 'day', 'timeslot') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['timeslot'].queryset = TimeSlot.objects.none() view.py class ExpSignup(TemplateView): template_name = 'thesis_scheduler/index.html' def get(self,request): timeslotdata = TimeSlotForm() return render(request, self.template_name, {'timeslotdata':timeslotdata}) def load_timeslots(request): day_id = request.GET.get('day') id_timeslots = TimeSlot.objects.filter(day=day_id, reserved=False) return render(request, 'thesis_scheduler/index.html', {'id_timeslot': id_timeslots}) url.py urlpatterns = [ path('', views.ExpSignup.as_view(), name='Registration'), path('ajax/load-timeslots/', views.load_timeslots, name='ajax_load_slots'), # <-- this one here ] index.html … -
How to add datetime format minute on each loop in pyhton django
This is my code. i want to add 25 minute on loop then save in DB, i try one solution but its just add 1 time add 25 minute. i want 1st time system enter actual datetime on second loop in datetime add 25 minute. service_obj = Service.objects.get(id=1) startingDate = datetime.strptime(startingDate, '%d-%m-%Y %I:%M %p').strftime("%Y-%m-%d %H:%M:00+00") service_fee = StaffServiceFee.objects.filter(service_id=service_obj.id).values_list('service_charges', 'staff_user').order_by('id') for service_fees in service_fee: obj = UserAppointments.objects.create(customer_id=1, staff_user_id=service_fees[1], service=service_obj, status="1") obj.date_time = startingDate obj.save() -
How to create Django-Rest-framework permission interface like django-admin provide | is there any library available for that?
How to create a User interface like django-admin provide for granting/revoking permissions for Django-Rest APIs. and automatically handle it. I mean I need a generic functionality, admin user can grant/revoke permissions or APIs to a particular group. I am searching from last 3 hours but found nothing Thanks -
allauth - enforce new user to provide mandatory fields
I'm trying to add django-allauth to a custom user model. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True, help_text="A verification link will be sent to this email-id") name = models.CharField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Please enter a valid phone number.") mobile = models.CharField(max_length=16,validators=[phone_regex],null=True,) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['mobile','name'] Here's my custom form class CustomUserCreationForm(UserCreationForm): password2=None def signup(self, request, user): user.mobile = self.cleaned_data['mobile'] user.name = self.cleaned_data['name'] user.save() return user class Meta(UserCreationForm): model = User fields = ('name','email','mobile') and in settings.py, I've ACCOUNT_FORMS = {'signup':'users.forms.CustomUserCreationForm'} When I open the /signup/ page, the custom form gets displayed and the additional values get saved. However, when I click on the Sign In and then click on the Google, and then provide the email and password of a user that is not in the system, after the redirect the user gets created without asking for additional fields. How can I enforce the new user to provide mandatory fields, after getting authenticated through social? (Please let me know if I need to provide additional settings or any any other code) Thanks -
Using a Textfield with JSON instead of a ForeignKey relationship?
I am working on a project where users can roll dice pools. A dice pool is, for example, a throw with 3 red dice, 2 blue and 1 green. A pool is composed of several dice rolls and modifiers. I have 3 models connected this way: class DicePool(models.Model): # some relevant fields class DiceRoll(models.Model): pool = models.ForeignKey(DicePool, on_delete=models.CASCADE) # plus a few more information fields with the type of die used, result, etc class Modifier(models.Model): pool = models.ForeignKey(DicePool, on_delete=models.CASCADE) # plus about 4 more information fields Now, when I load the DicePool history, I need to prefetch both the DiceRoll and Modifier. I am now considering replacing the model Modifier with a textfield containing some JSON in DicePool. Just to reduce the number of database queries. Is it common to use a json textfield instead of a database relationship? Or am I thinking this wrong and it's completely normal to do additional queries to prefetch_related everytime I load my pools? I personally find using a ForeignKey cleaner and it would let me do db-wise changes to data if needed. But my code is making too many db queries and I am trying to see where I can improve it. FYI: … -
Unsupported media type \"application/x-www-form-urlencoded\" in request
I am using ViewSets for Profile model but if I send request in Postman I am getting following error. Unsupported media type \"application/x-www-form-urlencoded\" in request But I do not have a idea What I am doing wrong. class ProfileView(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer parser_classes = (MultiPartParser,) permission_classes = (IsOwnerOrAdmin,) def get_queryset(self): return super(ProfileView, self).get_queryset().filter(user=self.request.user) def get_object(self): qs = Profile.objects.filter(user=self.request.user).first() return qs def put(self, request): file = request.data['file'] return Response(status=204) I have configured in settings.py file as well. But I cannot work this out. Any help would be appericated. Thanks in advance -
Setting up correct path using the package django-docs
I am trying to use django-docs (https://pypi.org/project/django-docs/) package to publish my documentation created with sphinx. But somehow I fail to set the correct path. I followed the documentation and I think this is where the problem is: DOCS_ROOT = os.path.join(PROJECT_PATH, '../docs/_build/html') The documentation says that for DOCS_ROOT I should use: Absolute path to the root directory of html docs generated by Sphinx (just like STATIC_ROOT / MEDIA_ROOT settings). So I tried with: DOCS_ROOT = os.path.join(BASE_DIR, '/doc/_build/html'), I also tried DOCS_ROOT = os.path.join(BASE_DIR, '/doc/_build/html'), And I also tried moving my doc folder out of the project and do ..'/doc/_build/html And I also hardcoded the absolute path but still no success. This is my folder structure: myproject manage.py doc (this is the doc folder where my sphinx doc is) ... ... I think it is something easy but I am simply stuck with this one.... Any help is of course very much appreciated. Thanks in advance! -
Trouble with joining tables together
I'm trying to join tables by using Django queryset, but for some reason it keeps throwing an error. Tables are structured as below. class Platform(models.Model): P_key = models.AutoField(primary_key=True) P_url = models.CharField(max_length=100) P_userkey = models.IntegerField(default=0) P_name = models.CharField(max_length=10) objects = models.Manager() class User_info(models.Model): U_key = models.AutoField(primary_key=True) U_name = models.CharField(max_length=20) U_img = models.CharField(max_length=100) U_info = models.CharField(max_length=100) U_sudate = models.CharField(max_length=20) P_key = models.ForeignKey(Platform, on_delete=models.CASCADE) objects = models.Manager() This is the code written to join two tables together. queryset = User_info.objects.all().prefetch_related("Platform") queryset = User_info.objects.all().select_related("Platform") queryset = Platform.objects.all().select_related("User_info") And the following is the error -> django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'Platform'. Choices are: P_key. I've tried a number of query sets but I wasn't able to get far. -
Django test, waiting for a modal
I'm trying to write a django test that clicks a button and then waits for a modal to open and check it is the right modal. I'm using selenium and firefox. This is my test class MySeleniumTests(LiveServerTestCase): #fixtures = ['user-data.json'] def setUp(self): self.admin = User.objects.create_user(username='JohnLennon', password = 'JohnLennon') self.admin.is_superuser = True self.admin.is_staff = True self.admin.save() self.researcher = User.objects.create_user(username='PaulMcCartney', password = 'PaulMcCartney') @classmethod def setUpClass(cls): super(MySeleniumTests, cls).setUpClass() chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chromedriver_path = '/usr/local/bin/chromedriver' cls.selenium = webdriver.Chrome(chromedriver_path, chrome_options=chrome_options) cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super(MySeleniumTests, cls).tearDownClass() def researcher_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/interface/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys(self.researcher.username) password_input = self.selenium.find_element_by_name("password") password_input.send_keys(self.researcher.password) self.selenium.find_element_by_id('id_log_in').click() def test_researcher_login_to_researchUI(self): self.researcher_login() url = self.selenium.current_url.split(':')[2][5:] self.assertEqual(u'/interface/', url) def test_new_study(self): self.researcher_login() # check new study opens WebDriverWait(self.selenium, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='id_new_study']"))).click() #self.selenium.find_element_by_id("id_new_study").click() WebDriverWait(self.selenium, 10).until(EC.presence_of_element_located((By.ID, "modal-title"))) self.assertEqual(u'New Study', self.selenium.find_element_by_id("modal-title")) This is the button in the html I'm trying to click <button id="id_new_study" type="button" style='width:100%;' class="btn btn-primary" onclick = "modal_form('/interface/add_study/')" >New Study</button> This is the error message I get Traceback (most recent call last): File "/home/henry/Documents/Sites/Development/web-cdi/webcdi/researcher_UI/tests.py", line 70, in test_new_study WebDriverWait(self.selenium, 10).until(EC.presence_of_element_located((By.ID, "modal-title"))) File "/home/henry/Documents/Sites/Development/web-cdi/env/lib/python3.6/site-packages/selenium/webdriver/support/wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: I know the modal does open when I'm running the application, because I can use it. I cannot get … -
Django. Create custom object without save and return like a queryset
I need create empty objects without save in data base(like a custom object for a specific conditions) and add this object to queryset. I have wtritten code: # create empty queryset queryset = MajorMinor.objects.none() major_minor = MajorMinor.objects.model dealer = User.objects.model dealer.email = 'test@gmail.com' grower = User.objects.model grower.email = 'test@gmail.com' major_minor.major = dealer major_minor.minor = grower # add my obj to queryset queryset |= major_minor return queryset but i have had an error: type object 'MajorMinor' has no attribute 'model' -
Django custom count based on ORM filter
I am trying to gather additional information based on previously filtered data, like this count(distinct batch_id) as batches, sum(files) as files The result is influenced by the previous filtering eg. .filter(batch_id__gte=165) I tried to clone the QuerySet and annotate aboves SQL .annotate( batches=Count('batch_id', distinct=True), batch_files=Sum('files') ) but this doesn't work because then the SQL is appended to the existing SELECT query Is there an easy way of getting a second query with a custom SELECT part while keeping the WHERE part? -
[Python3][Django]how to get masklen from model
the model as below to store the ip address in postgres. from django.db import models from netfields import InetAddressField, CidrAddressField, NetManager class TestModel(models.Model): client_ip = InetAddressField(default='0.0.0.0/0', store_prefix_length=True) I want to get the IP masklength directly through the model. but I can't find a attribute correspondig to postgresql inet masklen https://www.postgresql.org/docs/9.4/functions-net.html -
Django: Get model from string without app_label
I Have a Django website which uses two databases. The models for the secondary database have been added to the same models.py but with a meta class for each of them to handle the database routing. class Meta: app_label = 'database_name' managed = False db_table = 'table_name' Now I'm trying to get a model by only using a string, however every example I've seen/tried seems to require using the app_label. apps.get_model('scripts', 'model_example') Using the app name of the actual app that everything is in results in a LookupError: App 'scripts' doesn't have a 'model_example' model. apps.get_model('database_name', 'model_example') Using the app_label that the actual models have in their meta class results in a LookupError: No installed app with label 'database_name'. I also can't seem to figure out how to solve this using AppConfig or ContentType as some other posts have mentioned. To be clear: I don't have an app with the database_name, its only used for routing. I'm looking for a way to retrieve a model by using a string, get_model() functions seem to require an actually existing app. Is there any way for me to get the model or do I need structural changes? and if so, what changes? -
How to call stored mysql procedures from django
I have 2 databases in django project: Django info (default migrations) Database with info I want to display on page. To work with second database I need to inspect it and work with raw(). But can I call stored procedure passing there variable and display it? I can't understand logic. Found this for psql , but where can I work with default python db connector? In views or creating simple python script? -
Run kubectl cronjob reusing a deployment template
I have a pod with 2 containers: a django webserver, and a cloud sql proxy. I want to run a cronjob every day (some django manage.py command). Ideally, I'd like a new container to be created in one of my running pods, by copying the webserver already running there. Find pod A Copy django container from pod A Start new django container in pod A execute command in new container of pod A shut down new container of pod A From my understanding, executing a kubernetes CronJob will create a new pod of its own. That means I need to copy everything, including volumes and proxy container. I tried to do that manually (by copypasting all the pod conf from the deployment into the CronJob conf) --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: SomeName labels: environment: SomeEnv spec: replicas: 1 template: metadata: labels: app: SomeApp name: SomeName2 environment: SomeEnv spec: containers: - image: gcr.io/org/someimage:tag name: ContainerName imagePullPolicy: IfNotPresent volumeMounts: - name: app-secrets mountPath: /var/run/secrets/app readOnly: true env: - name: SECRET_KEY valueFrom: secretKeyRef: name: app-secrets key: django - image: gcr.io/cloudsql-docker/gce-proxy:1.11 name: cloudsql-proxy command: ["/cloud_sql_proxy", "--dir=/cloudsql", "-instances=org:zone:db=tcp:5432", "-credential_file=/secrets/cloudsql/credentials.json"] volumeMounts: - name: cloudsql-instance-credentials mountPath: /secrets/cloudsql readOnly: true - name: ssl-certs mountPath: /etc/ssl/certs - … -
How to display contents based on their category on button click in Same page in Django?
I am working on a portfolio project. where I have to categorize the projects based on their Categories. I have given buttons for each categories and I have to display each contents of individual categories on Button Clicks below them. Eg. I have 2 projects in Design category. When I click Design I should get these two projects below the button. I tried filtering of contents and successfully displayed them in other page but unable to display them in the same page. Here is my Code: Models.py class PortfolioCategory(models.Model): projectCategory = models.CharField(max_length=200) projectSummary = models.CharField(max_length=300) projectLink = models.CharField(max_length=200) class Meta: verbose_name_plural = "categories" def __str__(self): return self.projectCategory class Portfolio(models.Model): projectName = models.CharField(max_length=250) projectLink = models.CharField(max_length=50, default="") projectImage = models.ImageField(upload_to="img/Portfolio/") projectContent = models.TextField(default="") projectCategory = models.ForeignKey( PortfolioCategory, verbose_name="Category", on_delete=models.CASCADE) def __str__(self): return self.projectName Views.Py def projectLink(request, projectLink): category = [c.projectLink for c in PortfolioCategory.objects.all()] if projectLink in category: categoryItems = Portfolio.objects.filter( projectCategory__projectLink=projectLink) myProjects = categoryItems.all() return render( request, "main/home.html#projectLink", { "projects": myProjects, "navbar": navbar, } ) projectContent = Portfolio.objects.get(projectLink=projectLink) return render( request, "main/projectItem.html", { "project": projectContent, "navbar": navbar, } ) def homepage(request): return render( request=request, template_name="main/home.html", context={ "portfolios": Portfolio.objects.all, "categories": PortfolioCategory.objects.all, "navbar": navbar, "socialLinks": socialIcons, "skillset": skills, }) template <nav id="nav" … -
"<Story: title>" needs to have a value for field "id" before this many-to-many relationship can be used
I added code, so the user can connect story maximum with 2 genres, when I try to save story it brings error in title. class Story(models.Model): title = models.CharField(max_length=255) genre = models.ManyToManyField(Genre) alias = models.CharField(max_length=255, null=True, blank=True) def save(self, *args, **kwargs): self.alias = slugify(self.title, 'ru') return super(Story, self).save(*args, **kwargs) def clean(self, *args, **kwargs): if self.genre.count() > 2: raise ValidationError('Error') super(Story, self).clean(*args, **kwargs) -
add time when we save a Timefield in django
I have a dateTime field in a model. The dateTime field named breakfast_start_time takes an input. I have to save another variable or timefield(whichever is better) named breakfast_attendence_start_time whose value should be automatically saved 15 minutes less than the breakfast_start_time. For this we use def save(self, *args, **kwargs): #do something super().save(*args, *kwargs) I am trying to do breakfast_attendence_start_time = breakfast_start_time - time(15,0) but it is giving error that class TimeField does not define '_sub_', so the '-' operator cannot be used on its instances -
Why getting duplicated log info when using django?
When try to get log . I don't know why my django project is duplicating my log message as different format.Where should I fixing this duplicate problem. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(levelname)s - %(module)s - %(message)s - %(asctime)s', }, 'json': { '()': 'sit.providers.libs.logutils.JSONFormatter' }, 'custom': { 'format': '[ %(asctime)s - %(levelname)s ] %(message)s' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'FluentHandler': { 'level': 'DEBUG', 'class': 'fluent.handler.FluentHandler', 'formatter': 'json', 'tag': 'integration' }, 'file': { 'level': 'ERROR', 'class': 'sit.providers.libs.logutils.MakeErrorFileHandler', 'formatter': 'default', 'filename': LOG_FILE_PATH }, 'update_error': { 'level': 'ERROR', 'class': 'sit.providers.libs.logutils.MakeUpdateErrorFileHandler', 'formatter': 'default', 'filename': LOG_FILE_PATH }, 'jenkins': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'custom' }, }, 'loggers': { '': { 'handlers': ['console', 'FluentHandler', 'file', 'jenkins'], 'propagate': True, 'level': 'INFO', }, 'update_error': { 'handlers': ['console', 'FluentHandler', 'update_error', 'jenkins'], 'propagate': True, 'level': 'INFO', }, 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, } } and ı am using logger as : logger.info("asdad") the output is : INFO - jeep - This car is not located in america. Skipping service charge. - 2019-10-04 07:32:50,662 [ 2019-10-04 07:32:50,662 - INFO ] … -
How to let Chroniker update my table in a cronjob?
I have an issue with my Postgresql database, I'm running my app in a container. I have a custom command in my Django app working minutely, when it start, my custom command check how many proxies there are and get the max ID and choose a random one. It works well, but something gone wrong after, when I check if the proxy didn't work in my script, I delete it from my database, my database accept to delete it, nothing gone wrong here. One minute after, when the command start again my command think it have the same number of proxy, when I check my database, I've got one less, so after some minutes my app choose randomly a proxy id who didn't exist. from django.db.models import Max import random def get_proxy(): max_id = Proxy.objects.all().aggregate(max_id=Max("id"))['max_id'] print(max_id) while True: pk = random.randint(1, max_id) proxy = Proxy.objects.filter(pk=pk).first() if proxy: return proxy When the issue append for example max_id return 680, whereas I've got only 600 id in my database. def get_proxy(): max_id = Proxy.objects.all().aggregate(max_id=Max("id"))['max_id'] print(max_id) print('max_id') while True: pk = random.randint(1, max_id) proxy = Proxy.objects.filter(pk=pk).first() if proxy: return proxy def scrapp(): url_api = "https://*************" url_objects = ******.objects.all() proxy = get_proxy() print('proxy.id') print(proxy.id) … -
Not able to insert value into database on django form submit
I have created a form that takes 2 inputs from a user and I want to add current date-time and currently logged in user when I receive user inputs in the POST method. Help me to write a view to edit the form. In the below code I am not able to assign value to blog_author. models.py (I am accepting blog_name and blog_details from user) class blogs(models.Model): blog_name = models.CharField(max_length=100,blank=False,null=False) blog_details = models.TextField(blank=False,null=False) blog_author = models.CharField(max_length=100,blank=True,null=True) blog_created_at = models.DateTimeField(auto_now=True) forms.py #with only two fields class blogForm(forms.ModelForm): class Meta: model = blogs fields = ('blog_name','blog_details') views.py #validation of form def create_blog(request): if request.method == 'POST': form = blogForm(request.POST) if form.is_valid(): form.save(commit=False) form.cleaned_data['blog_author'] = request.user form.save() form = blogForm() context = {"form":form} return render(request,'create_blog.html',context) -
getting (" placeholder ") input attribute in django
I want to get my placeholder input attribute, when a user submit the form. How can it be done in django framework? for example, I want it to be done like this: def get_attr(request): plh = request.POST.get('placeholder') I know that the code above isn't correct, because the POST method doesn't have that attribute. So, what can I do? -
Retrieve query from django ORM
I created a Company in my django app, two or more person can login with the same company. I want to show the data of one user of the company to the other user of the company. To simplify: If user1 of a company creates an object, then it should be visible to all the users of that company Models.py class User(AbstractUser): is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) class Company(models.Model): company_name = models.CharField(max_length=255, default=0) company_email = models.EmailField(max_length=255, default=0) company_phone = models.CharField(max_length=255, default=0) def __str__ (self): return self.company_name class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='comapany_owner') def __str__ (self): return self.user.username class Product(models.Model): product_name = models.CharField(max_length=255, default=0) product_priceperunit = models.IntegerField(default=0) product_owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='product_owner') Views.py @method_decorator([login_required, employee_required], name='dispatch') class ProductsTableView(ListView): model = Product context_object_name = 'product' template_name = 'packsapp/employee/employeeProductsTable.html' def get_queryset (self): queryset = Product.objects.filter(product_owner=self.request.user.employee) return queryset Here I am extracting the data by employee. How can I modify the query to give the data of all the employee of the same company ?? -
How to remove default value '0' in django forms using css only
I'm making django forms which requires a default value while making migrations into it but I want to show this :"--------" by default, not 0 using css only: my django form looks like this: <div class="row"> <div class="col-md-6 col-sm-8 col-12"> <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Save</button> <a href="{% url 'employee:products_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </form> </div> </div> In this img, Instead of showing 0 I want "------", but must be done only with css. -
get_user(uid).email returns None if user is logged in by facebook in firebase_admin django
Code: import firebase_admin from firebase_admin import auth from firebase_admin import credentials from firebase_admin.auth import get_user cred = credentials.Certificate("cred.json") firebase_admin.initialize_app(cred) verified = auth.verify_id_token(id_token=token) print(get_user(verified["uid"]).email) output of this code will be None if user logged in with facebook, but if user is logged in with google then it will return email of user