Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /blog/ in django 2.0
am getting this error trying to set a blog category page NoReverseMatch at /blog/ Reverse for 'category_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P[-a-zA-Z0-9_]+)$'] Here is my url.py from django.urls import path,include from .import views urlpatterns = [ path('blog/',views.post_list,name="post_list"), path('blog/post-detail/<slug:slug>',views.post_detail,name="post_detail"), path('blog/category-detail/<slug:slug>',views.category_detail,name="category_detail"), ] views.py from django.shortcuts import render,get_object_or_404 from.models import Post,Category # Create your views here. def post_list(request): object_list=Post.objects.all() context={ 'object_list': object_list, } return render(request,"blog.html",context) def post_detail(request,slug=None): post=get_object_or_404(Post,slug=slug) context={ 'post':post, } return render(request,"post_detail.html",context) def category_detail(request,slug=None): category=get_object_or_404(Category,slug=slug) post=Post.objects.filter(category=category,status='Published') context={ 'category':category, 'post':post, } return render(request,"category_detail.html",context) blog.html {% for obj in object_list %} {% if obj.status == 'Published' %} <article> <div class="embed-responsive embed-responsive-16by9"> <img src="images/blog1.jpg" alt="" /> </div> <div class="post-content"> <h2>{{obj.title}}</h2> <div> {{obj.created}} Author {{obj.user}} <h4><a href="{% url 'category_detail' slug=post.category.slug %}">{{obj.Category}}</a></h4> <hr/> <p>{{obj.body}}</p> <a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' obj.slug %}">Continue reading →</a><br> </div> </article> {% endif %} {% endfor %} category_detail.html {% extends "base.html" %} {% load static %} {% block seo_title %}{{category.seo_title}}{% endblock %} {% block seo_description %}{{category.seo_description}}{% endblock %} {% block Content %} <h2>{{category.title}}</h2> <p>{{category.description}}</p> {% for item in post %} {{item.title}} {{item.body|truncatechars:50}} {% endfor %} {% endblock Content %} NOTE THE OTHER VIEWS.PY ARE WORKING FINE JUST THE category_detail function -
Reverse for '' with keyword arguments '' not found
I'm using django 2.1 and python 3.6 and I'm running to an issue which seems like other people have ran into in past years. This is part of my views.py: def blog_list_by_cat(request, cat_id, cat_name): ... def blog_list_by_genre(request, genre_id, genre_name): ... This is my urls.py: urlpatterns = [ path('', views.index, name='index'), re_path(r'^blog/(?P<blog_id>\d+)/(?P<slug>[^/]+)/?$', views.single_blog, name='single_blog'), re_path(r'^blog-list/(?P<cat_id>\d+)/(?P<cat_name>[^/]+)/?$', views.blog_list_by_cat, name='blog_list_by_cat'), path('blog-list/latest/', views.blog_latest, name='blog_latest'), re_path(r'^blog-list/genre/(?P<genre_id>\d+)/(?P<genre_name>[^/]+)/?$', views.blog_list_by_genre, name='blog_list_by_genre'), ] and in my template when I call those links, this one works fine: {% for cat in cat_list %} <a class="dropdown-item" href="{% url 'blog_list_by_cat' cat_id=cat.id cat_name=cat.cat %}">{{ cat.cat }}</a> {% endfor %} While this one throw an error in the same template: {% for genre in genre_list %} <li><a class="dropdown-item" href="{% url 'blog_list_by_genre' genre_id=genre.id genre_name=genre.title %}">{{ genre.title }}</a></li> {% endfor %} This is the full error: Exception Type: NoReverseMatch Exception Value: Reverse for 'blog_list_by_genre' with keyword arguments '{'genre_id': 5, 'genre_name': 'Action'}' not found. 1 pattern(s) tried: ['blog-list/genre/(?P\d+)/(?P[^/]+)/?$'] As you can see, I'm using named urls and I'm using qoutations around the url name and not adding app name in urls. both codes are the same. But why the second one does not work? -
Django templates - include and repeat the block contents
In my home.html page, I am trying to include a header.html file along with extending base.html. Following is my code {% extends "base.html" %} {% block body %} {% include 'header.html' %} # including the block navigation from header.html <nav id='header-nav'>{% block nav %} {% endblock %}</nav> # including the block image from header.html <div id='header-img'>{% block image %} {% endblock %}</div> # Reusing the same navigation in footer from header.html <div id='footer-nav'>{% block nav %} {% endblock %}</div> {% endblock %} Home.html looks like the following {% block image %}<h1>I am image</h1>{% endblock %} {% block nav %}<h1>I am navigation</h1>{% endblock %} However, it returns an error - ''block' tag with name 'nav' appears more than once'. Why is that? Is there any solutions to this? Regards -
How to update image in django?
So here is! I would like to change the image to enter by the user when he wants to change his profile picture but it does not work while the other information they change. views.py : @login_required(login_url="") def personne_form_view(request): if request.method == 'POST': form = PersoForm(request.POST, request.FILES,error_class=ParagraphErrorList) personne = Personne.objects.filter(Q(nom_pre__icontains=request.POST.get('nom_pre'))) if form.is_valid(): if not personne : form.save(commit=True) return redirect('manapoitra_client') else : messages.warning(request,'Cette personne existe déjà!') else: form = PersoForm() return render(request, 'personneH.html', {'form': form}) @login_required(login_url="") def update_client(request, pk): client = Personne.objects.get(pk=pk) form = PersoForm(request.POST or None,error_class=ParagraphErrorList, instance=client) if form.is_valid(): form.save() return redirect('manapoitra_client') return render(request, 'editClient.html', {'form': form, 'client': client}) models.py : class Personne(models.Model): tof = models.FileField(verbose_name="Photo") nom_pre = models.CharField(max_length=60, verbose_name="Nom") choices_sexe = ( ('F', 'Femme'), ('H', 'Homme') ) sexe = models.CharField(max_length=1,choices=choices_sexe) adresse = models.CharField(max_length=70, verbose_name="Adresse") telephone = models.CharField(max_length=10, verbose_name="Télèphone") email = models.EmailField(verbose_name="Courriel") agence = models.ForeignKey(Agence, verbose_name="Agence", on_delete=models.CASCADE) service = models.ForeignKey(Service, verbose_name="Service", on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True, verbose_name="Date de création") def __str__(self): return self.nom_pre et dans mon templates : {% extends 'base.html' %} {% block content %} <div class="centrer"> <form method="POST"> {% csrf_token %} <table> {{ form.as_table }} <tr> <td></td> <td><button class="btn btn-info formbut">Sauvegarder</button></td> </tr> </table> </form> </div> {% endblock %} thank you in advance -
Display Image in Django
I've been unable to make this work although I realise there are similar questions. Hoping someone can point me in the right direction. I have a django app which allows uploads of images with it. Right now my model looks like this. The image is not displaying for some reason when it is called from the code. The reasons I can imagine are in the view.py file, or how I am calling it in the template file. Appreciate your help in advance, MODELS class Category(models.Model): name = models.CharField(max_length=128, unique=True) image = models.ImageField(blank=True, null=True, upload_to="locations/%Y/%m/%D") views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name VIEWS def index(request): # Query the databse for a list of ALL categories currently stored. # Order the categories by no likes in descending order . # Retrieve the top 5 only - or all if less than 5. # Place the list in context_dict dictionary # that will be passed to the template engine. category_list = Category.objects.order_by('-likes')[:5] page_list = Page.objects.order_by('-views')[:5] context_dict = {'categories': category_list, 'pages': page_list} # Render the response and send it back! return render(request, 'Spaces/index.html', … -
Fitlering queryset by is not None
I'm attempting to filter a queryset based on amount is not None userservices = UserService.objects.filter(user=user) userservices = userservices.filter(amount=None) I'm getting the following error: name 'amount' is not defined Any thoughts? Thanks! -
Django Unhandled exception in thread started by at python manage.py runserver
I am running Django project on linux(Ubuntu16.04), Recently i was uninstall my os and reinstall the same OS on my system.I have some django project previously it was working very well, after installing the os and All django packages It is not running but however if i create any new django project with django-admin startproject name.. it works . The following error i am getting Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f7ceceb5730> Traceback (most recent call last): File "/home/balu/Desktop/yottaasys/django-hrms/hrm_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/balu/Desktop/yottaasys/django-hrms/hrm_env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/balu/Desktop/yottaasys/django-hrms/hrm_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/home/balu/Desktop/yottaasys/django-hrms/hrm_env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/balu/Desktop/yottaasys/django-hrms/hrm_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/balu/Desktop/yottaasys/django-hrms/hrm_env/lib/python3.5/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/balu/Desktop/yottaasys/django-hrms/hrm_env/lib/python3.5/site-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python3.5/logging/config.py", line 490, in configure raise ValueError("dictionary doesn't specify a version") ValueError: dictionary doesn't specify a version -
Filtering on action decorator - Django Rest Framework
I am trying to filter data using a decorator action on Django Rest Framework, it works perfect if I use the global queryset (get_queryset() function) but I need to use it in a separate function. I am using django-filter to perform it. This is the code. My view: class ShippingAPI(viewsets.ModelViewSet): serializer_class = ShippingSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('origin__department', 'destination__department', 'first_collection_date', 'last_collection_date', 'vehicle') The override (action) @action(detail=False, methods=['GET']) def filter_shippings(self, request, **kwargs): queryset = Shipping.objects.filter(status=2, orderStatus=0) serializer = SearchShippingSerializer(queryset, many=True) #Yes, I am using another serializer, but it is solved,I use diferent if it is necesary return Response(serializer.data) After use my url 'api/filter_shipping/(all filters here)', this still return all the data without the filters I am requesting. Thanks for your help -
Django ORM appending Table Name when accessing table
I am new to django and I just finished my fist app in django. Now, I want to deploy it. As this app is not stable so I deployed it with light weight python runserver command on the server. I took a dump of my database and generate the same database with this dump on the server. Now the problem is, when I run the application, the django ORM access the database with [dbname].[tablename] for example hubstaff.logentry_project. hubstaff is the name of the database on the server, logentry is app name and logentry_project is table name. The database contains tables without [database] prefix (only logentry_project) so it gives an error (1146, "Table 'hubstaff.LogEntry_project' doesn't exist") Here is my settings of DATABASE DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join('hubstaff'), 'USER':'root', 'PASSWORD': 'haha', 'HOST':'localhost' } } following is the mysql dump DROP TABLE IF EXISTS `logentry_project`; CREATE TABLE IF NOT EXISTS `logentry_project` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `startDate` date NOT NULL, `endDate` date DEFAULT NULL, `sourceOfProject` varchar(20) NOT NULL, `paymentType` varchar(20) NOT NULL, `ProjectPaymentAmount` int(10) UNSIGNED DEFAULT NULL, `sourceName` varchar(20) DEFAULT NULL, `is_Active` tinyint(1) NOT NULL, `projectSeverity` int(10) UNSIGNED NOT NULL, `hubstaffName` varchar(30), `hoursToWork` int(10) … -
How to return to current tab after clicking the submit button?
Here is the script for tab. <script> function openEvt(evt, evtName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(evtName).style.display = "block"; evt.currentTarget.className += " active"; } function showDiv() { document.getElementById('pop').click(); } </script> Here is my view. <div class='col-sm-12'> <div id="Pop" class="tabcontent"> <form method="GET"> <select class='name' name='name'> <option value="Please select" disabled selected>- Please Select -</option> {% for name in name_list %} <option value="{{ name }}">{{ name }}</option> {% endfor %} </select> <button onclick="showDiv()" type="submit">Go</button> </form> <table id="model_table" class="table table-bordered"> <thead> <tr> <th colspan=2>Model</th> <th>Quantity</th> </tr> <tr> {% for pop in model_pop %} <td>{{ pop.name }}</td> <td>{{ pop.model }}</td> </tr> {% endfor%} </thead> </table> </div> Here is the code for tab. <div class="tab"> <button class="tablinks" onclick="openEvt(event, 'Home')">Home</button> <button id='pop' class="tablinks" onclick="openEvt(event, 'Pop')" >Pop</button> </div> I want to remain the same tab after press the 'GO' button. I've added the function 'showDiv()', but still won't remain the same tab after pressing the 'GO' button. -
How should Postgres be installed to run as a daemon under user name _postgres on Mac OSX?
I followed directions for installing Postgres on Mac OS X using Brew. All worked well. I placed a .plist in my Library/LaunchAgents and had Postgres running when I logged in. However, when I logged out postgres shuts down (which is correct behavior for processes started by launchd which are in a user's Library/LaunchAgents directory). I wanted to have the database running all the time for all users so I tried to move my file homebrew.mxcl.postgresql.plist into the directory /Library/LaunchDaemons. I set the owner:group to root:wheel and set permissions as well. This didn't work as Postgres said it wouldn't run as root (reported in the log file in /usr/local/var/log). So I added a UserName and GroupName to be _postgres for each. It wouldn't run, and I believe there were permission issues, which I gather is that postgres running as postgres running as user:group of _postgres:_postgres cannot read files in /usr/local/var/postgres or /usr/local/var/log which are all sholland:admin for user:group (brew installed files under my userid holland and group admin). I changed the UserName to sholland and GroupName to admin in /Library/LaunchDaemons/homebrew.mxcl.postgresql.plist, and now postgres is running happily each restart as user sholland group admin. This is all fine, but I would like … -
Django NoReverseMatch: Reverse not found, not a valid view function or pattern name.
I have a Django app that resolved urls correctly as of a few days ago but no longer does so. Looking at my git log nothing pertaining to urls changed, but all of a sudden is appears Django is not loading urls for the application in question. The debug page shows the app is installed (though it's last in the load order, if that matters). The behavior I'm seeing implies that Django is either ignoring or overriding only some parts of the app's urls.py file though-- some urls defined by the app in the same urls.py file do load! Namespacing: While it would likely make short work of the issue, I'm trying to override existing non-namespaced urls and cannot refactor the code that exists outside the scope of my app to establish the namespace. So that is not an option. I simply want to trump the parent project's url resolution so my views are called instead of stock. Any help would be appreciated! -
Scaling Django using cache and database clusters
I'm working on the optimization and the scalability of a django project. At the moment, our infrastructure is as follow : One web server; One database server (Postgresql); Media and Static files are managed using aws S3. We want to scale our infrastructure according to this figure : I read the django documentation about the database replication, and the django caching built in API. But things are not clear for me in case we have multiple web app servers. Should we mention the same databases locations in the settings.py files so that all the web app servers use the same cache servers and database cluster ? Any documentation that explains in details the implementation of this architecture ? -
Permission denied when mkdir inside of a django Docker container when running collectstatic
I've modified django-cookiecutter default production template to make caddy web server serve static files. I'm using volumes to map the ./static directories in django and caddy containters through host ./static directory, but I'm getting permissions error when docker executes python manage.py collectstatic --noinput while trying to create a subfolder of ./static. Traceback (most recent call last): File "/app/manage.py", line 30, in <\module> execute_from_command_line(sys.argv) ... File "/usr/local/lib/python3.6/site-packages/collectfast/management/commands/collectstatic.py", line 111, in copy_file self.do_copy_file(args) File "/usr/local/lib/python3.6/site-packages/collectfast/management/commands/collectstatic.py", line 100, in do_copy_file path, prefixed_path, source_storage) File "/usr/local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file self.storage.save(prefixed_path, source_file) File "/usr/local/lib/python3.6/site-packages/django/core/files/storage.py", line 49, in save return self._save(name, content) File "/usr/local/lib/python3.6/site-packages/django/core/files/storage.py", line 236, in _save os.makedirs(directory) File "/usr/local/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/app/static/sass' I tried chown -R systemd-timesync:root static inside host, creating ./static folder inside host as root, and adding RUN mkdir /app/static && chown -R django /app/static inside django container's Dockerfile (it executed as container's root user). docker-compose.yml version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_caddy: {} services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile volumes: - ./static:/app/static depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile volumes: - production_postgres_data:/var/lib/postgresql/data - production_postgres_data_backups:/backups env_file: - ./.envs/.production/.postgres caddy: … -
Django Admin is not showing list and filter options
When I get yo the Admin site, the models page is not showing my list_display or filter options. I can get in a model and change database info, that seems to work ok. It just seems not to recognizes my setup. It used to work just fine, I don´t know exactly when in my app update this started happening. from django.contrib import admin from .models import ProductosBase, Marcas, Categorias_Producto admin.site.register(ProductosBase) class ProductosBaseAdmin(admin.ModelAdmin): list_display = ('marca', "categoria_producto", "producto", "color", "foto_1") list_filter = ('marca', "categoria_producto", "producto") fields = (("codigo_kinemed", 'marca'), ("categoria_producto", "producto"), ("color", "packaging"), ("ancho", "largo"), ("units_inner", "inner_master", "tier"), "descripcion", "foto_1", "foto_2", "video_link") def __unicode__(self): return self.name admin.site.register(Marcas) class Marcas(admin.ModelAdmin): list_display = 'marcas' fields = ['marcas'] admin.site.register(Categorias_Producto) class Categorias_Producto(admin.ModelAdmin): list_display = 'Categorias_Producto' `enter code here`fields = ['Categorias_Producto'] -
Django: Nested multicolumn join
There is a way to define multicolumn relation in Django using RelatedObject. However, I can't manage to define multicolumn relation if one of the source columns is not local. In my particular case it is related field from another table (another join), but I can imagine it could be any expression. Example: class A(models.Model): a_value = models.IntegerField() class B() key1 = models.IntegerField() key2 = models.IntegerField() b_value = models.IntegerField() class Meta: unique_together = (('key1', 'key2'),) class C() a = models.ForeignKey(A) c_value = models.IntegerField() b = models.RelatedObject( B, from_fields=('a__a_value', 'c_value'), # <<< note the __ to_fields=('key1', 'key2'), ) -
Display relationship attribute in django template
So, in my models I have: class Recipe_Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.FloatField() GRAM = 'g' KILOGRAM = 'kg' LITER = 'l' CENTILITER = 'cl' UNITY_CHOICES = ( (GRAM, 'Gram(s)'), (KILOGRAM, 'Kilogram(s)'), (LITER, 'Liter(s)'), (CENTILITER, 'Centiliter(s)'), ) quantityUnit = models.CharField( max_length=2, choices=UNITY_CHOICES, default=GRAM, ) In my template: {% for ingredient in recipe.ingredients.all %} <li>{{ ingredient.name }} - # quantity goes here </li> {% endfor %} How can I show the quantity atribute of the Recipe_Ingredient associated with this recipe and ingredient? In the shell I could do this query: Recipe_Ingredient.objects.get(ingredient=Ingredient.objects.get(name='Cenoura'), recipe=Recipe.objects.get(name='Teste')), but I'm not quite sure how to do it in the template and what's the correct way of doing it. -
Django __search lookup causes FieldError
I have a database of Pattern objects and I want to get all patterns which has field Pattern.substring contained by sentence: "This sentence has to contain all returned Pattern objects". So it returns for example Pattern objects with these .substring values: "This sentence","all", "ce all returned" .... So I need something like reverse lookup. As far as I know, __search should do that but it raises error: Pattern.objects.filter(substring__search="This sentence has to contain all returned Pattern objects") Although I use django.db.backends.postgresql, it raises: FieldError: Unsupported lookup 'search' for CharField or join on the field not permitted. Do you know how to make it work? Full traceback: FieldError Traceback (most recent call last) <ipython-input-16-80407f61e9e0> in <module>() ----> 1 Pattern.objects.filter(substring__search="This sentence has to contain all returned Pattern objects") ~/.virtualenvs/ticketscrawler/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs) 80 def create_method(name, method): 81 def manager_method(self, *args, **kwargs): ---> 82 return getattr(self.get_queryset(), name)(*args, **kwargs) 83 manager_method.__name__ = method.__name__ 84 manager_method.__doc__ = method.__doc__ ~/.virtualenvs/ticketscrawler/lib/python3.6/site-packages/django/db/models/query.py in filter(self, *args, **kwargs) 834 set. 835 """ --> 836 return self._filter_or_exclude(False, *args, **kwargs) 837 838 def exclude(self, *args, **kwargs): ~/.virtualenvs/ticketscrawler/lib/python3.6/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs) 852 clone.query.add_q(~Q(*args, **kwargs)) 853 else: --> 854 clone.query.add_q(Q(*args, **kwargs)) 855 return clone 856 ~/.virtualenvs/ticketscrawler/lib/python3.6/site-packages/django/db/models/sql/query.py in add_q(self, q_object) 1251 # So, … -
NoReverseMatch at `redirect()` with existing view methods
I've burrowed through the mound of NoReverseMatch questions here on SO and elsewhere, but to no avail. I have a view method, clean, and within in a redirect: def clean(request, aid): if request.method == 'POST': return redirect(enrich, permanent=True, aid=account.id) else: return render(request, 'clean.html') And a view method called enrich: def enrich(request, aid): return HttpResponse('this be the enrich page') It has a path in urls.py: path('<aid>/enrich/', views.enrich, name='enrich'), And yet, when calling on the redirect in the clean method, I am lovingly told this by Python: NoReverseMatch at /app2/<aid removed>/clean/ Reverse for 'app2.views.enrich' not found. 'app2.views.enrich' is not a valid view function or pattern name. Which leaves me flummoxed, as app2.views.enrich does indeed exist. What am I to do? The path exists and operates correctly (if I visit /app2/<aid>/add/, I am welcomed with the proper HTTP response), but on redirect it doesn't actually seem to work, and neither do any of the other views. Some context: There are 3 apps in this Django project All of these apps have proved functional along with their views The versioning is Django 2.1 and Python 3.7.1 Disclaimer: the app is not actually called 'app2', that is simply a placeholder. -
Django: Query DB for most recent record for each type
I'm collecting data about WiFi enabled devices, and I'm storing the MAC Address, as well as the time the data was collected in a database. Each device is detected multiple times, which means that the db table has multiple rows with the same MAC address, but different detection times, like so: What I want, is to get only the most recent detection for every MAC Address. In the example above, that would be: Nov. 17, 2018, 6:17 a.m.: 02:e3:e6:b4:63:81 Nov. 17, 2018, 6:20 a.m.: 0a:13:0b:18:c0:5e Nov. 17, 2018, 6:20 a.m.: 16:50:1d:82:cf:fa How can I filter my DB query to achieve something like this? models.py from django.db import models """ Node is a Pi Zero. Each time one of these is found, we want to display it as a map marker """ class Node(models.Model): # A human readable name for the node name = models.CharField(max_length=30, default='Pi Zero') mac_address = models.CharField(max_length=30, primary_key=True) time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name """ Device is a WiFi enabled devices. The Pi Zeros discover new Devices and feed that information to the mesh network sink. The sink node then makes a POST request to this webapp that instantiates an instance of this model. This data is … -
Can't delete the objects and get reverse_lazy. asking for confirm_delete.html when should redirect to index page
first of all thanks for your time. I'm pretty new at django framework and following a tutorial. it was going fine until i try to clean my code. i've already read de documentation of reverse and im not getting the use of lazy reverse. When i delete a object on template should redirect me back to index.html although i get: TemplateDoesNotExist at /webdeve/dream/4/delete/ webdeve/dreams_confirm_delete.html Those are my urls.py: from django.conf.urls import url from webdeve import views app_name = 'webdeve' # Dreams urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), # Dreams/detail url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # Dreams/detail/add url(r'dream/add/$', views.DreamCreate.as_view(), name='dream-add'), # Dreams/detail/Update url(r'dream/(?P<pk>[0-9]+)/$', views.DreamUpdate.as_view(), name='dreams-uptdate'), # Dreams/detail/detete url(r'dream/(?P<pk>[0-9]+)/delete/$', views.DreamDelete.as_view(), name='dreams-delete'), ] my delete view.py class DreamDelete (DeleteView): model = Dreams success_url = reverse_lazy('webdeve:index') and the function at html file: {% for Dreams in object_list %} <a href="{% url 'webdeve:detail' Dreams.id %}"><img src={{ Dreams.imagem }}></a> <li><a href="{% url 'webdeve:detail' Dreams.id %}"> {{ Dreams.titulo }} - {{ Dreams.objetivo }} </a><li> <!--delete BUTTON--> <form action="{% url 'webdeve:dreams-delete' Dreams.id %}"> {% csrf_token %} <input type="hidden" name="dreams_id" value="{{ Dreams.id }}" method="post" style="display: inline" > <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> {% endfor %} Thanks for attention! -
How to use extra field from modelForms to query an object? Django
I have the following form: class Recipe_IngredientForm(forms.ModelForm): class Meta: model = Recipe_Ingredient fields = ('quantity', 'quantityUnit') def __init__(self, *args, **kwargs): super(Recipe_IngredientForm, self ).__init__(*args, **kwargs) self.fields['ingredient_form'] = forms.CharField() And I'm trying to get the value of this form to search for an object, if it exists, i'll set it to be saved in my model. def recipe_add_ingredient(request, pk): recipe = get_object_or_404(Recipe, pk=pk) if request.method == "POST": form = Recipe_IngredientForm(request.POST) if form.is_valid(): recipeIngredient = form.save(commit=False) recipeIngredient.recipe = recipe aux = form.fields['ingredient_form'] recipeIngredient.ingredient = Ingredient.objects.get(name=aux) recipeIngredient.save() return redirect('recipe_detail', pk=recipe.pk) else: form = Recipe_IngredientForm() return render(request, 'recipe/recipe_add_ingredient.html', {'form': form}) But I get an error when submitting the form: Ingredient matching query does not exist, but it shows that I'm getting a value that exists via GET, and if I query the exact same thing in the shell, it return my object. Any Idea? -
Edit extended user model
So I have this custom User Model Extending AbstractBaseUser MODEL class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=50, unique=True, blank=True, null=True) userid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) first_name = models.CharField(max_length=20, blank=True, null=True) last_name = models.CharField(max_length=20, blank=True, null=True) phone = models.CharField(max_length=15, unique=True, blank=True, null=True) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD='email' REQUIRED_FIELDS=['first_name', 'last_name',] def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, from_email, [self.email], **kwargs) def __str__(self): # __unicode__ on Python 2 return self.userid FORMS class MyUserForm(forms.ModelForm): class Meta: model = MyUser fields = ['email', 'first_name', 'last_name', 'phone', 'password'] VIEWS def update_user(request): if request.method == 'POST': form = MyUserForm(data=request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('dashboard') return redirect('inbox') else: form = MyUserForm() return render(request, 'dashboard.html', {'form': form}) Every time I submit the form it returns invalid i.e. it redirects to url 'inbox' as given in the view. I've going through the code and tweaking for hours and haven't figured out why it keeps returning … -
Django rest framework add field to serializer that does not get added to every entry
I am trying to add data to a serializer, but I am having trouble getting it to only add the field to the response once instead of for each entry. Here is my code: class FriendGiftSerializer(ModelSerializer): giftDisplayData = AllGiftSerializer(source='giftId', required=True) bestMatch = serializers.IntegerField() topAttribute = serializers.SerializerMethodField() class Meta: model = FriendGift fields = ('giftId', 'giftDisplayData', 'bestMatch', 'topAttribute') def get_topAttribute(self, obj): return self.context["top_attribute"] And the topAttribute field is added to every instance of FriendGift instead of just once at the end. I feel like I am missing something small, but am having trouble finding the right resource for how to solve this. Appreciate the help! -
Save facebook a link of profile picture in model using django-allauth
I'm using DRF and django-allauth. I'm trying to save a link of profile picture in my model. When I'm logging in my app through Facebook at first time, I'm getting django.db.utils.IntegrityError: UNIQUE constraint failed: user_profile.user_id. When I'm logging in my app through Facebook at second time, I'm getting Not Found: /profile/user/36/ and come in my app. I really can't figure it out how to fix it. Here is my model.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from allauth.account.signals import user_signed_up, user_logged_in from allauth.socialaccount.models import SocialAccount import hashlib try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding import force_unicode as force_text class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') city = models.CharField(max_length=30, blank=True) about = models.TextField(blank=True) avatar = models.ImageField(upload_to='avatars/', verbose_name='Images', blank=True) sound = models.BooleanField(default=False) points = models.DecimalField(max_digits=4, decimal_places=2, default=0.00) energy = models.IntegerField(default=0) avatar_url = models.URLField(max_length=256, blank=True, null=True) class Meta: db_table = 'user_profile' verbose_name = 'Profile' verbose_name_plural = 'Profiles' def __str__(self): return str(self.user) // GET PICTURE FROM SOCIAL @receiver(user_logged_in) def set_initial_user_names(request, user, sociallogin=None, **kwargs): preferred_avatar_size_pixels = 256 if sociallogin: if sociallogin.account.provider == 'facebook': picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format( sociallogin.account.uid, preferred_avatar_size_pixels) profile = UserProfile(user=user, avatar_url=picture_url) profile.save() @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) …