Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django chained/dependant dropdown
I'm making a project in which I need to implement a chained dropdown, the users select first their state, then their County, and then their Neighborhood, I've been looking into a lot of options and all of them are for either only two selects (like country then city), or for a function based view, and replicating this code in my class based view it isn't working. I'd very much appreciate any help. I'm new to Django. Here are my models for location.models.py: class Estado(models.Model): estado = models.CharField(max_length=100) def __str__(self): return self.estado class Municipio(models.Model): municipio = models.CharField(max_length=100) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.municipio class CP(models.Model): cp = models.CharField(max_length=100) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.cp class Colonia(models.Model): colonia = models.CharField(max_length=100) cp = models.ForeignKey(CP, on_delete=models.CASCADE) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.colonia As for where I want to implement it, is in the Posts model, here are all the relevant codes, I think: models.py class PostRoom(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author') colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=False, null=True) cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=False, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=False, null=True) views.py: class RoomSubmitCreateView(LoginRequiredMixin, CreateView): model = PostRoom … -
type object 'datetime.timezone' has no attribute 'now'
This line of code is receiving an AttributeError: now = timezone.now() I can't figure out why. I am correctly importing the package as follows: from django.utils import timezone But it is still throwing: Attribute Error: type object 'datetime.timezone' has no attribute 'now' These are my settings.py if it helps you: LANGUAGE_CODE = 'es-ar' TIME_ZONE = 'America/Argentina/Buenos_Aires' USE_I18N = True USE_L10N = True USE_TZ = True -
Adding Different Theme modes in a Django Project
I am trying to add a themes for users in my Django project. Users can choose between dark mode and light mode. So in the base.html, I have set the links to be as following: <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyles('app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyles('app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> I have started a new app called mode with following models.py: class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name here is the javascript <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); var cssFile = "{% static 'css' %}" function swapStyles(sheet){ document.getElementById('mystylesheet').href = cssFile + '/' + sheet localStorage.setItem('theme', sheet) updateTheme(sheet) } function loadSettings(){ //Call data and set … -
Bokeh rendering glitchy (long complex visualization), embedded in Django
I have a django app w/ a bokeh server embedded in it. The code is complex enough that I cannot possibly paste it here. But I've found that as I add more and more widgets, that updates to the various plots have grown glitchy; sometimes the plot I eventually render renders, sometimes it does not. The accompanying table sometimes only shows half the fields, and other fields appearing blank. I am unfortunately not able to provide minimum viable code here but what are the best options / things I should troubleshoot? -
Deploying a Django app to heroku. Debug False
I am trying to deploy my app to heroku. I successfully deployed to app after dealing with some bugs(the CSS wouldn't load, or images wouldn't load). Now when I deploy the app works fine, when DEBUG = True. When I change DEBUG = False all the images fail to load. Here is my code: settings.py """ Django settings for DBSF project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import django_heroku import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] AUTH_USER_MODEL = 'social.User' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'channels', 'social', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'DBSF.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
How to Reordering the position of objects in Django?
The code below is getting error NoneType' object is not iterable. I want to reorder the position of objects using JQuery sortable.js. when i drag and drop for changing the position of an object i'm getting the error NoneType' object is not iterable. Please can anybody tell me why i'm getting this error? thanks in advance. views.py @csrf_exempt def SortAble(request): if request.method == 'POST': pk = request.POST.get('pk') for b in pk: book = get_object_or_404(Article, pk=int(b['pk'])) book.position = b['order'] book.save() return JsonResponse({'succes': True}, status=200) else: return JsonResponse({'succes': False, 'errors': []}, status=400) <tbody> {% for object in articles %} <tr data-pk="{{ object.id }}"> <td>{{ object.title }}</td> </tr> {% endfor %} </tbody> <script> $(document).ready(function () { $("tbody").sortable({ update: function (event, ui) { sort = []; window.CSRF_TOKEN = "{{ csrf_token }}"; $("tbody").children().each(function () { sort.push({ 'pk': $(this).data('pk'), 'order': $(this).index() }) }); $.ajax({ url: "{% url 'rundown-sort' %}", type: "post", datatype: 'json', data: { 'sort': JSON.stringify(sort), 'csrfmiddlewaretoken': window.CSRF_TOKEN }, }); console.log(sort) }, }).disableSelection(); }); </script> -
Is there a way to retrieve Enum description instead of name in a GraphQL API made with Django Graphene
This question is more about what's the best practice than how to monkey-patch Graphene to accomplish what I want. Django Graphene turns model's choices automagically in enums. Lets say I have this model: class Car(models.Model): brand = models.PositiveSmallIntegerField( choices=( (1, "Audi"), (2, "Mercedes Benz"), (3, "BMW") ) ) with this node: class CarNode(DjangoObjectType): class Meta: model = Car filter_fields = [] interfaces = (relay.Node,) then, running the following query: query Cars { cars { edges { node { id brand } } } } results in this response: { "data": { "cars": { "edges": [ { "node": { "id": "Q2FyTm9kZTox", "brand": "A_1" } }, { "node": { "id": "Q2FyTm9kZToy", "brand": "A_2" } }, { "node": { "id": "Q2FyTm9kZToz", "brand": "A_3" } } ] } } } At this point I may want to make a custom enum to turn A_1, A_2 and A_3 into capitalized, snake cased values, to make them self-descriptive... class CarBrand(graphene.Enum): AUDI = 1 MERCEDES_BENZ = 2 BMW = 3 @property def description(self): if self == CarBrand.AUDI: return 'Audi' if self == CarBrand.MERCEDES_BENZ: return 'Mercedes Benz' if self == CarBrand.BMW: return 'BMW' return 'Other brand' class CarNode(DjangoObjectType): brand = CarBrand() ... Now, the response looks A LOT … -
unable to access private repos with oauth access token
i have created a Oauth github app and Oauth works fine. but i want to access the all repos(including private) with the access-token i get during Oauth. i have tried with personal access token and i am getting all the private reops. why its not working with Oauth access-token ? Scops SOCIALACCOUNT_PROVIDERS = { 'github': { 'SCOPE': [ 'user', 'repo' ], } } regarding the env. i am using dj-rest-auth to authenticate with Github and get the access-token. -
Is there a way to filter JSON data from Django?
I have a JSON file im accessing by API and it gives me the results I need but I only want a subset of the data, is there any way to do this with Django/Python view? -------------VIEW------------------- def scanreport(request): url = "https://server/scans/7" headers = { 'accept': "application/json", 'content-type': "application/json", 'x-apikeys': 12345abc } response = requests.request("GET", url, verify=False, headers=headers) context = { 'api_data':response.json.loads } return render (request,'scans.html', context) --------------HTML---------------- {% extends 'base.html' %} {% block body%} <div> <p>Hey You</p> <pre>{{ api_data | pprint}}</pre> </div> {% endblock %} ------------JSON----------------------------------------- {'comphosts': [], 'compliance': [], 'filters': [{'control': {'list': ['true', 'false'], 'prefix': 'filter', 'type': 'dropdown'}, 'name': 'asset_inventory', 'operators': ['eq', 'neq'], 'readable_name': 'Asset Inventory'}, {'control': {'prefix': 'filter', 'readable_regex': 'NUMBER', 'regex': '^[0-9]+$', 'type': 'entry'}, 'name': 'bid', 'operators': ['eq', 'neq', 'match', 'nmatch'], 'readable_name': 'Bugtraq ID'}, {'control': {'list': ['true', 'false'], 'prefix': 'filter', 'type': 'dropdown'}, 'name': 'exploit_framework_canvas', 'operators': ['eq', 'neq'], 'readable_name': 'CANVAS Exploit Framework'}, -
Is it possible to override filter lookup with predefined values with custom Manager/Queryset in Django
I am trying to implement the behaviour for my models so that when you are deleting the object(s) it is not deleting physically, but just add some attribute to state that it was deleted. So I created custom queryset, manager and mixin to apply for each created model: class StateQuerySet(models.query.QuerySet): def delete(self): self.update(active=False) class StateManager(models.Manager): def get_queryset(self): return StateQuerySet(self.model, using=self._db).filter(active=True) class ModelMixin(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=True) objects = StateManager() def delete(self, *args, **kwargs): self.active = False self.save() class Meta: abstract = True And the models: class Organizer(ModelMixin, models.Model): name = models.CharField(max_length=256) class EventData(ModelMixin, models.Model): caption = models.CharField(max_length=512) description = models.TextField(blank=True, default='') organizer = models.ForeignKey(Organizer, on_delete=models.CASCADE) So, the idea, is when I do any: Organizer.objects.all() / Organizer.objects.filter(name__startswith='<some_start_prefix>') I will recieve Organizer objects only which are active=True (i.e. "not deleted"). All looks good, but when I have related objects, there is an issue. If, for example, I do: EventData.objects.filter(organizer__name__startswith='<some_start_prefix>') It will return all EventData objects even the 'deleted'. But if I do: EventData.objects.filter(organizer__name__startswith='<some_start_prefix>', organizer__active=True) All works as expected and only 'active' records returned. So I don't want to use: organizer__active=True for each query in the views. I've read the docs but still don't understand how to create this … -
Using values from one database in another database in Django
I have 2 models in my Django application, and i need that one of the models use values from another model. class Products(models.Model): supplier=models.CharField(max_length=25) sku=models.CharField(max_length=30) name_prod=models.CharField(max_length=30) price_prod=models.IntegerField() class Sales(models.Model): client=models.CharField(max_length=25) name_sale=models.CharField(max_length=30)// Here I want only name_prod of the Products model quantity=models.IntegerField() price_sale=models.IntegerField() // Here I want only the price_prod of the Products model -
Writing test inside function
I have two functions running at the same time(simultaneously). I want to write my test inside one of them. I mean I want to run my test's simultaneously with my other function. Because my other function creates fake data such as it creates votes if that turn is "night". So my test file is stated below. How can I run my test simultaneously with other function. def function1(): call_command('fake') def function2(): # some codes here # I also want to write my tests here because I need to fake command is running # while my test's running thread1 = Thread(target=function1) thread2 = Thread(target=function2) thread1.start() thread2.start() time.sleep(10) fake data generator is stated below while room.status != 'Finished': if turn and turn.type == 'Day' sleep(0.5) to_be_killed = RoomPlayer.objects.filter( room=room).filter(alive=True).order_by("?")[0] Vote.objects.create( day=turn, voter=room_players[j], voted=to_be_killed) -
Django channels3 Testing calling sync from async
I'm having a problem with Django Channels 3. I want to call the http test client from an async function. Here is my function def broadcast_message(client, message): return client.post( reverse("message-broadcast"), message, content_type="application/json") Here is the async function @pytest.mark.asyncio @pytest.mark.django_db(True) async def test_end_to_end(client): http_response = await loop.run_in_executor( None, broadcast_message, client, test_message) RuntimeError: Task <Task pending name='Task-1' coro=<test_end_to_end() running at /usr/src/app/tests/test_consumer_and_view.py:62> cb=[_run_until_complete_cb() at /usr/local/lib/python3.8/asyncio/base_events.py:184]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.8/asyncio/futures.py:360]> attached to a different loop tests/test_consumer_and_view.py:62: RuntimeError I want to understand what is going on and how to fix it. Thanks. -
How to create a custom interface for django orm from legacy odbc
I'm accessing an application backend with a proprietary odbc driver provided by the platform vendor (Progress DataDirect ODBC, customized SDK build). This odbc works with pyodbc but not django's orm. Is there a guide for building a custom interface and adding that to django's list of databases? Or is there a way to inject the pyodbc connection or override the queryset's connection? Or is there a way add a pyodbc (not sqlserver) in the DATABASES section of settings.py? -
Is this the right way to use <> inside path()? [closed]
The code inside urls.py: from django.urls import path path('web/edit<str:webname>', views.edit_web), The code inside views.py: @login_required def edit_web(request, name): return render(request, 'edit.html') -
Custom query to or from a Serializer in djang rest framework
Given I have this enum in my model: MEDIA_TYPES = ( ('A', 'Acrylic'), ('W', 'Watercolor'), ('MM', 'Multimedia'), ('G', 'Gouache'), ('O', 'Oil'), ('P', 'Pencil'), ('C', 'Charcoal'), ('PS', 'Pastel'), ('CO', 'Conte Crayon'), ) These could be selected for artwork objects in my admin. I want to create a serialized json for only the ones used. Let's say I have a number of objects, but they only use Watercolor, Oil and Charcoal and not the other media. How do I return an object that looks like this: [ { "W": "Watercolor" }, { "O": "Oil" }, { "C": "Charcoal" } ] -
NoReverseMatch at /property/city/city/
I am developing a web commerce Django app and keep running into this bug. Below are some screenshots. Any help appreciated. Models.py Urls.py Views.py Template -
How to make full page tabs that act as webpages?
Sorry I'm showing a lot of code but I cant convey my meaning well enough. So my first page works perfectly, you type in a URL, information from that product shows up then the user clicks it then the name of the product become the tab name and the url path. I want to make this work with tabs where each time you press a new tab it takes you to the starter page and each tab acts as an individual page. How could I do this using JavaScript. HTML var className = document.getElementsByClassName('tabs'); var itemcont = document.createElement("div"); itemcont.id = "itemcont"; var imgcont = document.createElement("div"); imgcont.id = "imgcont"; var prodcont = document.createElement("div"); var title = document.createElement("h1"); prodcont.id = "prodcont"; imgcont.innerHTML = '<a onclick="move()"><img id="image" src="https://cdn.searchenginejournal.com/wp-content/uploads/2019/11/2.3-5dbd10f9530fc-480x360.png"></a>'; title.innerHTML = '<a onclick="move()"><h1>Razer Huntsman Mini Mercury Mercury Ed. (Red Switch) - Compact Gaming Keyboard (Compact 60 Percent Keyboard with Linear Opto-Mechanical Switches, PBT Keycaps, Detachable USB-C Cable) US Layout , White</h1></a>'; itemcont.appendChild(imgcont); prodcont.appendChild(title); itemcont.appendChild(prodcont); document.getElementById("myTextInputID") .addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); var input = document.getElementById("myTextInputID") .value; if (input.includes("")) { document.getElementsByClassName("containFORM")[0] .insertAdjacentElement("beforeend", itemcont); document.getElementById("prodcont") .insertAdjacentElement("afterbegin", imgcont); document.getElementsByClassName("containFORM")[0] .style.backgroundColor = "white" } else { var URLerror = document.createElement("p"); URLerror.classList.add("error"); var urlerror = document.createTextNode("This … -
Heroku Error Deploying, Conda Related Error
I am deploying my first application to Heroku and am receiving the following error. It is a Django application remote: ERROR: Could not find a version that satisfies the requirement conda==4.6.14 (from -r /tmp/.../requirements.txt (line 17)) (from versions: 3.0.6, 3.5.0, 3.7.0, 3.17.0, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.0.4, 4.0.5, 4.0.7, 4.0.8, 4.0.9, 4.1.2, 4.1.6, 4.2.6, 4.2.7, 4.3.13, 4.3.16) remote: ERROR: No matching distribution found for conda==4.6.14 (from -r /tmp/.../requirements.txt (line 17)) Line 17 of requirements.txt is /Downloads What exactly does this error mean? -
Trying to download pyhton and django
i've just tried to download python but i keep getting the same message, Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. I'm not sure on how to fix it, i tried to diasble the shortcut from setting but it then said "The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." If there is any help out there it is greatly appreciated. Thanks. -
In Django if we use google oauth why the email address are not added in the User model?
In my Django app, I have a used google oauth2 for login, so when a user signs up, the first_name, last_name and username are automatically added to the User model and can be viewed through the admin panel. But the email addresses of the user are not being added, why is it so? Is there any way we can add the email address to the User model when the user signs up using OAuth? -
Should I set up all the logging messages in every page of my django project?
Should I use all of these in views and models and urls in my django project?: logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') I mean, should I just paste these at the end of the files in my project or should I do something different? Would that be enough? (I'm new to logging). -
How to Fixed Django Database Error On Apache Server
The Best Way To Permission Apache Server http://coder-i.com/Digital-Ocean-Apache-To-Django-Database-Operational-Error -
Docker Airflow within Fedora issue on LDAP
can anyone assist with an Docker Airflow within Fedora issue on LDAP , I'm getting the following error after configuring ldap within airflow.cfg File ldap3/strategy/base.py line 147 in open raise LDAPSocketOpenError(unable to open socket exception_historyldap3.core.exceptions.LDAPSocketOpenError: ('unable to open socket', [(LDAPSocketOpenError("('socket ssl wrapping error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)',)",), ('ldaps://', 636))]) Any idea how this can be resolved all certs (.cer .key & CA) have been loaded successfully and airflow is running on https://hostname:8080/ -
Clean method is calling another clean method if ValidationError is raised
In my forms.py I have two forms. One is a called a SeriesForm which gets it fields from Series model in models.py, another one is called a SeasonsForm which gets it fields from Seasons model in models.py. If ValidationError is raised in SeasonsForm it calls SeriesForm clean method which is what I don't want if no ValidationError is raised SeriesForm clean method isn't called and everything works fine. The reason I don't want this behavior is because I am rendering both forms in the same page and this behavior causes the other form(SeriesForm) to display values that I've entered in SeasonsForm (when I submit the form). The SeriesForm is like a user editing his profile page, in simple words it gets it instance from the database to fill the values so I do something like this in views.py: series = Series.objects.get(...) SeriesForm(request.POST, instance=series) # notice the instance parameter Maybe because the Seasons model has a foreign key that references Series model it calls the SeriesForm clean method is it because of that? Complete Code I've provided comments in code to help to focus on the important things. models.py class Series(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) SeriesName = models.CharField(max_length=30, default="") slug …