Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: delete pevious photo while adding a new photo
I am developing a user profile where users can add profile picture. Adding the picture is working fine but when I want to add a new photo, old photo doesn't go away. My django version is 3.1 and I have tried django-smartfields but still it is not working. Can anyone help? views.py from smartfields import fields class Profile_Pic(models.Model): user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic') profile_pic = fields.ImageField(upload_to='media', default='admin_car/static/images/img_avatar.png', blank=True) class Meta: db_table = 'Profile_Pic' user_image.html {% extends 'datas/base.html' %} {% block content %} {% load static %} <h1 class="text-center" style="color: white">Add Profile Picture</h1> <br><br> <div class= "col-md-6.offset-md-3"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if form.errors %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> <p>Data Error, Please Check Again.....</p> {% for field in form %} {% if field.errors %} {{ field.errors }} {% endif %} {% endfor %} </div> {% endif %} {{ form.as_p }} <input type="submit" value="Save" class="btn btn-primary"> </form> </div> {% endblock %} -
How to use variables in webpage address in Django?
I am creating a search bar such that if the name of a webpage is entered, I want the user to be redirected to that page. To implement this, I have written the following code in my views.py file- if(request.method=="POST"): for entry in entries: if(entry==request.POST['q']): return HttpResponseRedirect("wiki/{{entry}}") ("entries" represents the set of valid strings that have a page attached to them) I am facing a problem in the last line where the browser is interpreting {{entry}} literally, instead of replacing the value of entry variable there. On running this, I am getting an error - TypeError, decoding to str: need a bytes-like object, NoneType found This is strange, because I have written a similar line in an html page which is working just fine - <a href="wiki/{{entry}}">{{entry}}</a> Is there a different way to write in .py files compared to .html files? If so, how can I write it? P.S. - For Reference, I am also attaching the url from the urls.py file that is being accessed by these lines of code path("wiki/<str:name>",views.addr,name="addr") -
How can I display javascriptfunctions results from one python django template in another?
I have a template in my Python Django project, which has a point counter based on the script below: function nowScrolling( last_known_scroll_position ) { let percentage = last_known_scroll_position / ( window_height - client_height ) * 100; progressbar.style.right = "calc( 100% - " + Math.round( percentage ) + "% )"; document.getElementsByClassName('score')[0].innerText= "Congrats! You have just earned " + Math.round(percentage)/2 +" points!"; } I wonder how to refer the score (function result) on another template / page (Profile, which is going to summarize users points? Thank you very much! -
chartjs data isn't passing to django webpage
I'm trying to build a webpage with a chart in it. For the chart i'm using Chartjs. Hardcoded data is no problem for the Chartjs chart. But if I'm trying to pass dynamic data the chart doesn't render. The labels and results output is 46 (the dataframe is 46 rows with 1 column) View.py def results(request): return render(request, 'results.html') def result(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): data = request.FILES['file'] # handle_uploaded_file(data) data = pd.read_csv(data,header=0, sep=',') df = data.values df2 = pd.DataFrame(df.reshape(-1,len(data.columns))) x = getPredictions(df2) x = np.array(x) result = x.reshape(-1,1).round() df = pd.DataFrame(data=result, columns=['output']) labels = len(df) # result = list(result) return render(request, 'results.html', {'result': result, 'labels': labels}) else: form = UploadFileForm() return render(request, 'index.html', {'form': form}) html page {% extends "base.html" %} {% block content %} <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> <div class="content"> <div class="row"> <div class="col-sm-8"> <div class="card card-tasks"> <h4>Chart.</h4> <canvas id="line-chart" width="500" height="350"></canvas> <script> new Chart(document.getElementById("line-chart"), { type: 'line', data: { labels: {labels|safe}, datasets: [{ data: {result|safe}, label: "output chart", borderColor: "#3e95cd", fill: false } ] }, options: { title: { display: true, text: 'output chart' } } }); </script> </div> </div> </div> </div> {% endblock content %} -
MySQL GROUP BY slows down query x1000 times
I'm struggling with setting up proper, effective index for my Django application which uses MySQL database. The problem is about article table which for now has a little more than 1 million rows and querying isn't as fast as we want. Article table structure looks more or less like below: Field Type id int date_published datetime(6) date_retrieved datetime(6) title varchar(500) author varchar(200) content longtext source_id int online tinyint(1) main_article_of_duplicate_group tinyint(1) After many tries I came that below index gives best performance: CREATE INDEX search_index ON newsarticle(date_published DESC, main_article_of_duplicate_group, source_id, online); And the problematic query is: SELECT `newsarticle`.`id`, `newsarticle`.`url`, `newsarticle`.`date_published`, `newsarticle`.`date_retrieved`, `newsarticle`.`title`, `newsarticle`.`summary_provided`, `newsarticle`.`summary_generated`, `newsarticle`.`source_id`, COUNT(CASE WHEN `newsarticlefeedback`.`is_relevant` THEN `newsarticlefeedback`.`id` ELSE NULL END) AS `count_relevent`, COUNT(`newsarticlefeedback`.`id`) AS `count_nonrelevent`, ( SELECT U0.`is_relevant` FROM `newsarticlefeedback` U0 WHERE (U0.`news_id_id` = `newsarticle`.`id` AND U0.`user_id_id` = 27) ORDER BY U0.`created_date` DESC LIMIT 1 ) AS `is_relevant`, CASE WHEN `newsarticle`.`content` = '' THEN 0 ELSE 1 END AS `is_content`, `newsproviders_newsprovider`.`id`, `newsproviders_newsprovider`.`name_long` FROM `newsarticle` USE INDEX (SEARCH_INDEX) INNER JOIN `newsarticle_topics` ON (`newsarticle`.`id` = `newsarticle_topics`.`newsarticle_id`) LEFT OUTER JOIN `newsarticlefeedback` ON (`newsarticle`.`id` = `newsarticlefeedback`.`news_id_id`) LEFT OUTER JOIN `newsproviders_newsprovider` ON (`newsarticle`.`source_id` = `newsproviders_newsprovider`.`id`) WHERE ((1) AND `newsarticle`.`main_article_of_duplicate_group` AND `newsarticle`.`online` AND `newsarticle_topics`.`newstopic_id` = 42 AND `newsarticle`.`date_published` >= '2020-08-08 08:39:03.199488') GROUP BY `newsarticle`.`id` … -
Accessing foreignkey in models
I'v been created a django project a these are my models class User(AbstractUser): phone = models.CharField(max_length=11, blank=False,null=False, verbose_name='تلفن') customer_basket = models.ManyToManyField(basket, blank=True,verbose_name='سبد سفارشات',related_name="basket") customer_slug = models.SlugField(null=True,unique=True, max_length=100, verbose_name='نامک') is_worker=models.BooleanField(default=False,verbose_name="اپراتور سفارش") And this one : class basket(models.Model): id = models.AutoField(auto_created=True, primary_key=True,serialize=False, verbose_name='ID') created_date = models.DateField(auto_now_add=True, verbose_name='تاریخ سفارش') total_money = models.IntegerField(default=0, blank=True, verbose_name='قیمت کل سفارشات') prepaid = models.IntegerField(default=0, blank=True, null=True, verbose_name='پیش پرداخت') deliver_date = models.DateField(auto_now=True, verbose_name='تاریخ تحویل') orders = models.ManyToManyField(order,blank=True, verbose_name='سفارش ها',related_name='orders',editable=True) def __str__(self): return str(self.id)+' '+str(self.created_date) class Meta: verbose_name = 'سبد خرید' verbose_name_plural = 'سبد های خرید' as you can see customer_basket in User class is Many to many I want to perform something like this: 'SELECT id FROM basket WHERE id=customer_basket_id But I don't know how to do that in midel form I want to use the result in limit_choices={'id':customer_basket_id} But when i run this it sais customer_basket_id is not defined I mean: How to access foreignkey id of a model inside of another model(customer_basket id in User model) Second how to access name of User in basket model? -
How can I get the app name in Django 3+ within a template?
I am looking for something like {{ appname }} to access the current app name of a site within a template. Unfortunately, answers for older versions of Django seem to produce errors at various positions in the code. Thank you! -
Trigger timers depending on datetime in database and render a template when each timer stops using Django
I have a datetime column in database. Each raw in this column expresses the start time of a lesson which may be any datetime through the current year. What I want to do is a try to trigger a function/view to start video call for instructor and redirect each client has this lesson before one minute to join lesson page. What I want to understand is what's the best practice to do that in Django? where I have to set this timers if they have to be contained in all pages to do redirection in any time? and how to do those redirections? Note I'm trying not to return timers as context in every view. So I want the best practice to return timers from one place and contains them in all pages. -
django - how to save api data into model from template button
I am using the Yelp API to search bars in a any location. This uses a template called results.html that has a button. Clicking this button should save the Yelp API unique ID of a Bar into my models. In my results dictionary that I loop over I call this 'id'. This is where I am having issues, taking the id from the template, saving it in the add_list views to the model BarList. This will not save to my database, I believe the main problem is my logic in add_list. Views.py def index(request): if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): city = form.cleaned_data['city_name'] API_KEY = 'MyAppKey' url = 'https://api.yelp.com/v3/businesses/search' headers = {'Authorization': 'Bearer {}'.format(API_KEY)} params = {'term':'bar','location':city} req = requests.get(url, params=params, headers=headers) parsed = json.loads(req.text) businesses = parsed["businesses"] final_result = [] for business in businesses: results = { 'id': business['id'], 'business': business['name'], 'rating': business['rating'], 'image_url': business['image_url'] } final_result.append(results) context = {'final_result': final_result} return render(request, 'API/results.html', context) else: form = CityForm() return render(request, 'API/home.html', {'form':form}) def add_list(request): if request.method == 'POST': api_id = results.get("id") Bar = BarList(api_id=api_id) Bar.save() else: return render(request, 'API/results.html') Models.py class BarList(models.Model): api_id = models.CharField(max_length=100) Urls.py urlpatterns = [ path('', views.index, name='API-home'), path('list', views.list, name='API-list'), … -
Integrating Scrapy to a Django project
I am following a tutorial: https://medium.com/@tiago.piovesan.tp/make-a-crawler-with-django-and-scrapy-a41adfdd24d9 github: https://github.com/TiagoPiovesan/scrapy_rottentomatoes to integrate scrapy to my django project. After doing the exact same things as shown here, there is no data in my database after crawling. Also downloaded the source code from git and nothing happens with no errors shown. Steps I made after downloading the project from github: 1.cd into source folder 2.created virtual environment 3.installed django, scrapy, scrapy-djangoitem, Pillow 4.makemigrations, migrate 5.created superuser 6.cd into crawling folder and run: scrapy crawl rottentomatoes The spider runs perfectly: 2020-10-31 20:10:52 [scrapy.core.engine] INFO: Spider closed (finished) but nothing happens. When I followed the code I had errors with importing the movies.models module in scrapy settings, but it seemed a pylint error only as the code run successfully. By simply opening the github version there is no visible errors, i can simply see no results. -
how to enable delete button in my form in Django?
I have a table containing records of a database table.In the table, I have put a Delete button for each row(each row shows 1 record).I need to call a view for deleting that record but I don't want to reload a new page.I need staying in same template and just by clicking a delete button,the related row gets deleted. The needed part of the template : {% for each in power_recs %} <tr> <td>{{ each.power }}</td> <td><form method="post" action="{% url 'app:name' %}"> {% csrf_token %} <input name="key" value="{{ each.pk }}" hidden> <button class="btn btn-outline-danger" type="submit">Delete</button></form> </td> </tr> {% endfor %} the view for deleting each row : def filter(request): pk = request.POST.get("key",None) record = Model.objects.get(pk=pk) record.delete() return render(request) ***I don't know what should I render here**** How can I call this view without changing the page that I am in it?(Imagine you have a table with 10 records.You want to delete 3 of the records 1 by 1.You click first record and it gets deleted and now you are again in the same page so you can click the next one and delete it.) Thanks. -
Django channels - connection timed out
I created a django-channels app that works without any problem in local. I'm now trying to deploy it to a DigitalOcean droplet. The whole Django WSGI part works, the only part not working is Django-Channels. If i try to connect to any consumer like below: ws://MYURL:9000/main I get the following error on my Chrome console: WebSocket connection to 'ws://MYURL:9000/main' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT Daphne service: [Unit] Description=Daphne service After=network.target [Service] PIDFile=/run/daphne/pid User=root Group=root WorkingDirectory=/django-vue-mpa ExecStart=/django-vue-mpa/venv/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 django_vue_mpa.asgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-abort PrivateTmp=true [Install] WantedBy=multi-user.target And here is my actual nginx conf: server { listen 80; server_name http://MYURL/; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /django-vue-mpa/django_vue_mpa; } location / { include proxy_params; proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock; } } What am i doing wront here? The exact same code works locally, but it looks like whenever i try to access django channels from outside i get refused. -
Django Channel Custom Authentication Middleware __call__() missing 2 required positional arguments: 'receive' and 'send'
I am writing a custom authentication middleware for django channels as follows: class TokenAuthMiddleware: def __init__(self, inner): # Store the ASGI application we were passed self.inner = inner def __call__(self, scope): return TokenAuthMiddlewareInstance(scope, self) class TokenAuthMiddlewareInstance: def __init__(self, scope, middleware): self.middleware = middleware self.scope = dict(scope) self.inner = self.middleware.inner async def __call__(self, receive, send): ## my logic to get validate user and store the user in user data ... ... ... self.scope['user'] = user_data inner = self.inner(self.scope) return await inner(receive, send) but on trying to connect to web socket from front end I get the following error TypeError: __call__() missing 2 required positional arguments: 'receive' and 'send' -
how can I add Image to my django database and display it in frontend
I am making a blogging website in Django. I want to add a functionality with which the user can upload an image in the form, which will be used as a thumbnail for that blog. I have added imageField in models.py file, now I am not getting how shall I take the image input from the user in the form section? post models.py: class Post(models.Model): sno = models.AutoField(primary_key=True) thumbnail = models.ImageField(null=True, blank=True, upload_to="images/") title = models.CharField(max_length=50) content = RichTextField(blank=True, null=True) author = models.CharField(max_length=50) slug = models.CharField(max_length=200) timeStamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timeStamp'] def __str__(self): return self.title + " by " + self.author html forms: <form action = "{% url 'addblog' %}" method="post"> <div class="form-group"> <label for="title" id="Title">Title</label> <input type="text" class="form-control" id="title" name="title"/> </div> {% csrf_token %} <div class="form-group"> <textarea name="content"></textarea> <script type = 'text/javascript'> CKEDITOR.replace("content") </script> </div> <button type="submit" class="btn btn-primary my-1" id='contact-button'>Post</button> </form> currently the add blog page looks like this: now I want a choose file option after the content text area where the user can upload an image and then that image gets saved in the database, after which I can display the image in the blog section at frontend. -
Proper way to write 'request.POST.post' in class based views
I'm trying to use CBV. I'm new to it. I'm having problem requesting a POST data inside a form. Here is my view: form_class = LocatarioForm template_name = 'contrato/locatario_form.html' def get_initial(self): return { 'contrato': self.kwargs["pk"] } def post(self, request, pk): segundolocatario = request.POST['segundolocatario'] return segundolocatario def get_success_url(request): # if request.POST.post('segundolocatario') == 'Sim' # return reverse('contrato:locatario', kwargs={'pk': self.object.pk}) return reverse('contrato:conjugec', kwargs={'pk': self.object.pk}) Here is the template: <form method="post"> {% csrf_token %} {{form}} <label for="segundolocatario">Deseja cadastrar um segundo locatário para este contrato?</label> <select name="segundolocatario" id=""> <option value="sim">Sim</option> <option value="nao">Não</option> </select> <br><br> <button type="submit">Próxima etapa</button> </form> I need to request 'segundolocatario' to flow control my templates. How can I do this in CBV? Thank you. -
Display django form errors with js after ajax call
i have this signup form that works fine and saves the user correctly when there are no errors but when there are errors in the inputs like two password fields didn't match ,i couldn't display those errors that are sent to the front-end with form.errors.as_json() so i need someone to guide me how to display those errors with the js here is the form in my forms.py file: class SignupForm(UserCreationForm): password1 = forms.CharField(widget=forms.PasswordInput( attrs={'placeholder': 'Password', 'class': 'form-control mt-3','id':'password1'})) password2 = forms.CharField(widget=forms.PasswordInput( attrs={'placeholder': 'Confirm your password', 'class': 'form-control mt-3 mb-3','id':'password2'})) class Meta: model = User fields = ("full_name", "email", "password1", "password2") widgets = { 'full_name': forms.TextInput(attrs={'placeholder': 'Full name', 'class': 'form-control mb-3','id':'full_name'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control','id':'email'}), } here the view of the form in my view.py: if request.is_ajax(): signup_form = SignupForm(request.POST) if signup_form.is_valid(): signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return JsonResponse({"success" : True}, status=200) else: return JsonResponse({'success': False} ,signup_form.errors.as_json() , status=400) the ajax request in my javascript file var $signupForm = $('#form-signup'); $signupForm.submit(function (event) { event.preventDefault(); var $signupData = $signupForm.serialize(); $.ajax({ url: "http://localhost:8000", method: 'POST', data: $signupData, success: function() { location.reload() }, error: function () { // display the errors in … -
django Channels with subdomains served over https - Chanel development server NOT taking over from development server (runsslserver)
I am using Django 3.1 I am following the online tutorial for django Channels, to build a simple chat server/room. However, I am using django_hosts as well as django_sslserver (in order to serve HTTPS on local host and on a subdomain), so I am having to modify the tutorial code slightly because my environment is different. These are the changes I've had to make: Integrating the Channels library with Django # mysite/asgi.py import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = ProtocolTypeRouter({ "https": get_asgi_application(), # <- Note: I am using HTTPS }) According to the Channels documentation, I should see the following line in the console: Starting ASGI/Channels version 3.0.0 development server at http://127.0.0.1:8000/ However, in my console, I still see the line: Starting development server at https://127.0.0.1:8000/ Using SSL certificate: /path/to/env/lib/python3.6/site-packages/sslserver/certs/development.crt Using SSL key: /path/to/env/lib/python3.6/site-packages/sslserver/certs/development.key From this point on, I am unable to replicate app behaviour following the example. My question is: How do I get django Channels to work with HTTPS (e.g. django_sslserver) ? -
Multiple generic class based DetailView's for the SAME model
I am attempting to use two detail views that will render different templates for the same model, at different URLs of course. Is it possible to have different generic detail views for the same model? If not I'll just have to write my own I suppose. All my detail views route to the absoluteurl but in this case I want each detail view to route to the template I have defined in the class. I used the method below to successfully create multiple list views and update views, but it just doesn't work on detail views, I always end up at "course_detail" even though I declared "course_detail_producer_view." models.py title = models.CharField(max_length=200) slug = AutoSlugField(max_length=100, help_text="course title", populate_from=['title', 'date'], unique=True, ) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) date = models.DateField(blank=True, null=True) new_course = models.BooleanField(default=False) new_instructor = models.BooleanField(default=False) katacoda = models.BooleanField(default=False) jupyterhub = models.BooleanField(default=False) released = models.BooleanField(default=False) status = models.CharField(max_length=50, choices=status_choices, blank=False ) pub_partner = models.CharField(max_length=50, choices=pub_partner_choices, blank=False) course_notes = models.TextField(max_length=500, blank=True, ) producer_notes = models.TextField(max_length=500, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False ) producer = models.ManyToManyField(Producer, related_name="course", blank=True, ) def get_absolute_url(self): """Return URL to detail page of a Course""" return reverse( "course_detail", kwargs={"slug": self.slug} ) def __str__(self): date_time = f"{self.date} … -
How can I get a ModelMultipleChoiceFilter to search two fields simultaneously?
I have a model with two 'slots', both of are ForeignKeys to the same separate model: class Car(models.Model): ... paint_colour1 = models.ForeignKey(Paint, on_delete=models.CASCADE) paint_colour2 = models.ForeignKey(Paint, on_delete=models.CASCADE) ... I want my filter to return, say, all cars that use blue paint whether the blue paint is in slot 1 or 2 (e.g. Car1.paint_colour1='blue' and Car2.paint_colour2='blue' would both be returned). Here is the filter I am using right now: class CarFilter(django_filters.FilterSet): paint_colour1 = django_filters.ModelMultipleChoiceFilter(queryset=Paint.objects.all(), label='Paint 1') class Meta: model = Car fields=[] As it stands right now, I can select as many paint colours as I want, but only the results with those colours in slot 1 are returned. However, if I add a second field for paint_colour2, only results with the colours in slot 2 are returned. I have tried using the following filter instead: class CarFilter(django_filters.FilterSet): paint_colour = django_filters.ModelChoiceFilter(queryset=Paint.objects.all(), method='search_both_colours', label='Search by colour:') class Meta: model = Car fields = [] def search_both_colours(self, queryset, name, value): return Paint.objects.filter(Q(paint_colour1__exact=value) | Q(paint_colour2__exact=value)) This allows me to return all results for a single colour whether the colour is in slot 1 or slot 2, but I want to be able to return results of cars with as many colours as are specified. -
Add property to model of other app in django
I am currently working on a project that should be deployed to several different clients with slightly different configurations and features. To achieve that, for each feature I wanted to create a new app in django. As an example we have one base app which contains a model for Patient (pretty simple, name, id, ...). For some clients I would like to create a parent app that will include an additional app called case_type which contains a model called CaseType. In that app one patient can have one caseType. But here is the catch. The patient app should work with or without the case_type app. Therefore I would like to kind of "inject" a new property into the model and serializer of Patient from within the case_type app. So this way when deploying with the case_type app the user will receive a JSON like this when calling /patient/<id>: { "name": "Bob", "id": "123", "caseType": { "type": "a", "comment": "something" } } but when calling the same route without the case_type app I want it to return { "name": "Bob", "id": "123" } This means I will have to dynamically adapt the serializer and model in a "dependency-injection"-kind of way. There … -
How can I ovveride Django Admin page?
I've read many answers but I don't know what am I missing. I did the same steps as they are mentioned in Django Docs (https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#admin-overriding-templates) but nothing happened. Here is my actual configuration : INSTALLED_APPS = [ 'app1.apps.App1Config', 'app2.apps.App2Config', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'rida.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')],#i modified this line 'APP_DIRS': False, #True 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] } } ] the contents of admin.py file of app1 : from django.contrib import admin from django.conf.urls import url from app1.models import Modele admin.site.register(Modele) I want to override the template base.html, so I copied it from django\contrib\admin\templates\admin and put it in myproject\templates\admin\app1, then I made some changes on this file but nothing happened, so I have no idea why it doesn't work and what am I missing. thank you in advance. -
Can't Edit and Delete posts from my Django post_detail.html template
I've added Edit and Delete buttons to my post_details.html. This is to edit or delete a post added by the owner of the post. It's unfortunate that I'm always running into errors when I access the post_details.html page. Please I need your help... Below is the code snippets: models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset(). \ filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') header_image = models.ImageField(null=True, blank=True, upload_to='post') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') objects = models.Manager() # Default manager published = PublishedManager() # Custom manager tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) views.py class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'body', 'tags', 'status'] template_name = 'blog/post/post_form.html' def form_valid(self, form): form.instance.author = self.request.user return super(PostUpdateView, self).form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post template_name = 'blog/post/post_confirm_delete.html' success_url = … -
Replacing the default ManyToMany widget with CheckboxSelectMultiple widget doesn't insert the checked boxes in the database
I'm trying to insert change the default widget of the ManyToMany field in a Django form and I want to use the CheckboxSelectMultiple widget instead. No matter if I use CheckboxSelectMultiple widget or the default widget for ManyToMany field, the rows corresponding to the checkboxes don't get inserted at all. I looked at the solutions here, here and here, but I don't understand what I'm doing wrong. Here's the relevant code: models.py: class Employer(models.Model): # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES, blank=True) short_bio = models.TextField(blank=True, null=True) website = models.URLField(blank=True) profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True) admin_approved = models.BooleanField(default=False) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=MAXIMUM_CATEGORY_LENGTH) def __str__(self): return self.name class JobListing(models.Model): employer = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=100) job_description = models.TextField() job_requirements = models.TextField(); what_we_offer = models.TextField(); # https://stackoverflow.com/questions/2771676/django-datetime-issues-default-datetime-now time_added = models.DateField(default=now) job_application_url = models.URLField(unique=True) admin_approved = models.BooleanField(default=False) categories = models.ManyToManyField(Category) def __str__(self): return self.job_title forms.py: EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"], widgets={"location": s2forms.Select2Widget}) class JobListingForm(forms.ModelForm): job_title = forms.CharField(max_length=100) job_description = forms.CharField(widget=forms.Textarea) job_requirements = forms.CharField(widget=forms.Textarea) what_we_offer = forms.CharField(widget=forms.Textarea) job_application_url = forms.URLField() categories = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = JobListing fields = ["job_title", "job_description", "job_requirements", "what_we_offer", "job_application_url", "categories"] views.py: … -
"AssertionError: False is not true" keeps popping up whenever i run tests.py on my django project
I am following a tutorial by Tom Aratyn in which i would test whether pagination works properly. Here is the tests.py file: from django.test import TestCase from django.test.client import \ RequestFactory from django.urls.base import reverse from core.models import Movie from core.views import MovieList class MovieListPaginationTestCase(TestCase): ACTIVE_PAGINATION_HTML = """ <li class="page-item active"> <a href="{}?page={}" class="page-link">{}</a> </li> """ def setUp(self): for n in range(15): Movie.objects.create( title='Title {}'.format(n), year=1990 + n, runtime=100, ) def testFirstPage(self): movie_list_path = reverse('core:MovieList') request = RequestFactory().get(path=movie_list_path) response = MovieList.as_view()(request) self.assertEqual(200, response.status_code) self.assertTrue( response.context_data['is_paginated']) self.assertInHTML( self.ACTIVE_PAGINATION_HTML.format( movie_list_path, 1, 1), response.rendered_content) This is already a copy-paste code from the book, however, the AssertionError keeps popping up. (m_env) C:\Users\mrblu\MyMDB\django>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: testFirstPage (core.tests.MovieListPaginationTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\mrblu\MyMDB\django\core\tests.py", line 31, in testFirstPage self.assertTrue( response.context_data['is_paginated']) AssertionError: False is not true ---------------------------------------------------------------------- Ran 1 test in 0.021s FAILED (failures=1) Destroying test database for alias 'default'... Thank you guys in advance. newbie here. I started coding only this feb 2020, and im already 25 yrs old. Im taking this on. -
Django: How to make a Grouped Choice Field that doesn't show children until hovered?
Currently, I have: Code in forms.py: class ExpenseForm(forms.Form): CHOICES = ( ('Debt', ( (11, 'Credit Card'), (12, 'Student Loans'), (13, 'Taxes'), )), ('Entertainment', ( (21, 'Books'), (22, 'Games'), )), ('Everyday', ( (31, 'Groceries'), (32, 'Restaurants'), )), ) amount = forms.DecimalField() date = forms.DateField() category = forms.ChoiceField(choices=CHOICES) In production, I have much more categories than the example above so if I show the children of each category as well in the first drop-down, it'll take the user a lot of scrolling to find the right child. What I want to do is have the children of each category only displayed in a separate drop-down beside the first one when the mouse is hovering on the category. This would cut down the amount of irrelevant entries in the first drop-down. How can I do that?