Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The HTML markup to include the image of Rango in the about template was not found
While creating a web app in Django, I've encountered a small issue. There seems to be a problem with my about template referencing. This is about.html: Here's my settings.py: And here's my urls.py: I'm getting an error saying: The HTML markup to include the image of Rango in the about template was not found. -
Disallow All Site Users From appearing In Post Form During Post Creation
The post rationale was to permit all clients on my site to have the option to make post and news which is a success however shockingly while making a post all the entire aunthenticated client/users in the data set shows up for the specific confirmed client to browse and this are data I don't need the client/users to see when making post and I have no arrangement to eliminate the users Foreignkey from the post Model since it encourages me actualizing other site basic capacities and the Author functions. since the users/client will fill in as creator/author class Post(models.Model): image = models.ImageField(upload_to="images/") title = models.CharField(max_length=150) summary = models.CharField(max_length=250) category = models.ForeignKey(PostCategory, on_delete=models.CASCADE) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=250, unique=True, blank = True) def onlyselfuser(self, *args, **kwargs): self.user = self.request.user super().onlyselfuser(*args, **kwargs) #please take a look at my view.py files class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = __all__ def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) i will appreciate if someone can show me a way out where the login user( user=request.user) will only appear excluding other users on moder and i tried a OneToOneField still and it didnt work. i Don't want … -
Integrating scrapy crawler with Django
Before you mark this as duplicate, please read ahead. I have researched much and haven't found anything (although a different question with the same title). In my project, I want to take a URL from the user and scrape the URL using a Scrapy spider/crawler. I first tried to do this by directly putting the scraper code in my views.py but the start/stop of twisted.internet.reactor was causing problems. Another method was to use a scheduling program such as Scrapyd. But the point is that the next operations in the particular view must happen only after the crawler has finished scraping. Scrapyd will only be scheduling the crawler. Please correct me if I am wrong about the assumption about Scrapyd or there is some API that I could use to track the progress of scraping. If not, suggest what I can do to achieve that. TIA. -
Two model fields and one form field in Django
I have two fields in Model and one form field. The widget AutocompleteInput is attached to form input. If the user selects an element from the autocompleteinput list in the widget, I want the data to be save to one field model. If the user enters their own string, I want the data to save to another field in the model. -
Django Model form not saving data to the database model on form submission
I have created a project and added models in the models and also created a form in forms.py. I am trying to modify some values using the commit=False. On submitting the form, it's not saving the data to the database and there is no error thrown from the code. I have no idea on how I can solve the issue. models.py from django.db import models from django.contrib.auth.models import User class Agent(models.Model): name = models.CharField(max_length=255) id_no = models.CharField(max_length=20) address = models.CharField(max_length=255) gender = models.CharField(max_length=8) age = models.IntegerField() agent_no = models.CharField(unique=True, max_length=12, null=True) email = models.EmailField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Company(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) telephone = models.IntegerField( null=True, blank=True) email = models.EmailField(max_length=50, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Task(models.Model): company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL) agent = models.ForeignKey(Agent, null=True, on_delete=models.SET_NULL) cargo = models.CharField(max_length=200) document = models.FileField(upload_to='documents/') quantity = models.FloatField() amount = models.FloatField() duty = models.FloatField(null=True, blank=True) status = models.CharField(max_length=50, default='Pending') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.cargo}" forms.py from django.contrib.auth.models import User from django import forms import re from django.core.exceptions import ValidationError from .models import * class TaskForm(forms.ModelForm): cargo = forms.CharField( required=False) document … -
Django Rest API- pass additional objects to ModelSerializer
I have a comment field for every blog post. I want to pass Comment.objects.all() from Views.py to ModelSerializer def get_comments(self, obj) to reduce the number of sql queries. As I am serializing a list of blog posts Views.py class BlogViewSet(ModelViewSet): queryset = Blog.objects.all().annotate( author_name=F('author__username') ) serializer_class = BlogSerializer permission_classes = [IsOwnerOrReadOnly] def list(self, request): return Response({'blogs': BlogSerializer(self.queryset, many=True).data}) Serializers.py class BlogSerializer(ModelSerializer): author_name = serializers.CharField(read_only=True) comments = SerializerMethodField() class Meta: model = Blog fields = ('title_text', 'main_text', 'datepublished', 'author_name', 'id', 'comments') def get_comments(self, obj): # filter comment comment_object = Comment.objects.filter(post_id=obj.id) comments = CommentSerializer(comment_object, many=True).data return comments -
how to connect an android device with adb server using python
Good Day..) I am able to connect android device with adb using USB cable but I want connect remote device with out USB cable and not rooted also. Basically I am running adb command through python. I am googling from 2 days most of the resources says we can't. If it's not please suggest me other resources. Big appreciation for your help.. Thanks -
pythonanywhere: Error code: Unhandled Exception
I am trying to host a website, But got stuck with this error enter image description here. Something went wrong :-( This website is hosted by PythonAnywhere, an online hosting environment. Something went wrong while trying to load it; please try again later. There was an error loading your PythonAnywhere-hosted site. There may be a bug in your code. Error code: Unhandled Exception what should be my next step? what can be the mistake for this error ? -
Showing application error after sucessfull deployment in python application
I made a new Python Project in Django, then deployed the application to the Heroku. When I open my application it shows me application error message. My logs don't indicate any errors as far as I can tell, but I'm receiving the following error when loading the site: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command. Below you can find the logs. Am I missing something here? (foodtasker) C:\Users\nikku\Desktop\foodtasker>heroku logs --tail 2021-02-11T10:52:05.964281+00:00 app[api]: Release v1 created by user nkarnwal07 @gmail.com 2021-02-11T10:52:05.964281+00:00 app[api]: Initial release by user nkarnwal07@gm ail.com 2021-02-11T10:52:06.223875+00:00 app[api]: Enable Logplex by user nkarnwal07@gma il.com 2021-02-11T10:52:06.223875+00:00 app[api]: Release v2 created by user nkarnwal07 @gmail.com 2021-02-11T11:10:53.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com 2021-02-11T11:11:06.000000+00:00 app[api]: Build failed -- check your build outp ut: https://dashboard.heroku.com/apps/8ca09b4c-2b22-4b60-9bef-ea151d6f0ace/activ ity/builds/96248b6d-f0dc-4016-b9bf-228f21fa2a87 2021-02-11T11:12:31.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com 2021-02-11T11:12:45.000000+00:00 app[api]: Build failed -- check your build outp ut: https://dashboard.heroku.com/apps/8ca09b4c-2b22-4b60-9bef-ea151d6f0ace/activ ity/builds/1a7d4064-5c4a-4e6b-a40a-b937ca3b4446 2021-02-11T11:16:22.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com 2021-02-11T11:16:39.000000+00:00 app[api]: Build failed -- check your build outp ut: https://dashboard.heroku.com/apps/8ca09b4c-2b22-4b60-9bef-ea151d6f0ace/activ ity/builds/482acec5-04d8-404e-a5f8-aaeaeba66ab7 2021-02-11T11:18:33.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com … -
How to show message given by django admin to the user when he select a value from drop down.?
I know this will be very hard to understand my question. But I have a requirement where I need to show the message added by admin to a specific model(This will be same for all instances from that Model) I can use Ajax call to show the message but for my requirements I need to change the notification whenever I want from admin end instead of changing in code. I used notifix.co to get notifications with End Urls but though I used Ajax call I am unable to implement this on certain page where I cam getting data with Ajax call. Is there any way where I can manage my pop up messages up on clicking a certain model in user end and I can manage the messages in Admin. -
Any ideas on how to fix the django TypeError: expected string or bytes-like object?
I created a form page for staff to add multiple files for each patient (A radiograph image, a CT scan and a medical notes file). It works perfectly when running the website locally but shows a TypeError when it is run from heroku. Could this be related to the fact that the database changed from sqlite locally to postgresql in deployment? Here is part of my models.py code class Radiograph(models.Model): patient = models.ForeignKey(User, null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) image = models.ImageField(null=True, blank=True) ct_scan = models.FileField(null=True, blank=True) medical_notes = models.FileField(null=True, blank=True) Here is forms.py code: class AddRadiograph(forms.ModelForm): class Meta: model = models.Radiograph fields = ['patient', 'image', 'ct_scan', 'medical_notes'] And here is the part of my views.py code: @allowed_users(allowed_roles=['clinics']) def add_radiograph_view(request): if request.method == 'POST': form = forms.AddRadiograph(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('accounts:add_patient') else: form = forms.AddRadiograph() return render(request, 'patientfiles/add_radiograph.html', {'form':form}) The traceback also highlights only form.save() Please take it step by step as I am still new to this language. Any help is much appreciated! -
How to add password to dynamic PDF file in Django
I want my dynamic PDF invoice should generate with random password but when i try to do that it gives me blank invoice PDF file. I have used xhtml2pdf for creating PDF file and PyPDF2 to add password. this my views.py file #For password generation i have created a function def generate_random_password(): MAX_LEN = 12 DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] COMBINED_LIST = DIGITS + LOCASE_CHARACTERS rand_digit = random.choice(DIGITS) rand_lower = random.choice(LOCASE_CHARACTERS) temp_pass = rand_digit + rand_lower for x in range(MAX_LEN - 4): temp_pass = temp_pass + random.choice(COMBINED_LIST) temp_pass_list = array.array('u', temp_pass) random.shuffle(temp_pass_list) password = "" for x in temp_pass_list: password = password + x return password and for creating PDF file i followed this blog https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ and this is how i am trying to add password def generate_invoice(): password = generate_random_password() print('////////password////////',password) data = Booking.objects.get(id=id) name = data.given_name+' '+data.surname email = data.email template = get_template('invoice.html') context = { "data":data } html = template.render(context) pdf = render_to_pdf('invoice.html', context) if pdf: filename = "Invoice_%s.pdf" %(data.id) pdf_response = HttpResponse(pdf, content_type='application/pdf') content = "attachment; filename=%s " % (filename) pdf_response['Content-Disposition'] = content receipt_file = BytesIO(pdf.content) fs = File(receipt_file, … -
I'm getting error when i try to admin login using django framework
here is my traceback: 1)response = await sync_to_async(response_for_exception, thread_sensitive=False)(request, exc) return response return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner ▶ Local vars 2)C:\Users\91807\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response if response is None: wrapped_callback = self.make_view_atomic(callback) # If it is an asynchronous view, run it in a subthread. if asyncio.iscoroutinefunction(wrapped_callback): wrapped_callback = async_to_sync(wrapped_callback) try: response = wrapped_callback(request, *callback_args, **callback_kwargs) … except Exception as e: response = self.process_exception_by_middleware(e, request) if response is None: raise # Complain if the view returned None (a common error). -
How do i create a field in my model whose value is calculated using values from other fields?
I have a model that takes in 3 integers as part of its fields class TradeBill(models.Model): ...... first = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)]) second = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)]) third = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)]) ..... What I need to have is another positive integer field called score that adds up the value of the other three. Currently i just have it as this and thus taking care of it in the frontend: score = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(6)]) But thats not great because i can put any value i want for example from the admin or any front end input i have. Sure i can do frontend validation to stop it from happening but django never let me down when it comes to their features so im sure theres something i can do -
Filter django queryset according to condition on a field?
I have a model like this: class Story(models.Model): version = models.PositiveIntegerField(default=1) # other fields Now I am getting a dict of id: version like: id_ver_dict = { # id ver 23: 2, 24: 1, 25: 3 } I want to filter my queryset according to the given dict such that the version in my DB is greater than the version in the id_ver_dict. How can I filter this in a single query? Is there something like this: Story.objects.filter(id__in=id_ver_dict.keys(), version__gt=id_ver_dict_value) P.S.: I am using MySQL -
my stylesheet and images doesn't work with Jinja2 templates with parameters - Django
I successfully converted my website templates to Jinja2, everything works as it should, except in urls with parameters. I have this is views.py file path("profile/<id>", views.profile), When the template loads in my browser the css and images dont load. But when I remove the parameter and set id manually in the view function everything works. Am I doing anything wrong? -
Django allauth redirect to previous page
I am using Django allauth besides django auth to login users in my webapp. I want to return the users back to current page after logging in or signup when login using allauth. I have gone through some of the answers but none work in my case. Please see my code below: #settings.py ACCOUNT_ADAPTER = 'kvizmaster.adapter.MyAccountAdapter' #adaper.py from django.http import HttpResponseRedirect from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): print("in code") redirect_to = request.GET.get('next', '') print(redirect_to) return HttpResponseRedirect(redirect_to) Login URL <a title="Google" class="socialaccount_provider google" style="text-decoration:none;" href="/accounts/google/login/?process=login?next={{request.GET.next}}">Sign in with Google</a> Form Next Variable <input type="" name="next" value="{{ request.GET.next }}"/> The login url has correct href assigned and next variable works on the form. However, I am unable to access the "next" in adapter.py. Please suggest. -
repartition.js:1 Uncaught ReferenceError: Chart is not defined at file.js:1
I am working on a django project and can't load chartjs. I get the following error: repartition.js:1 Uncaught ReferenceError: Chart is not defined at file.js:1 the file that has the problem is: file.js this is the first line: Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif'; I have already loaded chart.js and it is working correctly on my environment. It is loaded on index.html as follow: <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script> Ps. working using django Any suggestions? Thanks. -
Filter django queryset by its related field
I have a DRF QuesionSet View inherited from generics.RetrieveUpdateDestroyAPIView I also have 2 models (simplified): Question(models.Model): question_set = models.ForeignKey(QuestionSet, related_name="questions") is_archived = models.BooleanField(default=False) ...other_fields QuestionSet(models.Model): ...fields Now I need to return a question_set object in the view, that only has questions that are True. Something like this: "id": 1, "questions": [ { "id": 1, "isArchived": true }, { "id": 1, "isArchived": true }, { "id": 1, "isArchived": true }, ] I am trying to override get_object() method in the view to return these values. So how do I achieve that? -
Can't make drf router work in a certain way
router = BulkRouter() router.register(r'', InventoryViewSet, basename='inventory') router.register(r'temporary/items', TemporaryInventoryViewSet, basename='temporary-inventory') this is part of my urls.py file the thing is I want to register route like this r'temporary' but it returns detail: not found in postman. but whenever I request "temporary/pk", I get desired item. The problem is, I can't make route "temporary" list all the objects. ('temporary/items' list all objects just fine, and 'temporary/items/pk' works great as well) I wonder what should I change to get the desired output -
Pagination button not highlighting the current page
So I'm trying to make a button which highlights as active when the page is the same as page number, but it does not work, It only highlights page 1, When I go to page 2 then page 1 is still highlighed, index function handles the page I'm talking about. views.py from django.shortcuts import render from .models import Listing from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator # Create your views here. def index(request): listings = Listing.objects.all() paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) params = {'listings':paged_listings} return render(request, 'listings/listings.html', params) def listing(request, listing_id): return render(request, 'listings/listing.html') def search(request): return render(request, 'listings/search.html') listings.html {% extends 'base.html' %} {% block content %} {% load humanize %} <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'index' %}"> <i class="fas fa-home"></i> Home</a> </li> <li class="breadcrumb-item active"> Browse Listings</li> </ol> </nav> </div> </section> <!-- Listings --> <section id="listings" class="py-4"> <div class="container"> <div class="row"> {% if listings %} {% for listing in listings %} <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <img class="card-img-top" src="{{ listing.photo_main.url }}" alt=""> <div class="card-img-overlay"> <h2> <span class="badge badge-secondary text-white">${{ listing.price | intcomma}}</span> </h2> </div> <div class="card-body"> <div class="listing-heading text-center"> <h4 … -
Heroku Build succeeded but "application error" {Django app}
heroku log: 2021-02-11T09:33:17.289297+00:00 app[web.1]: ModuleNotFoundError: No module named 'ivytasks' 2021-02-11T09:33:17.289983+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-02-11T09:33:17.306006+00:00 heroku[web.1]: State changed from starting to up 2021-02-11T09:33:17.429342+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [4] [INFO] Shutting down: Master 2021-02-11T09:33:17.429457+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-02-11T09:33:17.511921+00:00 heroku[web.1]: Process exited with status 3 2021-02-11T09:33:17.647676+00:00 heroku[web.1]: State changed from up to crashed 2021-02-11T09:33:18.929260+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ivytasks.herokuapp.com request_id=1d65f0f2-d28b-4f75-a02b-3f55c4d2ae2a fwd="154.97.8.251" dyno= connect= service= status=503 bytes= protocol=https 2021-02-11T09:33:19.373547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ivytasks.herokuapp.com request_id=36c5d48e-3181-4cf0-9f55-655dad447156 fwd="154.97.8.251" dyno= connect= service= status=503 bytes= protocol=https you can check the project repo link: github.com/osamamhd/ivyTasks -
Django queryset regex filter gives (3692, 'Incorrect description of a {min,max} interval)
Using Django 2.2 and MySQL database. I have a field (info) in the table containing stringified JSON data. I want to filter the data matching the regular expression. The example data in the info field is [{"type":"button","data":{"link":"https://example.com","label":"Click Here","tracking":{"id":"E3s06x","tag":"btn1"}}}] Where I want to match the expression "tracking":{"id":"(\S+)","tag":"(\S+)"} I tried using the regex filter in the Django ORM query = query.filter( info__iregex=r'"tracking":{"id":"(\S+)","tag":"(\S+)"}' ) But it is giving an error django.db.utils.OperationalError: (3692, 'Incorrect description of a {min,max} interval.') -
How to find the class index of a clicked element using javascript?
I have a tab-based website where tabs are created dynamically by cloning the default tab view, however, without knowing the index number of each element there is no way to perform logic on each tab. function search(){ window.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); alert(click) var input = document.getElementsByClassName("myTextInputID")[click].value; if (input.includes("https://www.amazon.co.uk/")) { document.getElementsByClassName("prodcont")[click].style.display = "block" document.getElementsByClassName("imgcont")[click].innerHTML = '<img class="image" src="https://www.needforseat.de/media/image/22/15/b3/MAXNOMIC-R-_LVL_Edition_Pro_YkaFLtIVOgbL1_320x463.jpg">'; document.getElementsByClassName("h1")[click].innerHTML = prodName; document.getElementsByClassName("containFORM")[click].style.backgroundColor = "white" } else { URLerror.appendChild(urlerror); var cont = document.getElementsByClassName("containFORM")[click]; cont.insertAdjacentElement("afterend", URLerror); setTimeout(function() { URLerror.remove(); }, 2000); } } }); } The only solution I've managed to come up with is by iterating through all the classes and givingibng them a name that matches their class number then whenever the tab button is clicked it returns its name. However this only works for the first 2 tabs and only goes up to an index number of one however when I add an alert for the value of clicked it shows the right value but the code runs on class index [1] which is very confusing. <div class="tabcontainer" id="tabcon" style="background-color: aquamarine"> <ul id="navigation1"> <li class="tabli" id="button1"><button class="tabs" id="default" onclick="openPage('0', this, 'red'); buttonOnclick(this.name);"></button></li> <ul id="navigation2"> <li id="tabli"> <button onclick="newTab()" class="addbut" style="text-align: center">+</button> </li> </ul> </ul> </div> … -
Django-smart-select with a through model on manytomany field
I am trying to implement django-smart-selects but my situation is not covered in the Docs. They cover two scenarios - those being class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ForeignKey**(Continent) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) and class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ManyToMany**(Continent) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) However, my scenario looks like this - there is an additional through model; class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ManyToMany**(Continent, through='CountryToContinent") name = models.CharField(max_length=255) class CountryToContinent(models.Model): continent = models.ForeignKey(Continent) name = models.ForeignKey(Country) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) in django admin I have registered the Location model and I have a tabular inline with continent and country fields but as there is the through model, the chained select does not work. Any guidance or hint would be appreciated.