Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django package import error "Invalid syntax"
openpyxl package import throws "invalid syntax" error in virtualenv while running the django project. While installing the package through requirements.txt file, I'm getting an error for this package in logs as follows This is the version of openpyxl I'm installing openpyxl==3.0.3 I've tried to install the package manually again by doing a pip install openpyxl but this says successfully installed but failed to build openpyxl. Any help with this issue will be appreciated. Thanks in advance. -
Django Populate DateTimeField valudation Error
This is mym models: class Post(models.Model): timestamp = models.DateTimeField() I am trying to populate this field like this: Post.objects.create(timestamp='20-03-20 8:56') and throws me following error: django.core.exceptions.ValidationError: ['“20-03-20 8:56” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Can anyone help me to fix this? -
Model field for implicit many-to-many (many-to-many-to-many) relationship in Django
Let us say in my models for a django app, I have three models, each with many to many relationship (this is a toy example). class User(models.Model): permissions_group = models.ManyToManyField(Group) class Group(models.Model): permissions_area = models.ManyToManyField(Area) class Area(models.Model): #other irrelevant field data... pass I would like to have a field on my User model, that expressed the relationship between users and Areas, which is an implicit many-to-many model (that is to say I don't define additional relations which create additional tables in the database, I use the relationship which goes through groups). I have considered using a custom manager, but that doesn't seem to allow the kind of relationship filtering that one sees with a standard RelatedField manager; I could simply set a decorated property on the class: class User(models.Model): @property permissions_areas(self): return Area.objects.filter(group__in=self.permissions_groups.all()) But that seems clunky, and doesn't use any django conventions. Is there a conventional way to do this in django using Django's tooling (custom managers or similar) which I am missing? -
Django: Annotate two values of the most recent foreign key
I'm actually using python 3.7 and Django 3.0.4. I using in my app models.py like this for a simple system of messages. from torii.models import User class Room(models.Model): users = models.ManyToManyField(User, related_name='conversations', blank=True) name = models.CharField(max_length=100) class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='messages') user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date = models.DateTimeField(auto_now_add=True) So when my user send a message I create a new Message object attached to my Room. I want to query all Room for a given User and annotate the date of the most recent message and the last message in my query. No problem to get the most recent date in my related messages using Max like this: for room in Room.objects.filter(users=user).annotate(last_message_date=Max('messages__date')).order_by('-last_message_date'): print(room.__dict__) {'id': 7, 'name': 'room-7', 'last_message_date': datetime.datetime(2020, 3, 20, 14, 0, 2, 118190, tzinfo=<UTC>)} {'id': 9, 'name': 'room-9', 'last_message_date': datetime.datetime(2020, 3, 8, 15, 19, 52, 343780, tzinfo=<UTC>)} {'id': 8, 'name': 'room-8', 'last_message_date': datetime.datetime(2020, 3, 7, 17, 18, 32, 648093, tzinfo=<UTC>)} But I don't find any way to simply annotate the content of the last message. I have tried Max('messages__content') but in fact, it's order message by alphabetic order and it's always the same who is returned... I tried several subqueries with F and Q … -
How to render a template in django from a different app using Class Based Views?
I'm feeling I shouldn’t be asking thins question because it seems too easy. But I can't find a solution in the django docs or here. I want to render a template in my class based generic ListView, which is in the templates folder of a different app. My folder structure: my_website -app1 -app2 -mywebsite -templates -users -welcome_pages -welcome_user.html -app3 -templates -mytemplate.html -mytemplate2.html -views.py -models.py In my app3 I have a view that looks like this: class VisualizationView(StaffRequiredMixin, ListView): template_name = ???? model = Project def get_context_data(self, **kwargs): print(self.get_template_names()) context = super(VisualizationView, self).get_context_data(**kwargs) context['projects'] = Project.objects.all() return context So I can easily render a template now in template_name which is in my app3 and spit out all my project objects there. But I want to render the context in welcome_user.html. Normally the documentation says I should use appname/templatename but I get a TemplateDoesntExist Exception. I tried passing to template_name: mywebsite/welcome_user.html mywebsite/users/welcome_pages/welcome_user.html welcome_user.html mywebsite/templates/users/welcome_pages/welcome_user.html If I print out self.get_template_names() I only get a list of templates that are within app3. I thought django would automatically be looking in the whole project wherever a template folder is? What am I missing here? Or is this not supposed to work in a CBV? Apologies … -
Correct way to query in many to many (django)
I am trying to get a list of books that have been added by a favorite by a user. I can pull up a list of all favorites from a user myfavorites = Favorite.objects.filter(user=thisUser)" which will return the correct list of 3 favorites by user1 but then when I try to use that list to get a list of the books with "myBooks" : Book.objects.filter(favorites=myfavorites), I instead only get a single object(the first book the user added to favorites). What is the proper way to query this? Is the problem in my views or my models? views.py def books(request): if 'userid' not in request.session: return redirect('/') else: num = request.session['userid'] thisUser = User.objects.get(id=num) myfavorites = Favorite.objects.filter(user=thisUser) context = { "user" : thisUser, "otherBooks" : Book.objects.exclude(favorites=myfavorites), "myBooks" : Book.objects.filter(favorites=myfavorites) } return render (request, 'app1/books.html', context) models.py class User(models.Model): first = models.CharField(max_length=30) last = models.CharField(max_length=30) email = models.CharField(max_length=40) password = models.CharField(max_length=40) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() class Book(models.Model): title = models.CharField(max_length=45) author = models.CharField(max_length=30) desc = models.TextField() user = models.ForeignKey(User, related_name="books") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BookManager() class Favorite(models.Model): favorite = models.BooleanField() user = models.ForeignKey(User, related_name="favorites") book = models.ForeignKey(Book, related_name="favorites") created_at = models.DateTimeField(auto_now_add=True) updated_at = … -
gunicorn server hangs when calling itself
I have a Django REST Framework service that runs on a gunicorn server. Here is what the config looks like: exec gunicorn \ --pid /web/gunicorn.pid \ --workers 4 \ --threads 8 \ --worker-class gthread \ --name my-api \ --chdir /src/api \ --bind unix:/web/.sock \ --timeout 300 \ --limit-request-line 8190 \ wsgi:application I have two views: def view1(request): # Call DB etc. def view2(request): my_api_python_client.call_view1(request) # Hangs! This results in the requesting hanging indefinitely. I understand that calling one view from another sounds counter-intuitive but it has to be done to leverage caching, async calls etc. What is curious is that when I run it as a Pycharm server, it works perfectly well! Question - Why does my request never get processed? How do I fix it? -
How to print an output in an HTML page multiple times using django framework?
enter image description here As per the code shown in the image, how can we use loops to print 'Result : {{result}}' multiple times? -
django how to return classBasedView from in a function
I am trying to put a condition before the password reset view, so I want to return it from a function based view. from django.contrib.auth import views as auth_views def password_reset(request, *args, **kwargs): if some condition: Do something else: return ( auth_views.PasswordResetView( **{ 'template_name': 'reset-form.html', 'email_template_name': 'reset-email.txt', 'html_email_template_name': 'reset-email.html', 'subject_template_name': 'reset_subject.txt', 'form_class': PasswordResetForm, 'success_url': 'etc...', } ), ) With this code I get 'tuple' object does not support item assignment error. What is wrong here? -
show data in another table dynamically in same page using jquery
enter image description here here i make ajax call and show data in new table without loading the page enter image description here here i want to get data by clicking previous table name by using a href on it. but unfortunately i cannot able to get html id which i written i another ajax function due to this i cannot unable to complete this ajax function call because i was testing weather i can get A href id of another function or not i am beginner in web fieldenter image description here . this is also pic of ajax callenter image description here pic of my website page show new table of modules by clicking on projects name but no i want to show dependencies table by clicking on name of module but i did not know to use how get html selector from previous call -
Get JSON values and populate DB/Model in real time in Django
I made a method to request some json values from a url and after populate my DB/models. def get_json(request): response = requests.get('url') geodata = response.json() for obj in geodata['features']: if ImagemServer.objects.filter(pathServer=obj['attributes']['Path']).exists(): imagemServer_list = ImagemServer.objects.all() return HttpResponse('API IS RUNNING') else: for obj in geodata['features']: imagemServer_list = None imagemServer_list = ImagemServer() imagemServer_list.objectidServer = obj['attributes']['OBJECTID'] imagemServer_list.imagemServer = obj['attributes']['Name'] imagemServer_list.sensorServer = obj['attributes']['TX_SENSOR'] imagemServer_list.anoServer = obj['attributes']['NR_ANO'] imagemServer_list.pathServer = obj['attributes']['Path'] imagemServer_list.save() return HttpResponse('API WAS UPDATED') If I run a the url /json (for example) this method runs and everything works. but here is the points: Everything works well in the first catch only - the DB/Model was populated; If I delete any entry in the DB/Model the intention is to check the json again (every time that I access /json) and populate the DB/Model again, based on the Path (if exists or not, unique values and the condition is to not duplicate the values). But in this case, if I delete any entry nothing happens If I run again. Also if I updated the json from the url (I have access to this) nothing is updated in the DB, older or new values. What I missing here? -
How do I Send mail on Updating user active in Django admin?
I have changed the registration process a bit as shown below. When from the admin panel when superuser checks active, the registered user() should get mail on pressing save button. How can I do that? Views.py def register(request): if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() messages.success(request, "User saved") return redirect("accounts:login") else: messages.error(request, "Error in form") else: form = RegistrationForm() context = {"form": form} return render(request, 'accounts/reg_form.html', context) -
Django returned response not updating in html
I send some of the dropdown values from my ajax to Django views, the Django views returning a response in JSON format. The value is a list of the list according to python so in javascript it's an array of arrays. What I want to do is to parse the data coming from the Django views and update a div content in the front end. This is what I tried so far: filter.html <form id="form1" method="POST"> {% csrf_token %} <div classs="container"> <div class="row"> <div class="col-lg-5"> <label for="intent">Intent</label> <div class="styled-select blue semi-square"> <select name="intent" id="intent-sel"> <option value="all">All</option> <option value="opinion">Opinion</option> <option value="complaint">Complaint</option> <option value="suggestion">Suggestion</option> <option value="satisfied">Satisfied</option> <option value="delivery">Delivery</option> <option value="customer_sensitivity_for_pricing">SensitivityForPricing</option> </select> </div> </div> <div class="col-lg-5"> <label for="product-type">Product Type</label> <div class="styled-select blue semi-square"> <select name="product_type" id="product-sel"> <option value="all">All</option> <option value="condom">Condom</option> <option value="lube">Lubricant</option> </select> </div> </div> <div class="col-lg-5"> <label for="rating">Rating</label> <div class="styled-select blue semi-square"> <select name="rating" id="rating-sel"> <option value="all">All</option> <option value="1">1 Star</option> <option value="2">2 Star</option> <option value="3">3 Star</option> <option value="4">4 Star</option> <option value="5">5 Star</option> </select> </div> </div> <div class="col-lg-5"> <label for="brand">brand</label> <div class="styled-select blue semi-square"> <select name="brand" id="brand-sel"> <option value="all">All</option> <option value="durex">Durex</option> <option value="skore">Skore</option> <option value="kamasutra">KamaSutra</option> </select> </div> </div> </div> </div> <div class="buttonHolder"> <button type="submit" id='upload-button' class="btn btn btn-outline-dark">Filter</button> </div> </form> <div id="content_data"> </div> … -
How to implement django webapp for travelling saleman problem
I have a semester project to implement travelling salesman problem using django framework and google maps api. This webapp is supposed to take some locations as input and output the route with minimal distance on the map shown on the website. I am already familiar with html, css and javascript. I have also learnt django for this project. But as this is my first development project, I don't know how to start making this project and what should be the structure of this project. Can anyone guide me for the basic steps to develop this project? -
Want to get the owner of the post but only i get 3 fields from 13 (Django)
User model Post model Post serializer Post view Using get method with POSTMAN Testing and i get only id , username and image -
Is there a way to create a Django app in memory just for testing?
I'm creating a Django project that behaves like a "framework". There is a custom management command to create apps with an given boilerplate (startapp overridden). Is there a way to create this app only in memory during the testing phase? -
I'm trying to add new product on my new project. But why it's show (no such table: main.auth_user__old)
I'm trying to add new product details on product table. But whenever I try to save this it's show me OperationalError at /admin/products/product/add/ *Here are errors detail: * Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Exception Type: OperationalError at /admin/products/product/add/ Exception Value: no such table: main.auth_user__old -
How to make one app to another app notifications message in Django?
I am trying to make one notifications message from one app to another app like One app is (app name)final(it python files like url,setting etc..)and other is (app name)user(it’s particularly app so its python files like model ,url,views,apps,admin etc...) So how to make?? So can u help me to solving my problems? -
Register Django custom path converter once for multiple urls files
I have converters.py file with defined MyCustomConverter. It is imported to multiple urls.py files (the same code for different django app urls): from django.urls import register_converter from converters import MyCustomConverter register_converter(MyCustomConverter, "my_custom_converter") Is it possible to avoid duplication and register the path converter once somewhere outside urls and use it everywhere? -
Django flatpages catch all
I am using the catch all pattern for flatpages in Django, like this:- urlpatterns = [ path('somepath/', include('project.somepathapp.urls')), path('anotherpath/', include('project.anotherpathapp.urls')), etc. ] urlpatterns += [ path('<path:url>/', views.flatpage), ] In my template, I use:- <a href="/about-us/">About Us</a> to get to the About flatpage. But the URL pattern strips off the final slash and passes the flatpage view the URL /about-us (as opposed to /about-us/). The flatpage view then spots that the URL doesn't end in a slash, adds it back in, finds the page and redirects to that URL but adds an extra slash so that the URL is now /about-us// If I remove the final slash from the catch all pattern, any URL from the main paths (somepath/ and anotherpath/) without the final slash is matched by the catch all pattern before the APPEND_SLASH is used and, since there is no page with that URL, the user gets a 404. So a URL like /somepath/ will work but /somepath won't. What have I done wrong? It seems like a catch-22 to me. I can't use the middleware option because that doesn't always get passed through other middleware views so I'm stuck. Any ideas? -
how to access phone number from django phonenumber_field.modelfields.PhoneNumberField?
I have PhoneNumberField in my django model. How to retrieve the actual phone number from the field object. class MyUser(models.Model): mobile = PhoneNumberField( verbose_name="Phone Number", blank=True, null=True, unique=True ) ... -
Persmissions of INSTALLED_APP not present, still 403 Forbidden error
I added a clearing cache app https://github.com/timonweb/django-clearcache to my django project. I don't see any new permissions from this app which I can assign to users. Still when other user than superadmin tries to access the clearing cache view, he gets "403 Forbidden" error. Which permission and how I should add for django-clearcache app to my project? Thank you. -
Celery No such table when using postgresql
Im currently putting my django project in production with docker and celery. for this i followed a blog post online. now i stumbled over an error which i can't seem to fix. when running the container with sqlite everything works just fine, but with postgresql i get this error: celery-beat_1 | [2020-03-20 14:32:00,052: INFO/MainProcess] Scheduler: Sending due task check_routers_online (Router.tasks.check_routers_online) celery_1 | [2020-03-20 14:32:00,066: INFO/MainProcess] Received task: Router.tasks.check_routers_online[d4cece14-1d20-43ae-8712-1ad48ce79208] celery_1 | [2020-03-20 14:32:00,085: ERROR/ForkPoolWorker-1] Task Router.tasks.check_routers_online[d4cece14-1d20-43ae-8712-1ad48ce79208] raised unexpected: OperationalError('no such table: Router_router') celery_1 | Traceback (most recent call last): celery_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute celery_1 | return self.cursor.execute(sql, params) celery_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute celery_1 | return Database.Cursor.execute(self, query, params) celery_1 | sqlite3.OperationalError: no such table: Router_router celery_1 | celery_1 | The above exception was the direct cause of the following exception: celery_1 | celery_1 | Traceback (most recent call last): celery_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 385, in trace_task celery_1 | R = retval = fun(*args, **kwargs) celery_1 | File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 650, in __protected_call__ celery_1 | return self.run(*args, **kwargs) celery_1 | File "/home/app/web/Router/tasks.py", line 14, in check_routers_online celery_1 | for router in routers: celery_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__ celery_1 | self._fetch_all() … -
error when do database migration when building Django website
I use python3.7 to build website using Django Framework. I could start the web server well But when I tried to do database migration(when I run this command: python3 manage.py makemigrations, error occurs: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) ..... delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locallibrary.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) -
One more "django.db.utils.ProgrammingError: relation "device_gclouddevice" does not exist"
I know there is a lot of post with this problem but somehow I can't find a solution for my problem. Configuration Django 3.0.0 Python 3.6.9 Docker 19.03.5 Issue I have a class starting like below, nothing fancy. class PubSub: test = GcloudDevice.objects.count() I use this class via command line and it works perfectly if I comment the test variable. BUT if I run the command line with this line I get: django.db.utils.ProgrammingError: relation "device_gclouddevice" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "device_gclouddevice". The thing is I am able to create GcloudDevice and I can see it and managed it from the admin zone. Things I already tried I deleted all my migrations, remove my db and its volume. Recreated all again, still the same issue. I tried after this to delete again the migration from my device app and migrate them on their own, still the same If anyone can help me and also explain to me how is it possible that everything works on the admin ( I can see on the django-debug-toolbar that this request is passing : SELECT COUNT(*) AS "__count" FROM "device_gclouddevice , HOW FRUSTRATING) but not from the command line I …