Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model not Associating with another model object
I am using Django to create an application where I have an Employee model that needs to be associated with a Company model. I am able to associate the User model with the Employee model correctly, but I am having trouble associating the Company object with the Employee object. My view: from django.shortcuts import render from django.http import HttpResponse from company.models import Company from .models import Employee from .forms import UserForm, CompanyForm from django.contrib.auth.models import User import random, string from django.db import IntegrityError def new(request): # Initialize forms user_form = UserForm(request.POST or None) company_form = CompanyForm(request.POST or None) # Check if the request is a POST request if request.method == 'POST': # Check if both forms are valid if user_form.is_valid() and company_form.is_valid(): email = user_form.cleaned_data['email'] # Check if a user with this email already exists try: user = User.objects.get(email=email) user_created = False except User.DoesNotExist: user = User(username=email, email=email) random_password = User.objects.make_random_password() user.set_password(random_password) user.save() user_created = True # Save the company form data company = company_form.save() # Check if an Employee already exists for this user try: employee = Employee.objects.get(user=user) employee_created = False except Employee.DoesNotExist: employee = Employee(user=user, company=company) employee.save() employee_created = True # Return appropriate response based on what was … -
Circular import during run multiprocessing
I have example like this: File models.py from django.db import models class Document(models.Model): name = models.CharField(max_length=20) text = models.CharField(max_length=200) File db_request.py from .models import Document def get_all_documents(): return Document.objects.all() File services.py from multiprocessing import Process from .db_request import get_all_documents def stream(): docs = get_all_documents() def start_streams_documents(): pr = Process(target=stream) pr.start() pr.join() File admin.py from .models import Document from .services import start_streams_documents @admin.register(Document) class MachineAdmin(admin.ModelAdmin): list_display = ('name','text') change_list_template = 'admin/document_table_changelist.html' def get_urls(self): urls = super().get_urls() my_urls = [path('start_streams/', self.start_streams)] return my_urls + urls def start_streams(self, request): start_streams_documents() return HttpResponseRedirect("../") If i call in services.py stream, i get an error Apps aren't loaded yet.. Ok, let's add import django django.setup() to db_request.py at first. Then i'll get an error circular import. The example is as simple as possible, what am I doing wrong? If i call stream without multiprocessing, it will work Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 120, in spawn_main exitcode = _main(fd, parent_sentinel) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 130, in _main self = reduction.pickle.load(from_parent) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fr3st\Desktop\Screener V3\app\documents\services.py", line 3, in <module> from .db_request import get_all_documents File "C:\Users\fr3st\Desktop\Screener V3\app\documents\db_request.py", line 2, in <module> django.setup() File "C:\Users\fr3st\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
How to write a classed based view in Django when we have an Order model that has multiple OrderRow records?
I have an Order model such as below: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=1, choices=ORDER_STATUS, default="D") def __str__(self) -> str: return self.customer.name + " Order No. " + str(self.pk) and OrderRow: class OrderRow(models.Model): product = models.ForeignKey("products.Product", on_delete=models.CASCADE) quantity = models.IntegerField() unit = models.ForeignKey("products.Unit", on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self) -> str: return self.product + " " + self.quantity + " " + self.unit I need to write a classed based view than when user enters in this page a new order automatically created for current user and the user be able to add OrderRows to the current Order. -
celery redis key unacked issue
I am using the Glitchtip service, which employs Celery to initiate worker processes for job processing. This setup involves a combination of Celery and Redis, where Redis serves as a message broker. Upon sending a substantial number of requests, I've noticed a spike in the Redis key named "unacked," which eventually causes Redis to run out of memory. In my environment configuration, I have set the following parameters: CELERY_ACKS_ON_FAILURE_OR_TIMEOUT is set to False. CELERY_ACKS_LATE is set to True. I'm wondering if there are any additional environment parameters that I should consider setting in order to better control the processing rate. Your assistance in this matter is greatly appreciated. Ref -> https://gitlab.com/glitchtip -
img not showing in html, while online urls are working
I'm trying to build my portfolio using django but i have trouble with it. I cannot add my photo in that. Even if i mentioned the correct path it's not displaying while online image are displaying properly.This where my profile photo is located <!-- Title Bar --> <section class="section-gap"> <div class="row featurette"> <div class="col-md-7"> <h2 class="fs-1 featurette-heading">PARAMASIVAN T</h2> <div class="fs-2 text-muted">Web Developer</div> <p class="lead">“Digital design is like painting, except the paint never dries.”</p> </div> <div class="col-md-5"> <img src="D:\Django_Projects\porfolio\mysite\myapp\templates\myapp\profile.png" alt="profile"> </div> </section> what is the solution for this problem? -
Django Polymorphic behaviour (Custom ForeignKey) without using GenericForeignKey
I'm working with a legacy DB that has fields like edited_by_type, and edited_by_id in many tables. This is basically a polymorphic relation for RubyOnRails persons. This represents a FK relation to multiple models using combinations of these two fields. for example, the value of edited_by_type can be either user, admin, or client. These are 3 different tables. so now you can guess that it's basically a unique constraint of edited_by_type, and edited_by_id together, where edited_by_type is used to determine the type of person (table) and then query that table using edited_by_id. I have a fairly good understanding of Django's GenericFK field that uses the contentType table internally. but since this is a legacy DB and I don't want to use the ContentType table at all it requires creating migrations and entries in the contenttype table. What I'm looking for is a customFk or (even customGenericFK) solution that somehow manages this and allows us to query the db as easily as we can. e.g something like the below (open to any other approach that doesn't involve creating a CustomFK). here is what I've tried so far. class CustomFK(models.ForeignKey): def __init__(self, fk_models, on_delete, **kwargs): for model in fk_models: super().__init__(to=model, on_delete=on_delete, **kwargs) # … -
I am trying to convert a WEBP image to JPEG and create a ZIP file but when I type in the ZIP it is still WEBP
image.read() is the image stored with django which is in WEBP format. ` image_read = BytesIO(image.read()) image_read.seek(0) image_converted = BytesIO() original_image = Image.open(image_read).convert('RGB') original_image.save(image_converted, format='JPEG') image_converted.seek(0) image_data = image_converted.getvalue() zip_file.writestr(f'{filename}', image_data) ` A zip file images in JPEG format -
Django form field feed with javascript produced list
I'm learning Django through a recipe posting website, in the recipe form I want to pass an ingredient list that is created with a java script function on the fly. I have two buttons, one to create the list, and the final submit button when the recipe form is ready. The problem is that every time the ingredients "adding ingredient button" is clicked, the form is submitted, since it is not valid it resets the whole form. How can I integrate the java script without submitting the form? I've tried many solutions that I've seen everywhere to no avail, so any help is welcome. Model. class Recipe(models.Model): """Represents the whole recipe description""" recipe_name = models.CharField(max_length=100, default=None) user_name = models.ForeignKey(User, on_delete=models.DO_NOTHING) description = models.TextField(max_length=500, help_text='Enter a brief description of the recipe') ingredients = models.TextField(max_length=1000, help_text='enter all the ingredients with quantities') cooking_time = models.CharField(max_length=50) preparation = models.TextField(max_length=3000, help_text='Enter the steps to prepare the recipe') date = models.DateField(auto_now_add=True) script. class Recipe(models.Model): """Represents the whole recipe description""" recipe_name = models.CharField(max_length=100, default=None) user_name = models.ForeignKey(User, on_delete=models.DO_NOTHING) description = models.TextField(max_length=500, help_text='Enter a brief description of the recipe') ingredients = models.TextField(max_length=1000, help_text='enter all the ingredients with quantities') cooking_time = models.CharField(max_length=50) preparation = models.TextField(max_length=3000, help_text='Enter the steps to … -
Django blog UserProfile model
I am creating a Django blog app and I already set up a Post and Comment model both linked with the built in Django User model via these fields below: POST MODEL writer = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blogs" ) COMMENT MODEL writer = models.ForeignKey( User, on_delete=models.CASCADE, related_name='user_comments') If I add a UserProfile model to this blog app, would I need to change the foreign key relationship in my post model to this: writer = models.ForeignKey( UserProfile, on_delete=models.CASCADE, related_name="blogs" ) Thanks P.S. I want only admin users to have profiles and to be able to click on their profiles to view the posts they have created. Regular users do not have the ability to create posts. They can only comment and like the posts. -
Urls in CSS files not getting signed through django-storages
For example, my css code has this image file: background: url('/static/studyspot5/images/shapes/footer_sass.png'); And it does not render on my AWS site I have the following relevant code in my settings.py: if USE_S3: STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' MEDIA_URL = f'https://{CLOUDFRONT_DOMAIN}/{MEDIAFILES_LOCATION}/' MEDIA_ROOT = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/{MEDIAFILES_LOCATION}/' STATIC_URL = 'https://%s/%s/' % (CLOUDFRONT_DOMAIN,STATICFILES_LOCATION) STATIC_ROOT = 'https://%s/%s/static/' % (AWS_S3_CUSTOM_DOMAIN,STATICFILES_LOCATION) STORAGES = { "default": {"BACKEND": 'custom_storages.MediaStorage'}, "staticfiles": {"BACKEND": 'custom_storages.StaticStorage'}, "OPTIONS": { "bucket_name": AWS_STORAGE_BUCKET_NAME, "region_name": AWS_S3_REGION_NAME, # "verify": AWS_S3_VERIFY, "signature_version": AWS_S3_SIGNATURE_VERSION, "cloudfront_key_id": AWS_CLOUDFRONT_KEY_ID, "cloudfront_key": AWS_CLOUDFRONT_KEY, "custom_domain": CLOUDFRONT_DOMAIN, }, } The CSS file (and all other static content) is served as a signed URL just fine, e.g. using the following code: <link rel="stylesheet" href="{% static 'studyspot5/css/style.css' %}"> But for those urls inside of CSS files, it will only pass the url of the file, without signing it (no parameters). Here is the resulting request headers. Note the referer URL is signed, but the darn background image from the CSS is not! -
how can i send file from s3 into the user in django?
i have a website , this website you can use it to upload a file. after that the users will be able to download what you have uploaded in that website. i upload a file , and this file is getting saved inside a bucket in AWS-S3. now how can i read that file from the bucket and send it to the user ? this is my function for donwloading : class Download(View): def get(self, request): try: if request.session["language"] == "en": the_path_of_templates = "website/en/" else: the_path_of_templates = "website/ar/" except: the_path_of_templates = "website/en/" ######################################################### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ######################################################### try: the_file = KarafetaProduct.objects.all()[0] with open(os.path.join(BASE_DIR, str(the_file.file)), "rb") as file: file_data = file.read() response = HttpResponse(file_data, content_type='application/vnd.microsoft.portable-executable') response['Content-Disposition'] = 'attachment; filename="{}"'.format(str(the_file.name)) return response except: return render(request=request, template_name=f"{the_path_of_templates}home.html") this is the link of the file in s3 : karafeta-bucket.s3.amazonaws.com\Python-3.11.5_3_q9ZN0gC.exe -
Django Email Configuration Issue: ConnectionRefusedError [WinError 10061]
Question: I'm encountering a ConnectionRefusedError in my Django project when trying to send emails. The error message is as follows: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Details: Context: I'm using Django for a web application. I have configured email settings in the settings.py file to use a custom email domain hosted on a Linode server. Email Configuration (settings.py): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'your_email_host' # e.g., 'smtp.yourdomain.com' EMAIL_PORT = 587 # Use the appropriate port for your email provider EMAIL_USE_TLS = True # Set to True if your email provider requires TLS EMAIL_HOST_USER = 'your_email@example.com' # Your full email address EMAIL_HOST_PASSWORD = 'your_email_password' # Your email password DEFAULT_FROM_EMAIL = 'webmaster@example.com' # Your default sender address SERVER_EMAIL = 'webmaster@example.com' # The address that error messages come from I checked the email server status; it's up and running. Question: What could be causing this ConnectionRefusedError? Are there any additional steps I should take to troubleshoot this issue? I am currently testing the email on my local host before making the changes to the production server Any insights or guidance on resolving this issue would be greatly appreciated. Thank you! -
Django request method defaults to GET while the tutorial I'm working with is using a POST in the code
I am following a django video tutorial to build a blog app. I am currently working in the view.py folder and creating the comment section. I followed every step carefully but i got an error while running the code. i will drop the code i wrote i wrote below and the error i'm recieving from django.shortcuts import render, redirect from .models import Post from .forms import CommentForm def frontend(request): posts = Post.objects.all() return render(request, 'blog/frontend.html', {'posts': posts}) def post_detail(request, slug): post = Post.objects.get(slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', slug=post.slug) else: form = CommentForm return render(request, 'blog/post_detail.html', {'post': post, 'form': form}) screenshot of the webpage I tried changing the if statement to a get, but i am not getting the django form as expected -
Duplicated insertion in database using django
I have the following model that i need to save : def validate_pdf(value): if not value.name.endswith('.pdf'): raise ValidationError("O arquivo deve ser no formato PDF.") class Documento(models.Model): titulo = models.CharField(max_length=200) autor = models.CharField(max_length=200) instituicao = models.CharField(max_length=200) arquivo_pdf = models.FileField(validators=[validate_pdf]) tamanho = models.BigIntegerField(default=1) and that's my creationview: class DocumentoCreateView(CreateView): model = Documento fields = ( "titulo", "autor", "instituicao", "arquivo_pdf" ) template_name = "documentos/documento_new.html" success_url = reverse_lazy("documento_new") def post(self, request, *args, **kwargs): super(DocumentoCreateView, self).post(request) form = DocumentoCreateForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): documento = form.save() #documento.save() path = f'/media/' + form.files['arquivo_pdf'].__str__() extracao_de_texo = TextExtractor(path) and this one is the form that I use to create the model: class DocumentoCreateForm(forms.ModelForm): class Meta: model = Documento fields = [ "titulo", "autor", "instituicao", "arquivo_pdf" ] and my issue is that a model is saved even if the form.is_valid() is false, so it means that it is saved before the validation. I was expecting that the model would be inserted only when i call the form.save() method. I don't know what could be this issue. -
'dict' object has no attribute 'headers'
It`s my views.py class SendRequestView(View): def post(self,request,pk): order = get_object_or_404(Order, id=pk, user=request.user) address = get_object_or_404(Address, address=request.POST.get("address")) order.address = f"{address.address}-{address.phone}-{address.email}" order.save() data = { "MerchantID": settings.MERCHANT, "Amount": order.total_price, "Description": description, "Phone": request.user.phone, "CallbackURL": CallbackURL, } data = json.dumps(data) # set content length by data headers = {'content-type': 'application/json', 'content-length':str(len(data))} print(type(headers)) try: response = requests.post(ZP_API_REQUEST, data=data, headers=headers, timeout=10) if response.status_code == 200: response = response.json() if response['Status'] == 100: return {'status': True, 'url': ZP_API_STARTPAY + str(response['Authority']), 'authority': response['Authority']} else: return {'status': False, 'code': str(response['Status'])} return response except requests.exceptions.Timeout: return {'status': False, 'code': 'timeout'} except requests.exceptions.ConnectionError: return {'status': False, 'code': 'connection error'} I have an error "'dict' object has no attribute 'headers'" I don`t know why, please help me to solve it. -
Why updating object models in Django doesn't work as expected?
This seems strange I have the following model in Django: class CustomUser(AbstractUser): first_name = models.CharField(_("first name"), max_length=20) last_name = models.CharField(_("last name"), max_length=20) email = models.EmailField(_('email address'), blank=False, unique=True) validated_account = models.BooleanField(_('validated account'), blank=False, default=False) phone = PhoneNumberField(null=False, blank=False, unique=True) def __str__(self): return f"{self.first_name} {self.last_name}" I have the following form to edit the model: class CustomUserChangeForm(UserChangeForm): password = None class Meta(UserChangeForm.Meta): model = CustomUser fields = ["first_name", "last_name", "email", "phone", "username"] This is my view to edit the model: @user_passes_test(lambda u: u.is_authenticated, "users:login") def edit_profile(request): if request.method == "POST": print(request.POST) form = CustomUserChangeForm(request.POST, instance=request.user) print(form) if form.is_valid(): user = form.save() auth_login(request, user) messages.success(request, "Edition successful.") return redirect("dashboard:cases") messages.error( request, "Unsuccessful Edition. Invalid information.") else: form = CustomUserChangeForm(instance=request.user) return render(request=request, template_name="dashboard/edit_profile.html", context={"edit_profile_form": form}) This is the printing result from the view call: <QueryDict: {'csrfmiddlewaretoken': ['DbmuCTIOAXdP96Ozrcsf3YXSCxQ1lusywgLz4OLh5FAHrjas25inxqIt0kS9syaj'], 'first_name': ['Super'], 'last_name': ['User'], 'email': ['admin@example.com'], 'phone': ['+0043328107a'], 'username': ['admin']}> <tr> <th><label for="id_first_name">First name:</label></th> <td> <input type="text" name="first_name" value="Super" maxlength="20" required id="id_first_name"> </td> </tr> <tr> <th><label for="id_last_name">Last name:</label></th> <td> <input type="text" name="last_name" value="User" maxlength="20" required id="id_last_name"> </td> </tr> <tr> <th><label for="id_email">Email address:</label></th> <td> <input type="email" name="email" value="admin@example.com" maxlength="254" required id="id_email"> </td> </tr> <tr> <th><label for="id_phone">Phone:</label></th> <td> <input type="tel" name="phone" value="+0043328107" maxlength="128" required id="id_phone"> </td> </tr> <tr> <th><label … -
Django dev server only allowing 1 user concurrently? Local host allows more
The problem that I am having is solely on my development server when two users execute POST requests back to my server concurrently (or at any point), in doing so one of the two users is logged off. I am wondering if anyone has any thoughts as to what would cause multiple users to not be able to interact with the server? The error occurs in this situation: I open two browsers on the same machine or different and go to my dev URL. I log into two different user accounts (held in my database) on each of the browsers. I am able to navigate fine on both to get to a spot to submit a POST request. I submit a basic HTML form for each of the users. One of the users (generally the second to request), is logged out and sent back to the login page when the POST request returns to that user. The other users post request is fine but he is then also forced to logout. I am building an app in django. I am using the session engine SESSION_ENGINE='django.contrib.sessions.backends.signed_cookies'. So far I thought that it was a database connectivity or cookie issue but that … -
how remove password2 field from django createsuperuser?
I am working on a project and want to find a way to remove password2 field in createsuperuser. I used BaseAbstractUser class and changed username to Email field but after searxhes alot couldn't found any way to: when I run python manage.py Createsuperuser it asks Email and after that password. after entering password I don't want re-enter password. I checked this way but couldn't found useful -
ModuleNotFoundError: No module named 'mysite.settings' - Django project
I inherited a Django project that another team of students were working on a couple of years ago. I have been trying to run the project using py manage.py runserver but that doesn't work. Instead, I get the following error: ModuleNotFoundError: No module named 'mysite.settings. Note, in the project folder there's no settings.py file which could be the problem. Does anyone have ideas why this is happening and how to solve it? I tried editing the wsgi.py file but that was not useful because there is no settings app. -
Cannot send message from Django to Telegram (telegram-send)
I want to send a message from Django to Telegram bot when a user submits a form. Following this short instruction (in Russian) I created a Telegram bot with a certain name, got an API token, installed telegram-send: pip install telegram-send then configured it: telegram-send --configure On request of the program I provided the API token and got a numerical password, which I entered in the Telegram bot channel and got a success message, which says that I can write to the channel with telegram_send. It really works! When I type directly in the terminal telegram-send "Hello!" I see my message popping in the bot channel. But then I stuck, trying to send message from one of my views. According to the instruction, I should import the package in my views.py module: import telegram_send and then use it somewhere in views and functions: telegram_send.send(messages=["Hello!"]) I tried to insert this code in different parts of my ListView, but cound't make it work. For example, I tried to add it to standard method get_context_data, which should be implemented each time the corresponding web page is requested class PropertyListView(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... telegram_send.send(messages=["Hello!"]) return context But the message does … -
Django Admin autocomplete field selector unidesirable behavior
I have an enterprise project based in Django which is stuck in version 3.1.7 due to unexpected behavior of autocomplete field admin selector. In former versions, when you click in the combobox, the text input editor is autoselected so once you click the first time, you can automatically start writing for searching in the list of fereign key values. I tried to update to newer version of Django, but certain users have complained that now they have to make the extra step of clicking in the text input editor, because it does no longer automatically write once you click the combobox. Ever if this is a minor nuance for computer versed users, workshop users (who lest's be honest, many of them are quite dumb with tech stuff) complain because it does not longer does the usual "easier" stuff and have to be more careful. Anyway, I do not understand why the change of this behavior in newer versions, it is a loss even if it is a small one. Is there any way to force the admin template component to work as it preivously did? -
Django tree of one to one relationships throwing errors
I have these models linked as shown. I created an instance of object 1 and then when i tried to create an instance of object 2 i got this error. django.db.utils.IntegrityError: duplicate key value violates unique constraint "App_Object2_group_id_key" DETAIL: Key (local_id)=(1) already exists. Is there a better way to link these models? class Group(models.Model): group_id = models.PositiveIntegerField() class Object1(models.Model): group= models.OneToOneField( Group, related_name="object_1", on_delete=models.CASCADE, ) class Object2(models.Model): group= models.OneToOneField( Group, related_name="object_2", on_delete=models.CASCADE, ) -
Why Django Count on M2M Field returns wrong value?
I have a manager that calculates all acquired skills by counting sessions related to educational materials attached to a specific skill. Here are my models and manager: class Trajectory(CommonSystemObjectModel): actives = models.ManyToManyField( 'actives.Active', verbose_name='Profile Goals', through='actives.TrajectoryActive', blank=True ) is_active = models.BooleanField( default=True, verbose_name='Is the profile currently active' ) class TrajectoryActive(CommonPriorityDataAbstractModel): trajectory = models.ForeignKey( to='trajectories.Trajectory', on_delete=models.CASCADE, verbose_name='Profile', related_name='trajectory_actives', db_index=True ) active: Active = models.ForeignKey( to=Active, on_delete=models.CASCADE, verbose_name='Goal', related_name='active_trajectories', db_index=True ) threats = models.ManyToManyField( to='threats.Threat', verbose_name='Skills', through='threats.ActiveThreat' ) class ActiveThreat(CommonPriorityDataAbstractModel): """Skill Model""" threat: Threat = models.ForeignKey( to=Threat, on_delete=models.CASCADE, verbose_name='Skill', db_index=True, related_name='threat_actives' ) trajectory_active = models.ForeignKey( to='actives.TrajectoryActive', on_delete=models.CASCADE, db_index=True, verbose_name='Goal attached to the profile', related_name='active_threats' ) content = models.ManyToManyField( CommonContentDataModel, verbose_name='Educational Materials attached to the skill', blank=True, db_index=True, related_name='content_threats' ) objects = ActiveThreatManager() class ActiveThreatManager(CommonObjectContentTypeManager): @staticmethod def _get_is_completed_case() -> Case: """A skill is considered acquired if the number of educational materials is greater than 0, the number of users is greater than 0, and the number of sessions on the skill's educational materials is greater than or equal to the number of users times the number of educational materials.""" return Case( When( Q(users_count__gt=0) & Q(content_count__gt=0) & Q(content__isnull=False) & Q(completed_sessions_count__gte=F('users_count') * F('content_count')), then=True, ), default=False, output_field=models.BooleanField() ) def default_metrics(self, is_completed: bool = None, **kwargs) … -
Django: Unknown command: 'loadcsv'
I get the error Unknown command: 'loadcsv' Type 'manage.py help' for usage. when trying: python manage.py loadcsv --csv reviews/managment/commands/WebDevWithDjangoData.csv why I am getting this error? I running this code in the correct folder seems like loadcsv is not working Do i need to install something to run loadcsv? -
Set a list of available times in jquery timepicker
I am trying to set a list of predefined times in a jQuery timepicker. It should run from 10am to 12 midnight. I am also trying to highlight certain times that there is no availability. I believe my code is mostly correct for this functionality. What I really need help with is getting the timepicker to show only the selected times. var times = ["6:00 PM", "5:00 PM"]; $('#timepicker').timepicker ({ timeFormat: 'h:mm p', interval: 60, minTime: '10:00am', maxTime: '12:00am', startTime: '10:00', dynamic: false, dropdown: true, scrollbar: true, beforeShowDay: function (time) { var string = jQuery.timepicker.formatTime('h:mm p', time); if ($.inArray(string, times) != -1) { return [true, 'highlighted-time']; } else { return [true, '']; } }, });