Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest API Url Pattern to handle . (dot) symbol
Creating Django REST API, Need suggestions to handle the .(dot char) in the urlpatterns. Below is the example detail: I have a Model (test) with name as one of the fields and name value is of format ABC.XYZ Below URL pattern does not work when name = ABC.XYZ url(r'^tests/(?P<string>[\w\-]+)/$', views.tests.as_view(), name='api_tests_name') -
Django3: Dynamic queryset function allocation performance
i am just experimenting on how to 'dynamically allocate queryset functions' and i would like to know the performance issues i might face later on. My querysets are working perfectly but i am a little skeptical about them. Please have a look at my code: settings.py: ... TODO_PRIORITY = ( ('LOW', 'Low'), ('MEDIUM', 'Medium'), ('HIGH', 'High'), ) ... models.py from django.db import models from django.contrib.auth import get_user_model from django.utils import timezone from .manager import TodoManager from django.conf import settings User = get_user_model() TODO_PRIORITY = getattr(settings, 'TODO_PRIORITY', None) assert TODO_PRIORITY is not None, "Your settings file is missing `TODO_PRIORITY` variable" assert isinstance(TODO_PRIORITY, tuple), "`TODO_PRIORITY` must be a tuple" # Create your models here. class Todo(models.Model): class Meta: ordering = ('start_time',) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todos") content = models.TextField(max_length=500, blank=False) start_time = models.DateTimeField(default=timezone.now) end_time = models.DateTimeField(blank=False) priority = models.CharField(max_length=6, choices=TODO_PRIORITY, default="MEDIUM") timestamp = models.DateTimeField(auto_now_add=True) objects = TodoManager() @property def todo_id(self): return self.id manager.py from django.db import models from django.utils import timezone from django.conf import settings now = timezone.now() today = now.replace(hour=0, minute=0, second=0, microsecond=0) tomorrow = today + timezone.timedelta(days=1) TODO_PRIORITY = getattr(settings, 'TODO_PRIORITY', None) assert TODO_PRIORITY is not None, "Your settings file is missing `TODO_PRIORITY` variable." assert isinstance(TODO_PRIORITY, tuple), "`TODO_PRIORITY` must be … -
How can I generate an annotated Django queryset that checks value of across rows within the same model that are also within a specific date range?
Looking for some guidance as I'm not making progress after a week of jumping between the Django documentation for Subqueries, Window functions, and dozens of other SO answers. I'm about 20 different queryset variations in and none are yielding the right results. WHAT I HAVE TimestampedModel(models.Model): # Attributes label = CharField() timestamp = DatetimeField() # Relationships traits = ForeignKey('TraitModel') TraitModel(models.Model): # Attributes value = IntegerField() WHAT I'M TRYING TO DO I would like to annotate a queryset of the TimestampedModel with a count on how many other rows within a certain date range meet a specific threshold. Said in another way, I want to detect whenever for each TimestampedModel object, there is a consecutive dip of trait values for each of the surrounding rows (based on a variable date range around each specific row). A more concrete example: Day 1: 10 traits Day 2: 11 traits Day 3: 10 traits Day 4: 13 traits Day 5: 2 traits Day 6: 3 traits Day 7: 3 traits Day 8: 11 traits ... I want to find if there are at least X consecutive timestamps dipping below Y number of traits. Using the example above, it would detect if there were 3 … -
Update item in django DetailView
I am trying to understand django better and have worked on the following simple app. I am trying to have (recurring) tasks which belong to a certain project. At the top of a task list I will have the task that has not been performed for the longest time. Clicking on a task will mean that it is/has been performed and I want to update the field last_performed to today and then reload the view. So far I have solved it like this. class Project(models.Model): project_name = models.CharField(max_length=100) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=100) last_performed = models.DateField('last time peformed') The template for the task list is <h1>{{ project.project_name }}</h1> <ul> {% for task in project.task_set.all %} <li>{{ task.task_name }} ({{ task.last_performed }}) <a href="{% url 'update' 1 task.task_name %}">Perform</a> </li> {% endfor %} </ul> and the view.py class ProjectView(generic.ListView): template_name = 'tasks/index.html' context_object_name = 'project_list' def get_queryset(self): return Project.objects.all() class TaskView(generic.DetailView): model = Project template_name = 'tasks/detail.html' def update(request, project_id, task_name): project = get_object_or_404(Project, pk=project_id) task = project.task_set.filter(task_name=task_name).first() task.last_performed = timezone.now().today() task.save() return render(request, 'tasks/detail.html', {'project': project}) I have the following patterns urlpatterns = [ path('', views.ProjectView.as_view(), name='index'), path('<int:pk>/', views.TaskView.as_view(), name='detail'), path('<int:pk>/<task_name>/', views.update, name='update'), ] Now my … -
GeoDjango store user location from request
I'm using GeoDjango version 2.2.6. Is there a way to get the users location from just their request and store them? I want to keep track of any location changes made by the user. -
Page not found when opening link as new window
Getting the error message; Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/students/undefined When I try and open a link as a new window on Django, this is the code I wrote; <a href="#" onClick="MyWindow=window.open('https://www.youtube.com/watch?v=fNk_zzaMoSs','MyWindow','width=600,height=300'); return false;">Click Here</a> The YouTube video opens in a new window, but I get the error message in my initial window, the one with my current project open -
Django - How to get model id when clicked on it
My django application purpose is so simple: user solves algorithm from some source (for instance, Hackerrank), and returns back to my application and sends feedback about result (these algorithms are given to users by me as a task). Now I want to get id of task when clicked on send button after feedback wrote. Because from admin dashboard I could see feedback was written for which task. BTW, I'm getting no such column: algorithmtrackerapp_taskfeedback.task_id error because of thinking task as a foreign key for feedback. Here are my codes: views.py: def index(request): tasks = Task.objects.all().order_by('-task_deadline') task_feedbacks = TaskFeedback.objects.all() form = CreateFeedbackForm() context = { 'tasks': tasks, 'task_feedbacks': task_feedbacks, 'form': form } if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return render(request, 'index.html', context) models.py: class Task(models.Model): task_name = models.CharField(max_length=100) task_url = models.URLField(max_length=300, blank=True, null=True) task_source = models.CharField(max_length=50, blank=True, null=True) task_deadline = models.DateTimeField() uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.task_name class TaskFeedback(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) sender = CurrentUserField() is_solved = models.BooleanField(default=False) feedback_content = models.TextField(max_length=500, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.feedback_content This is my interface: -
DRF Serializers taking a lot of time to execute , What other option do i have to send the serialized response in DJANGO
So I am trying to send complex nested JSON response from one of the endpoints in API developed in DJANGO , I am using DRF for that purpose , they're great but they're really slow . I was wondering what other option do I have . The response needs to be serialized and it's nested , complex . DRF Serializers were working great until the dataset grew and now it's really slow . -
Pytest failing to import third-party packages
So I am stuck with pytest. My setup is a django setup with docker-compose. Anytime I run pytest, I get errors like this Hint: make sure your test modules/packages have valid Python names. Traceback: lib/python3.6/site-packages/compressor/tests/test_signals.py:4: in <module> from mock import Mock E ModuleNotFoundError: No module named 'mock' another one E _pytest.config.ConftestImportFailure: (local('/app/lib/python3.6/site-packages/testfixtures/tests/conftest.py'), (<class 'ModuleNotFoundError'>, ModuleNotFoundError("No module named 'sybil'"), <traceback object at 0x7fb8a7a4e780>)) Seems like it's having problem importing third-party libs, how do I ignore these kinds of errors. -
django-plotly-dash serve css files locally
I am trying to serve css files locally in a DjangoDash app using django-plotly-dash. Simpleexample.py app = DjangoDash('SimpleExample', serve_locally=True) app.css.append_css("path_to_css") app.layout = html.Div([ html.Div( className="app-header", children=[ html.Div('Plotly Dash', className="app-header--title") ] ), html.Div( children=html.Div([ html.H5('Overview'), html.Div(''' This is an example of a simple Dash app with local, customized CSS. ''') ]) ) ]) simpleexample.html {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} {% plotly_app name='SimpleExample' ratio=0.45 %} </div> {% endblock %} header.css and topography.css are the files as described here: https://dash.plotly.com/external-resources. According to these: https://github.com/GibbsConsulting/django-plotly-dash/issues/121 and https://github.com/GibbsConsulting/django-plotly-dash/issues/133, the issues regarding this should be fixed. However the css styling does not render-- What am I missing here? There was a suggestion in the above github issues that we can use django template rather than iframe. I could not find much documentation on that -- can anyone point me there? Thank you. -
Django Manytomany Autocomplete Lookup
Is it possible to adopt the Django many to many autocomplete loopup for form? I know how to adopt the Django normal loopup but not the many to many with autocomplet outside of admin page. For the normal loopup this will work by adding this into the html template: <a onclick="return showRelatedObjectLookupPopup(this);" class="related-lookup" id="lookup_id_object" title="Lookup" href="/admin/..."></a> -
Django search form with multiple filter
in my Django web site I've got a User page where are listed all the items the User added to the database. There's a search form for the user to search into its own items. The problem is that the search form doesn't work. I'm a little bit confused about how to filter through the database because, first I've filtered all the items in order to show only the ones added by the User logged, and then I should filter through these based on the user input. Hope someone could help me, thanks! The 'def look()' is what I tried but doesn't work Views.py class userListView(ListView): model = Info template_name = 'search/user.html' paginate_by = 10 def get_queryset(self): qs = super().get_queryset() qt = qs.filter(utente=self.request.user) return qt def look(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['cerca'])) srch = request.POST.get('cerca') if srch: sr = Info.objects.filter(srch = Subquery(qt)) if sr: return render (self.request, 'search/user.html', {'sr':sr}) else: return render(self.request, 'search/user.html') else: return render(self.request, 'search/user.html') user template html <div class="add"> <div class="posted"> <div class="head"> <h2> YOUR LIST </h2> <div class="form"> <form method="post" action="{% url 'user' %}"> {%csrf_token%} <input type="text" name="cerca" class= "form-control" placeholder=" Type Album or Band Name..."> <!-- <button type="submit" name="submit">Search</button> --> </form> </div> </div> … -
Django - Foreign key, admin and forms
I’m working on a Django Project (i’m a beginner) and i have a small problem. I have different model with Foreign_Key. And also I have Forms to implements model. My problem, is not to big i think : I want the id + name instance on my admin or on my forms. Actually i have the value in def __str__(self): return self.nom I can’t do return self.id because it’s Int type. example of my models.py class Affaires(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) nom = models.CharField(max_length=50) adresse = models.CharField(max_length=100, blank=True, null=True) cp = models.CharField(max_length=5, blank=True, null=True) ville = models.CharField(max_length=50, blank=True, null=True) dessinateur = models.PositiveSmallIntegerField(blank=True, null=True) conducteur = models.PositiveSmallIntegerField(blank=True, null=True) chefdeprojet = models.PositiveSmallIntegerField(blank=True, null=True) cloture = models.IntegerField() class Meta: managed = True db_table = 'affaires' def __str__(self): return self.nom Have you got an idea ? -
Caching on Django Rest Framework GenericViews
I don`t find infos on how caching of Django Rest Framework generic views is configured. Do I have to override the get message and add an own @method_decorator? This feels ungeneric to me. class BlogTags(generics.ListAPIView): queryset = CustomContentBlogTag.objects.all() serializer_class = CustomContentBlogTagSerializer permission_classes = [AllowAny] @method_decorator(cache_page(60 * 60 * 24)) def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) Docs I found: Caching: https://www.django-rest-framework.org/api-guide/caching/ Generic views: https://www.django-rest-framework.org/api-guide/generic-views/ In the generic views docs, there is a sentence, that the queryset is cached somehow. But what, if I want the whole view to be cached? -
Order a form in a django formset by overriding __iter__ and __getitem__ method
I am using Django inlineformset_factory and i want to order a form based on the form instance foreign key in ascending order. I research on django documentation on how to order the django formset and the answer is using the iter and getitem method. But the problem in my code is I am being unable to sort the django formset yet. -
This site can’t be reached mysite.com refused to connect. ERR_CONNECTION_REFUSED
I am trying to add social authentication to my Django project and because of this I need to be able to do this: mysite.com:8000/account/login/ instead of this: 127.0.0.1:8000/account/login/ I'm on Ubuntu 16.04 running chrome Version 81.0.4044.92 (Official Build) (64-bit) I have updated INSTALLED_APPS in the settings file in Django to read: ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1'] And added the following in /etc/hosts 127.0.0.1 mysite.com I have also cleaered the chrome cache but I still get the following error: "This site can’t be reached mysite.com refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED" Does anyone know how I can get this to work please? Or even suggest another way to do it. -
How to have 2 different models for user and admin in django and how to manage them?
I am trying to create a social media type website where users can post images, videos, blogs, and meantime they can see other user's postings. I want to have 2 different models. One for users and another only for admins and moderators of the website. Admin and moderators can log in to the admin panel and edit the website. The users can only post certain things, delete their posts or update and add other users as friends/followers. In default option in Django, the users and admins are in the same model/table of a database. So is there any way to separate them? The users will be able to log in to the website. If I create 2 different models for users and admin how will I be able to authenticate the users when they will try to login to the base website where they will post things? How will I be able to set the Request.user? What will be my auth_user_model? I have created 2 different databases for this thing. One is for the admin and user DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'admin', 'USER': '#user', 'PASSWORD': '#password', 'HOST': 'localhost', 'PORT': '5432', }, 'user':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user', … -
Exception Value: string indices must be integers : Render bundle error vue + django
im using webpack loader to inyect my vue app into django, here is the code: Settings : WEBPACK_LOADER = { 'DEFAULT':{ 'BUNDLE_DIR_NAME':'/', 'STATS_FILE':os.path.join(BASE_DIR,'aptim-frontend/dist','webpack-stats.json') }} vue config file : const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" publicPath: "http://0.0.0.0:8080/", outputDir: "./dist/", chainWebpack: (config) => { config.optimization.splitChunks(false); config .plugin("BundleTracker") .use(BundleTracker, [{ filename: "../frontend/webpack-stats.json" }]); config.resolve.alias.set("__STATIC__", "static"); config.devServer .public("http://0.0.0.0:8080") .host("0.0.0.0") .port(8080) .hotOnly(true) .watchOptions({ poll: 1000 }) .https(false) .headers({ "Access-Control-Allow-Origin": ["*"] });},}; And the html line where I get the error is at the index html {% render_bundle 'app' %} ERROR :Exception Value: string indices must be integers -
How to load django objects requesting DB once and do searches after
Suppose I have a QuerySet of all db entries: all_db_entries = Entry.objects.all() And then I want to get some specific objects from it by calling get(param=value) (or any other method). The problem is, that In documentation of QuerySet methods it is said: "These methods do not use a cache. Rather, they query the database each time they’re called.". But what I want to achieve is to load all data once (like doing Select *), and only after do some searches on them. I don't want to open a connection to the db every time I call get() in order to avoid a heavy load on it. -
How do I use arrays in Django models?
I have model of ShortURL, which contains some data. I want to collect metadata on each redirect (ip, time, etc), so I need to add ArrayField (which will contain dictionaries) of some sort. Didn't find anything such in docs, what do I do? -
django sql-server hot to bind checkbox values to a specific id in database
im new to django an programming with pyton and right now i am trying to bind checkboxes to a ID (not the primary Key. Right now i can write the value of the checkboxes to the database, but everytime i do that django makes an insert but i need to do an update to the database. I get the right id true the url. If i use instance= suddenly no checkbox is stored at all but the id is erased from the database. How can i bind the checkboxes to the posid in my database. So my database would be like id posid vegaplan mhd ve globalgap 74 1515 1 1 1 1 My form: class MyForm(ModelForm): class Meta: model = MyForm fields = '__all__' (Fields are: id(pk),posid, vegaplan, mhd, ve, globalgap my view: def MyView(request, posid): fid = MyModel.objects.get(posid=posid) form = MyForm(request.POST, instance = fid) if request.method == "POST": vegaplan = 'vegaplan' in request.POST mhd = 'mhd' in request.POST ve = 've' in request.POST globalgap = 'globalgap' in request.POST tosave= models.MyModel(vegaplan=vegaplan, mhd=mhd, ve=ve, globalgap=globalgap) tosave.save(form) return render(request, "pages.html") If some could help me or just give me a hind a would be very happy, right know i lost every … -
Using custom query in django-filters
I'm trying to filter a Model using Filterset (django-filter) and render from/to select form field in my Template. Unfortunately I cannot figure out how to get it working. While my code and power_category fields render fine, only a text field gets displayed when trying to render the reported field, unless I set type="date", then the datepicker pops up when clicking the date field; however only one shows up (need two, to, and from to select the range). -
Django query to remove older values grouped by id?
Im trying to remove records from a table that have a duplicate value by their oldest timestamp(s), grouping by ID, so the results would be unique values per ID with the newest unique values per ID/timestamp kept, hopefully the below samples will make sense. sample data: id value timestamp 10 10 9/4/20 17:00 11 17 9/4/20 17:00 21 50 9/4/20 17:00 10 10 9/4/20 16:00 10 10 9/4/20 15:00 10 11 9/4/20 14:00 11 41 9/4/20 16:00 11 41 9/4/20 15:00 21 50 9/4/20 16:00 so id like to remove any values that have a dupliate value with the same id, keeping the newest timestamps, so the above data would become: id value timestamp 10 10 9/4/20 17:00 11 17 9/4/20 17:00 21 50 9/4/20 17:00 10 11 9/4/20 14:00 11 41 9/4/20 16:00 -
django google map or other map saving lat and long data on user pointed location
This is my model: c lass Shop(models.Model): lat = models.CharField( max_length=300, null=True, blank=True, ) long = models.CharField( max_length=300, null=True, blank=True, ) and this is my form: <form method="POST"> {% csrf_token %} <input type="text" name="lat"> <input type="text" name="long"> <input type="submit" value="save"> </form> I am trying to implement, there will be a map in the frontend, when user put the mouse pointer on the map, the pointed location lat and long data should be filled in my form. I have read google map API documentation and i see the API key is Lil bit expensive for me. I am finding a way to fill the form field with lat and long when user click on specific location on a map, It is no problem if it is google map or bing or other, i just need a solution for free so when user click on a location, it should be fill the form. I know javascript has solution to get current location lat and long but this is not my business logic. CAN Anyone help me to achive this? -
Updating and saving dict in django with post requests
I am trying to make a responsive tournament bracket with python/django and using $.post requests to update a tournament dict - which I pass to a 'bracket' template as a dictionary, render, then update by $.posting the passed in variable to a nother view, which updates, saves to server, then redirects to 'bracket' view. I am just starting to make some progress, but having issues with reformatting of the bracket object. Little more detail The bracket is initialized in python (in my views.py) in a bracket view, but I am calling in the view a Tournament class that I got from here. the Tournament class takes a list of players and then generates a dictionary corresponding to the games with the method t.generate_bracket(). I kind of restructure this and then pass it into a bracket view for displaying - I display the restructured array in my template but also pass in the un-restructured one I have little radio buttons that are bound to a $.post 'update_bracket' view. In the JS $.post, I send the array to the view, where I will call a t.play_game() method to update the bracket. Then - instead of a JSON or HTTP response and subsequent …