Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
change background with Css
I want to change my background site so at first it changed but when I trying to change it again to another color it not happen I link my code file with style.css file with this code {% load static %} style.css (code):in my style.css folder body{ background-color: blue;} first I changed the background to brown then I want to change it to blue but it doesn't change (also when I go to my site it still brown also when I use this code in style.css (body{ background-color: blue} when I click on inspect it appears to me body{ background-color: brown} ) -
Customize Django ListView Pagination
im implementing a Django ListView for a Search View. The search is done using Elasticsearch and django-elasticsearch-dsl. Im actually getting a pagination of just 10 items because thats the amount of contents that Elasticsearh answers by default. I could ask elasticsearch to get all the contents but it would be really unnefficient since im only showing like 50 of them. Is there any way that Django reads the pagination information from other than the queryset? This is what my view looks like: from .elastic import search class SearchView(ListView): template_name = "search/index.html" paginate_by = 50 def get_queryset(self): keyword = self.kwargs['keyword'] lang = get_language() return search(keyword, lang) -
Upgrading Oracle XE from 11g to 21c broke django's ability to talk to TNS Listener
I have an old application that is running django 1.10 with an oracle XE 11g back end. We are trying to upgrade the XE to 21c. The issue is that django cannot find the TNS listener even though it is there and running. sqlplus works correctly so there is no issue with the listener itself. The django application and the XE database are both running on the same server so there is no networking issue. The main change as far as I can tell between the 11g and 21c is that the newer oracle database has plugin databases and needs to be addressed via the easy connect naming mechanism. Is that supported by django 1.10? Directly using cx_Oracle to connect to the database from python3 also works without throwing errors. Any pointers appreciated. -
Add html tag and style on CKEditor Textarea
I'm using django ckeditor, is it possible to add html and css on textarea? Something like this: -
How to track frontend app screens in backend
I have a application with django rest and flutter. In frontend there are 20 screens. Now i want track each screen like if user uninstall app and comeback after 1 year he will able to land on previous screen. So suggest me good approach form backend perspective -
Failed to save in SQLite database django
I have the following codes: models.py class Job(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField() freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(auto_now_add = True, null = True) date_modified=models.DateTimeField(auto_now = True, null = True) version=models.IntegerField(default = 1) class Job_removed(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField(null = True) freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(null = True) date_modified=models.DateTimeField(default=timezone.now) version=models.IntegerField(null=True) views.py def job_delete(request,pk): job=Job.objects.get(pk=pk) jobdetail = Job_detail.objects.get(job=pk) if request.method == "POST": jobr = JobRemovedForm(request.POST) if jobr.is_valid(): jobr.jobname = job.jobname print(jobr.jobname) jobr.owner = job.owner print(jobr.owner) jobr.enabled = job.enabled print(jobr.enabled) jobr.start_date = job.start_date print(jobr.start_date) jobr.start_time = job.start_time print(jobr.start_time) jobr.date_added = job.date_added print(jobr.date_added) jobr.version = job.version print(jobr.version) jobr.save() return redirect('/job/', {'job':Job.objects.all}) else: jobr = JobRemovedForm() return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail, 'jobr':jobr}) return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail}) Output of my powershell for those print commands: In the database (SQLite): What I am trying to do is to copy from the entry from … -
Finding median in annotation django
Im using MySQL server as database and need to find median price in query like this: price_query = Product.objects \ .filter(price_query) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(avg_price=Avg('Price'), std_price=StdDev('Price'), count=Count('Price'), max_price=Max('Price'), min_price=Min('Price'), median='???') \ .order_by('dt') response is look like this {"date":"2021-05-01T00:00:00Z","avg_price":4326.666666666667,"std_price":20.548046676563168,"min_price":4300.0, "max_price":4350.0,"count":3} Any help is highly appreciated. -
Django - Getting all URLs for folders and subfolders
I am building an image gallery application that does not require a database. The user places a folder containing images and its subfolders into the '/media' directory, and python scripts gather data such as the full path, the name of the directory, the image path/names inside, and the subfolders and their images, it sends this data to the view and it's rendered in the template. The first folders all work, I can access them, see their content, but I can't access the subfolders inside those galleries. I want the url to look something like this but the subfolder part isn't cooperating. website.com/directory/<folder1>/<subfolder>/ The first folder is working with str:data, it displays. pagination works, the images are rendered to the template, but I don't know how to get the urls to work for all subsequent directories. path(r"directory/<str:data>/", views.directory, name="directory"), This is what the code looks like for that right now, I thought slug would be appropriate considering the file names can be a variety of different things. urls.py path(r"directory/album/<slug:item>", views.album, name="album") view.py def directory(req, data): sl = MyClass() dir = data albums = sl.folder_path(data, include_gallery=True) img_list = sl.list_files(dir) paginator = Paginator(img_list, 9) page_number = req.GET.get('page') page_obj = paginator.get_page(page_number) return render(req, "galleries/galleries.html", … -
Where do POST request from a form send the data to in django
Suppose I have created a login page and a register page. both have forms with same name attribute say "username" in the input tag. login page calls views.login function and register page calls views.register function. Now in register page I am submitting a form with some username and saving it in a variable in views.register something like this username = request.POST["username"] views.login too have the same code username = request.POST["username"] My query is where will the username go? only in the views.register function or in views.login function too? -
Using get_model in a custom slug generator raises django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I created a custom slug generator function to use in multiple models across multiple apps. To achieve this I pass the relevant django app name and django model as string parameters to the function, so the function can check if the slug is unique for that model: def slug_generator(django_app, django_model, field_name, slug_len, prefix=""): unique_pk = False model = apps.get_model(django_app, django_model) while not unique_pk: random_pks = random.sample( string.ascii_uppercase + string.digits + string.ascii_lowercase, slug_len) new_pk = ''.join(random_pks) search_query = {field_name: new_pk} try: if not model.objects.filter(**search_query).exists(): unique_pk = True except: if not model.objects.all().exists(): unique_pk = True return prefix + new_pk called in models.py like so: class Form(models.Model): form_id = models.CharField( max_length=25, default=slug_generator('forms', 'Form', 'form_id', 25)) The function was working fine when I only was using it for a single model (so i wasn't using get_model, I just hard coded the model it was for). Since adding get_model, this error is thrown on startup django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I tried putting the following before my function: import django django.setup() It only led me to a new error RuntimeError: populate() isn't reentrant, so it makes me think that there is a better way to write the function. Is what I am trying to achieve … -
htmx and django Class Based Views
I was traying to convert the countdown tutorial from here[1] to Class Based Views but I do not know what is missing. [1]https://htmx-django.com/blog/how-to-implement-countdown-timer-in-django-via-htm views.py class TimeDifferenceView(TemplateView): delta = datetime(2022, 12, 1, tzinfo=timezone.utc) - timezone.now() template_name = 'base.html' days = delta.days seconds = delta.seconds % 60 minutes = (delta.seconds //60) % 60 hours = delta.seconds // 3600 def get_context_data(self,*args, **kwargs): # Call the base implementation first to get the context context = super(TimeDifferenceView, self).get_context_data(*args, **kwargs) # Create any data and add it to the context. context['days'] = self.days context['seconds'] = self.seconds context['minutes'] = self.minutes context['hours'] = self.hours return context base.html <div id= "time" class="d-flex justify-content-between" hx-get="{% url 'time_difference' %}" hx-trigger="every 1s" hx-select="#time" hx-swap="outerHTML" > <div> <h5>Days</h5> <p> {{days}} </p> </div> <div> <h5>Hours</h5> <p> {{hours}} </p> </div> <div> <h5>Minutes</h5> <p> {{minutes}} </p> </div> <div> <h5>Seconds</h5> <p> {{seconds}} </p> </div> </div> -
How do I resolve "Invalid service account certificate. Certificate must contain a "type" field set to "service_account"" error to run a Django server?
I'm trying to run a Django server. I have installed python 3.8.2 and the rest of the requirements are installed through a requirements.txt file in the project folder. After installing the requirements, I've tried to run the server but it generates the following error: ValueError('Invalid service account certificate. Certificate must contain a ' ValueError: Invalid service account certificate. Certificate must contain a "type" field set to "service_account". I have tried re-installing python, re-installing the requirements, running it in a virtual environment but nothing has worked so far. It would be really great if someone guides me how to resolve this error and run the server. Error with complete traceback: https://drive.google.com/file/d/1nZdOXKjDgOnd96yJBfhZbWSZ_jdDjTuK/view?usp=sharing Manage.py: https://drive.google.com/file/d/1eXXvy8Jm2GmqmYD0pmG9CJUF-QEYchS-/view?usp=sharing Requirements.txt: https://drive.google.com/file/d/1hOsZrYactHs4nTmfbshPvIV2xAvzuaq4/view?usp=sharing -
Django model override save function raise error if an object is already active
in my Django Model I would like to validate an investment before saving, if this investment has active field value set to true and another investment belonging to the same company is already active then I should raise an error, si business rule is an only one active investment/company : Here is my code : def save(self, *args, **kwargs): if self.active: qs = type(self).objects.filter(active=True).filter(startup=self.startup) # TODO a bug here when unchecking then checking a unique active investment ==> error raised if qs: raise ValidationError(message="An active investment already exists for this startup") super(Investment, self).save(*args, **kwargs) My code seems to work, however i have found a bug in Django admin, in fact if an investment is active and is the only one to be active for that startup, when I uncheck then check again the active box the error is raised although I am not adding an active object neither updating here I am simply clicking on a checkbox twice!! -
How to sent data from contact form to my private gmail in django?
I have contact form on my Django website. I want, when someone fill the form to be sent to my private email. I have tried to do it like this, but it just refresh the page, I don't know what I made wrong. When I google the solution, I get many solutions with email services, but I don't need that, when form is filled, data to be sent to my private mail. What I need to change in my views function? This is contact form! views.py def contact(request): page_title = 'Contact' form = ColorfulContactForm() if request.method == 'GET': form = ColorfulContactForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] email = form.cleaned_data["email"] message = form.cleaned_data["message"] send_mail = EmailMessage("my.mail@gmail.com", message, to=[email]) return response else: form = ColorfulContactForm() return render(request, 'contact.html', {'page_title':page_title, 'form': form}) forms.py class ColorfulContactForm(forms.Form): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'style': 'border-color: blue;', 'placeholder': 'Write your name here' } ) ) email = forms.EmailField( max_length=254, widget=forms.TextInput(attrs={'style': 'border-color: green;'}) ) message = forms.CharField( max_length=2000, widget=forms.Textarea(attrs={'style': 'border-color: orange;'}), help_text='Write here your message!' ) -
Can not create db table in django migration
I have 2 apps "app1", "app2" in my django project. When I ran python3 manage.pymakemigrations, I can see ... Migrations for 'app1': ... Migrations for 'app2': ... But when I ran python3 manage.py migrate, I got error saying django.db.utils.ProgrammingError: relation "auth_user" does not exist "auth_user" is db table for app1.User model. I tried to run migrate separately. It is fine for app2. But when I run python3 manage.py migrate app1, I got No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I cannot find a solution for my case, anyone can help? -
Gmail API with heroku and django project
I am stuck with identyfing issue on application being deployed to Heroku. It is a python django project that using a Gmail API should send out emails to defined subscribers. Code is as below views.py (where function is called) def MailJournals(new_acts): mailAdresses = models.EmailSubscriber.objects.all().values_list('email') mail_list = [x[0] for x in mailAdresses] journal_date = datetime.strftime(datetime.now(), '%d/%m/%Y') message = MIMEText(render_to_string('newsScrapper/mail.html',{ 'journal_date': journal_date, 'new_acts': new_acts, }), 'html') message['to'] = ",".join(mail_list) message['from'] = EMAIL_HOST_USER message['subject'] = 'Official Journal as of ' + journal_date with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp: smtp.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) smtp.send_message(message) settings.py: EMAIL_HOST_USER = env('EMAIL_USERNAME') EMAIL_HOST_PASSWORD = env('EMAIL_PASSWORD') The thing is it perfectly works on localhost so I do not believe this is a code issue. Here are some heroku logs I have extracted for the call of that function: 2021-11-30T21:09:30.657994+00:00 heroku[router]: at=info method=GET path="/home/load/" host=legisync.herokuapp.com request_id=6c5c138d-05a4-488e-8bcd-c0bdc03da7fa fwd="83.23.240.85" dyno=web.1 connect=0ms service=464ms status=302 bytes=259 protocol=https Unfortunately I have no idea how to correctly identify underlying root cause why it does not work from heroku... Any ideas, or if sth else is needed from my side to share pls let me know. -
How to speed up the query transactions for large records in Django, if we are visiting multiple classes to achieve this?
I'm trying to show user profiles suggestion for a loggedIn user based on the tags he/she follows, In my case i have to travel to User_Interests_Tag class to get all the tags, next visit Post_Tag class to get all the posts for each of the tag(loop), once i have the all the postId's, visit the Post class to get each unique user and append it to a profile(List) and used paginator to limit the profiles sent to the client. How can i achieve this without using for loops to increase the overall efficiency and response time from the server? here is the snippet what i want to achieve : #looping through each tag for user_interests_tag in user_interests_tags: #user_post_tags = Post_Tag.objects.in_bulk(user_interests_tags) (used bulk but no luck) user_post_tags.extend(list(Post_Tag.objects.filter(tag_id = user_interests_tag).values_list('post_id', flat=True))) profiles = [] #looping through each tag id for user_post_tag in user_post_tags: #getting the user from post class user = Post.objects.get(id = user_post_tag) #checking if already follows and if already their in user profiles array if user not in profiles and not User_Follow.objects.filter( owner_id = user_id.id, user_id = user.user_id): profiles.append(user) #paginating 6 per request paginator = Paginator(profiles,6) limited_profiles = paginator.page(page) return limited_profiles Any leads very much appreciated, thanks in advance :) -
How to resolve the error: TypeError at /signup save() missing 1 required positional argument: 'self'
I'm trying to register users using AbstractUser but I'm getting an error. Although I'm getting error, users still get registered but I can't handle login with the registered users. The error goes thus: The error goes thus: The post request My views.py goes thus: def signup(request): if request.method == 'POST': first_name = request.POST['first-name'] last_name = request.POST['last-name'] username = request.POST['username'] email = request.POST['email'] phone_no = request.POST['phone-no'] password = request.POST['password'] password2 = request.POST['password2'] if password==password2: if CustomUser.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('signup') elif CustomUser.objects.filter(email=email).exists(): messages.info(request, 'Email Already Exist') return redirect('signup') else: CustomUser.objects.create_user(first_name=first_name, last_name=last_name, username=username, email=email, phone_no=phone_no, password=password) CustomUser.save(commit=False) return redirect('login') else: messages.info(request, 'Passwords Not Matching') return redirect('signup') else: return render(request, 'signup.html') And my models.py: class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=150) phone_no = models.CharField(max_length=20) is_end_user = models.BooleanField(default=True) is_smart_earner = models.BooleanField(default=False) is_top_user = models.BooleanField(default=False) -
Heroku : Server Error, Status=(500), bytes=403
Everything in the project is working but I only have problem with this request and I dont know what it is. heroku logs: 2021-11-30T19:23:21.705472+00:00 app[web.1]: 10.1.43.186 - - [30/Nov/2021:19:23:21 +0000] "GET /api/player=1/matches HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36" 2021-11-30T19:23:21.707787+00:00 heroku[router]: at=info method=GET path="/api/player=1/matches" host=football-players-stats-api.herokuapp.com request_id=e94d6c13-3fbd-4825-b696-282992be5bc9 fwd="186.58.74.102" dyno=web.1 connect=0ms service=27ms status=500 bytes=403 protocol=https views: class MatchesView(generics.ListAPIView): serializer_class = MatchesSerializer permissions = (IsAuthenticated) def get_queryset(self): player = self.kwargs['player'] return Matches.objects.filter(player=player).all() urls: app_name = 'api' urlpatterns = [ path('',include(router.urls)), path('player=<str:player>/matches',views.MatchesView) ] -
Why does my Django form not raise Validation Error?
I read through most SO cases regarding this issue but all are kind of specific, so I come here for help. I have impelemented a range filter in my Django project that takes in two inputs set to a low bound and high bound value, and displays the range of data within those bounds. What I'm trying to do, is make it so when a user inputs a higher number in the low bound than the high bound value, a ValidationError is raised for the user to see on the front end, and results are not displayed. I am a bit new to working with Django forms, but I can supply my code, and maybe someone could provide a solution forms.py class PlayerForm(forms.Form): # player forms points_high = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, label = 'Reviews', required = False, widget = forms.NumberInput( attrs={'id': 'pointsHigh', 'name': 'pointsHigh', 'href': '#', 'value': '', 'class': "form-control"})) points_low = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, required = False, widget = forms.NumberInput( attrs={'id': 'pointsLow', 'name': 'pointsLow', 'href': '#', 'value': '', 'class': "form-control"})) def check_bounds(self): """custom validation to check if low bound value is higher than high bound value""" data = self.cleaned_data player_low = data['player_low'] player_high = data['player_high'] if player_low … -
AttributeError: 'float' object has no attribute 'quantize' using django-firebird
I'm using: Django 2.2.24 django-firebird 2.2a1 fdb 2.02 my model: class MyModel(models.Model): ... total = models.DecimalField(max_digits=10, decimal_places=2, null=True) ... When i run a simple query: ml = MyModel.objects.values('id', 'total').last() I got this error: AttributeError: 'float' object has no attribute 'quantize' could someone help me please ? -
Can we loop through django channel layers?
I'm using django channels. I have encountered a problem. I'm trying to loop through different room names to send messages. but I'm getting type error. I don't know if this is possible with django-channels or is it fine to use loop for sending messages in sockets my code. consummers.ProjectConsumer Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) sender = text_data_json['sender'] receiver = text_data_json['receiver'] message = text_data_json['message'] # Send message to room group username = ["admin","main"] for user in username: object = { 'sender':sender, 'receiver': user, 'message':message, } username = user self.room_name = username print("here", self.room_name) self.channel_layer.group_send( self.room_name, { 'type': 'sent', #function name as an event type 'object': object #function parameters as an event object } ) async def sent(self, event): sender = event['object']["sender"] receiver = event['object']["receiver"] message = event['object']["message"] # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender':sender, 'receiver':receiver, 'message':message, })) error: File "/home/aa/gitCodes/clone-beru/4-multiuser_handler/backend/notifications/sockets/consumers.py", line 117, in receive await self.channel_layer.group_send(... TypeError: can not serialize 'type' object -
Failed in connecting to remote sql database using domain name instead of hardcoded remote ip adress
ALLOWED_HOSTS = ['http://xxx.xxxx.com/'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxDB', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root', } tried replacing the remote ip to domain name which is in working state,django stops connecting doesnt show any error.please help. -
owl Carousel is not working after ajax success in python Django
I want to get the parent category list on the slider by clicking the main category's slider list. the second category's sider is not working when I click the main category. $('.maincategory').owlCarousel({ }); $(".box").on("click", function(){ var value= this.id.toString(); var csr =$("input[name=csrfmiddlewaretoken]").val(); debugger $.ajax({ url: 'getParentCategory', type: 'POST', data: { id: value, csrfmiddlewaretoken: csr }, success: function (response) { data = response.results AppendData(data); } }); }); function AppendData(data){ $(".secondCategory").empty(); debugger; var htmls = ''; if(data.length != 0){ for (var i = 0; i < data.length; i++) { htmls += '<div class="item eight-card-single text-center">' htmls += '<a id="{{value.id}}" class="second-category category">' htmls +='<img src="/media/uploads/products/logo.jpg">' htmls +='<h5 id="'+ data[i].name +'" class="card-title">'+ data[i].name +'</h5>' htmls +='</a>' htmls +='</div>' } $(".secondCategory").append(htmls); $('.secondCategory').owlCarousel({ }); } else { $(".secondCategory").append("No data"); } }; -
how to assign a value to new user in django
i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and right now, i don't know what to do neither do i know how to implement maybe becuase i don't have much experince with django. views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') # error is showing "instance" is not access using visual studio code instance = UserMembership.objects.create(user=obj, membership=get_membership) messages.success(request, f'Account Successfully created for {username}! You can Login In Now') return redirect('userauths:login') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File …