Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST urls - Dynamic Protocol
I am using Django REST Framework and doing the following: Request certain object via GET request The response includes the data + the specific url for that object Edit this object and send it back to the backend via PATCH request against the specific URL mentioned in step 2 Everything is working right when working in localhost, however after deployment I have a 'Mixed Content' error when sending the PATCH request, because I am serving my app under HTTPS protocol, but the urls (step 2) Django returns are HTTP Can I make these URLs generated by Django dynamic? So if the initial GET request is via HTTPS the urls are HTTPS and vice versa -
I can't understand how django's path() works
I've tried looking at the documentation, and read several questions of the same subject, and can't wrap my head around it. I've been trying to follow the tutorial, and while I've gotten pretty far I still cannot understand what the path function does. What does it do on this snippet? path('', views.index, name='index'), What about this one? path('books/', views.BookListView.as_view(), name='books'), Or this one? path('catalog/', include('catalog.urls')), -
Problems with header fields in django rest framework HMAC module?
So I've been trying to utilize the djangorestframework-hmac module (https://github.com/aaronlelevier/django-rest-framework-hmac) to secure a REST API with HMAC. But I'm running into what would seem to be a fundamental problem with it: as with most HMAC schemes, the client needs to put the message signature in a header field named 'Signature', but the problem is that header field names get translated by Django ('Signature' becomes 'HTTP-SIGNATURE'). But I can see in the code for django-restframework-hmac that the server is looking for a header field called 'Signature'. Now the module comes with an example, which works, but in the example, the client is running Django, which I believe may somehow be skirting around the header-field translation problem. But what if the client is not using django? How could the client possibly get his header fields seen by the server? Is there something I'm missing here about the way django uses header field names? -
how to get something from my database to appear on my django html project
I am trying to get a quote from my database to appear on my html webpage using django. IT will not appear here goes my index.html file **the code on this website put the quotes around my answer. in my program its no quotes on it. Other than that , the code is exactly how it appears in my file.: {%extends 'homepage/layout.html' %} {% block content %} {% for quote in quotes %} <h2>{{quote.body}}</h2> {% endfor %} {% endblock %} Here goes my models.py file: from django.db import models class Quote(models.Model): def __str__(self): return self.body Here goes my views.py file: from django.shortcuts import render from .models import Quote def index(request): quotes = Quote.objects.all()[:1], context = dict() context['quotes'] = quotes return render(request, 'homepage/index.html', context) When i run this, I get no errors. Its's just the quote that is stored in the database does not display on the screen . BUT When i run this in my index.html file : {%extends 'homepage/layout.html' %} {% block content %} {% for quote in quotes %} <h2>{{quote}}</h2> {% endfor %} {% endblock %} it displays the quote as a query set object. So I do know the quote can be referenced and my project is … -
How to change the view of Django FormFIeld in template
I am facing view issue as multiple clear button are showing in Django FormField template view. Here is my template code: {% for field in form.visible_fields %} <div class="form-row"> <div class="col-md-3 offset-md-1 lfta"> <label class='control-label' for="{{ field.label }}"> <span>{{ field.label }}</span> </label> </div> <div class="col-md-7 lftb amiR"> {% if field.id_for_label == 'id_pricing_sheet' or field.id_for_label == 'id_pt_agreement' %} {% render_field field class="form-control-file" %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted"> <font> {{ field.help_text|safe }}</font></small> {% endif %} </div> </div> {% endfor %} -
Why does form wizard forget data when I add an error?
I have a form wizard where I have add a non_field error at the end if a condition is not met. This works successfully unless I submit the form a second time with the error displayed. If I submit the form again, condition still not met, the form wizard forgets all the data, and renders the first form again. This is not a huge deal, but it looks ugly and would like to fix it. What is wrong with my logic that the form forgets data after non_field_error is rendered? if x: return HttpResponseRedirect(reverse('success')) else: form = self.get_form(data=self.request.POST, files=self.request.FILES) form.add_error(None, 'My error message.') return super(Form1, self).render(form, **kwargs) -
Django admin action with intermediate page: not getting info back
I'm trying to create an admin action that adds a custom time delta to some date. The time delta will be read from a input in the intermediate page. After confirming it, I will apply that delta to every instance selected previously. Using this code (I simplified for this question) I can't get the value of the entered time delta. I can't tell whether the user pressed the "Apply" button. models.py class Match(models.Model): date_of_match=models.DateTimeField() admin.py class MatchAdmin(admin.ModelAdmin): actions=('move_date',) def move_date(self,request,queryset): if 'apply' in request.POST: #to do, add timedelta to date_of_match print("I'M IN!") return render(request.'admin/move_date.html',{'matches':queryset}) move_date.short_description="Move date" move_date.html {% extends "admin/base_site.html" %} {% block content %} <form action="" method="post">{% csrf_token %} <p>How much delta?<p> <input type="number" step="1" value="days"/> <input type="hidden" name="action" value="move_date" /> <input type="submit" name="apply" value="Apply"/> </form> {% endblock %} -
How to add an attribute to an option in a select form in django python
I have models class tipo_pago(models.Model): descripcion = models.CharField(max_length=20) banco_req = models.BooleanField(default=False, verbose_name="Requiere banco", help_text="Activa esta casilla si se requiere el banco de origen") status = models.BooleanField(default=True) and class cliente_pago(models.Model): tEstado = ( ('pagado','Pagado'), ('pendiente','Pendiente'), ('cancelado','Cancelado'), ) cliente = models.ForeignKey('cliente',blank=False,null=True,on_delete=models.SET_NULL) fecha = models.DateTimeField(default=timezone.now) fecha_pago = models.DateField() tipo_pago = models.ForeignKey('tipo_pago',blank=False,null=True,on_delete=models.SET_NULL) banco = models.ForeignKey('banco', blank=True, null=True,on_delete=models.SET_NULL) referencia = models.CharField(max_length=25) cuenta = models.ForeignKey('cuenta',blank=False,null=True,on_delete=models.SET_NULL) importe = models.FloatField(default=0) pago = models.FloatField(default=0) saldo = models.FloatField(default=0) observacion = models.TextField(blank=True,null=True) estado = models.CharField(max_length=10,default='pendiente',choices=tEstado) My form to fill the fileds is the next one: class cliente_pagoModal(CustomModelForm): class Meta: model = cliente_pago exclude = ('fecha','pago','saldo','estado',) To the field "tipo_pago" in cliente_pago form i want to add a data parameter Now look like this: < select name="tipo_pago" class="form-control" required="" id="id_tipo_pago"> < option value="" selected="">--------- < option value="3">Efectivo < option value="2">Cheque < option value="1">Transferencia bancar < /select> but I want it to look like this < select name="tipo_pago" class="form-control" required="" id="id_tipo_pago"> < option value="" selected="">--------- < option value="3" data-banco_req="0">Efectivo < option value="2" data-banco_req="1">Cheque < option value="1" data-banco_req="2">Transferencia bancar < /select> I am using python 3.7 and django 2.0.8 -
form_valid / form_invalid / post functions never called
I looked other similar posts, but I can't point out where I'm going wrong. The code never calls form_valid() or form_invalid. I tried creating def post() as well, but post is never called either. home.html <form id="input-form" action="intermediate" method="post" enctype="multipart/form-data">{% csrf_token %} . . . <input type="submit" name="submit" value="Go to Next step" onclick="return check_sequences()"/> <input type="reset" value="Reset" id="reset"/> </form> urls.py urlpatterns = [ url(r'^$', views.main_view, name='deimmunization-main-view'), url(r'^result/$', views.result_view, name='result-view'), . . . ] forms.py class UserInputForm(forms.Form): sequence_text = forms.CharField(...) sequence_file = forms.Field(...) def __init__(self, request, *args, **kwargs): super(UserInputForm, self).__init__(*args, **kwargs) seqfile = kwargs.get('files') if seqfile: self.sequence_file = seqfile.get('sequence_file') else: self.sequence_file = None def clean(self): cleaned_data = super(UserInputForm, self).clean() sequence_text = cleaned_data['sequence_text'] sequence_file = cleaned_data['sequence_file'] . . . return cleaned_data views.py class MainView(edit.FormView): template_name = 'deimmunization/home.html' form_class = UserInputForm success_url = 'intermediate' @method_decorator(cache_control(no_cache=True, must_revalidate=True, no_store=True)) def dispatch(self, request, *args, **kwargs): return super(MainView, self).dispatch(request, *args, **kwargs) def get_form_kwargs(self): kwargs = super(MainView, self).get_form_kwargs() kwargs.update({'request' : self.request }) return kwargs def get(self, request, *args, **kwargs): return super(Mainview, self).get(request, *args, **kwargs) def form_valid(self, form): print("Form_valid called.") form = UserInputForm(self.request) result = form.process() . . . if (...) : return HttpResponseRedirect(self.success_url) else : return super(mainView, self).form_valid(form) def form_invalid(self, form): print("Form_invalid is called") So I have noticed … -
Unicode in django 2
I am used to using print to print the django model object that I define in __unicode__, but it seems that no longer works: >>> t=Timezone.objects.all()[0] >>> print (t) Timezone object (Andorra) >>> t.__unicode__() 'GMT-02:00 Andorra' How would I call the "print" method, like it was previously done in django, to return the unicode method? -
Wagtail: Changing the default setting for "UserProfile.submitted_notifications" from "True" to "False"
The default notification setting for a wagtail user instance seems to be "Receive notification when a page is submitted for moderation", which does not fit our needs: we do not want each and every wagtail user to be notified (emailed) when a page gets submitted for moderation. The default for this user notification setting is "True": # wagtail/wagtail/users/models.py # https://github.com/wagtail/wagtail/blob/master/wagtail/users/models.py#L25 class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) submitted_notifications = models.BooleanField( verbose_name=_('submitted notifications'), default=True, help_text=_("Receive notification when a page is submitted for moderation") ) … and I would like to change the default to "False" (e.g. users should opt-in for getting email notifications). But I do not know what’s the “best practices approach” for this task. And I was a little surprised to have this problem at all, since I assumed that only members of the "Moderators" group/role would be notified. (which does not seem to be true). What I tried/thought of: Modifying this setting pro grammatically (which worked): Existing user instances could be modified via shell: ./manage.py shell from django.contrib.auth import get_user_model User = get_user_model() for user in User.objects.all(): user.wagtail_userprofile.update(submitted_notifications=False) user.wagtail_userprofile.save() Modifying this setting in my CustomUser save() method (does not work): # project/users/models.py (pseudocode) class CustomUser(AbstractUser): def save(self, *args, **kwargs): super().save(*args, … -
How do I delete a Notification made with django's m2m_changed signal?
I've successfully been able to create a notification when a user 'likes' a post with this code: @receiver(m2m_changed, sender=Post.likes.through) def auto_create_like_notification(sender, instance, action, pk_set, **kwargs): if action == "post_add": Notification.objects.create(post=instance, user=instance.likes.through.objects.last().user, liked=True) Now, when action == "post_remove", I'm looking to delete this notification instance. I've been playing around trying to find out ways to filter Notifications.object to find the one for which a remove signal has just passed, but I haven't come up with anything. I can print(instance.likes.through.objects.all()) during the "pre_remove" and "post_remove" and see two of the same querysets, minus the removed Post_like. Is there a method to find the missing Post_like? If I could get that, I could filter my Notifications.object by post=instance, and then by user=Post_like.user. Here is my Post model: class Post(models.Model): photo = models.ImageField(upload_to=get_image_path, null=True, blank=True) caption = models.TextField(max_length=2200, null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') location = models.CharField(max_length=100, blank=True) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') -
Dynamically generated fields missing from cleaned_data in Django
This is driving me crazy. I'm using Django to build a form where a user can create recipes. A recipe can be associated to one or many ingredients, so those fields are dynamically generated (there's a button for the user to add as many fields as he likes). Those fields are named ingredient_0, ingredient_1, ingredient_2 and so on. Each recipe takes a certain quantity of each of those ingredients, and those fields are also dynamically generated (quantity_ingredient_0, quantity_ingredient_1...) This is what I have for my RecipeForm class: def __init__(self, *args, **kwargs): super(RecipeForm, self).__init__(*args, **kwargs) # Ingredients dropdown field INGREDIENT_CHOICES = [(ingredient.id, "{0} ({1})".format(ingredient, ingredient.unit)) for ingredient in Ingredient.objects.all()] # Generate fields with pre-filled recipe ingredients and respective quantities recipe_ingredients = RecipeIngredient.objects.filter(recipe=self.instance) for i in range(len(recipe_ingredients) + 1): field_name = 'ingredient_{}'.format(i) self.fields[field_name] = forms.ChoiceField(choices=INGREDIENT_CHOICES, required=False) self.fields['quantity_' + field_name] = forms.IntegerField(required=False) try: self.initial[field_name] = recipe_ingredients[i].ingredient self.initial['quantity_' + field_name] = recipe_ingredients[i].quantity except IndexError: self.initial[field_name] = "" self.initial['quantity_' + field_name] = 0 # Create an extra blank field field_name = 'ingredient_{}'.format(i+1) self.fields[field_name] = forms.ChoiceField(choices=INGREDIENT_CHOICES, required=False) self.fields['quantity_' + field_name] = forms.IntegerField(required=False) And: def clean(self): cleaned_data = super(RecipeForm, self).clean() ingredients = [] id_list = [] i = 0 field_name = 'ingredient_{}'.format(i) ##################################### print(self.data) print(cleaned_data) ##################################### # … -
How do I integrate Django and react-router-dom?
How do I setup the Django urls.py and the React Components to establish this? -
Django unclear behaviour on missed values on model initialization
I have a postgres Database and a model with a field as blank=False and null=True. Let's say: info = models.CharField('Facts and features', max_length=1024, blank=False, null=False) # facts and features Now, when I am creating a model like this: m = MyModel(param1=val1, param2=val2) and miss a value for info it basically won't raise any exception for that on saving. Even more, it will keep an empty value for info in the database after using save method. Any suggestions why does it happen? In my opinion if I miss to add a value in the model initialization, it should be at least considered as None, but it's not. I googled that and couldn't find an specific answer for that. But, found that only full_clean() model method performs checking and raises exceptions like these: ValidationError: {'info': ['This field cannot be blank.'], 'owner': ['This field cannot be blank.']} Any help is welcome! -
Queryset for current logged in user Django
I am doing queryset with my model. Now the queryset is displaying all the data in my html page. But I want to display only the logged in users data. models.py class Data(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Status = models.CharField(max_length=10, blank=False) Date = models.DateField(blank=True, null=True) views.py @login_required def search(request): status_list = Data.objects.all() status_filter = UserFilter(request.GET, queryset=status_list) return render(request, 'users/data.html', {'filter': status_filter}) filters.py class UserFilter(django_filters.FilterSet): class Meta: model = Data fields = { 'Date': ['year','month', ], 'user': ['exact', ], } I tried with different views.py also but it didn't work. @login_required def search(request, user): status_list = Data.objects.get(user=self.request.user).search(query) status_filter = UserFilter(request.GET, queryset=status_list) return render(request, 'users/data.html', {'filter': status_filter}) -
django.utils.datastructures.MultiValueDictKeyError: 'myfile'
During handlig POST request I get the error in the title. Changing request.FILES['myfile'] to request.FILES.get('myfile') didn't help. I have no idea why this occures. I've tried changing form attributes but that didn't help either. My view: def generate_random_user(request): if (request.method == 'POST'): text_info = request.POST.get('text_input') myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) local_file_path = os.path.join(settings.MEDIA_ROOT, filename) album = Album(local_file_path, text_info) task = album.slice.delay(album) songs_titles = album.songs_titles #converted_files_urls = [fs.url(path) for path in songs_paths] return HttpResponse(json.dumps({'task_id': task.id}), content_type='application/json') return render(request, 'index.html') The index html: <html> <head> <title>Celery Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <body style="text-align: center;"> <h1>Generate Random Users</h1> <progress id="progress-bar" value="0" max="100" style="display:none; margin-bottom: 1em;"></progress> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <br><textarea name="text_input" cols="40" rows="15" ></textarea> <br><button id="submit_btn" type="submit" align="center" >Upload and slice.</button> </form> <script type="text/javascript"> var frm = $('form'); var button = $('#submit_btn'); var pgrbar = $('#progress-bar'); button.click(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { if (data.task_id != null) { get_task_info(data.task_id); } }, error: function (data) { console.log("Something went wrong!"); } }); return false; }); function get_task_info(task_id) { $.ajax({ type: 'get', url: '/get-task-info/', data: {'task_id': task_id}, success: function (data) { frm.html(''); if (data.state == 'PENDING') { frm.html('Please wait...'); } … -
Haystack + Django CMS search error "reduce() of empty sequence with no initial value"
I'm relatively new to the Django world. Our client wants to add a search feature to their site so I'm integrating Haystack and Aldryn Search as described here: https://github.com/aldryn/aldryn-search I've also gone through here: https://django-haystack.readthedocs.io/en/v2.6.0/tutorial.html Exception Location: env/lib/python2.7/site-packages/haystack/backends/simple_backend.py in search, line 79 Here are some helpful information snippets: urls.py - (r'^search/', include('haystack.urls')), templates/search/search.html - {% extends 'base.html' %} {% block content %} <div class="primary-content"> <div class="container constrained"> <form method="get" class="paragraph" action="."> {{ form.as_table }} <div class="text-right"> <button type="submit" class="button"> Search </button> </div> {% if query %} <h3>Results</h3> {% for result in page.object_list %} <div class="post-preview paragraph"> <h3> <a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a> </h3> </div> {% empty %} <p>No results found.</p> {% endfor %} {% if page.has_previous or page.has_next %} <div> {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %} </div> {% endif %} {% else %} {# Show some example queries to run, maybe query syntax, something else? #} {% endif %} </form> </div> </div> {% endblock %} settings.py - HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } HAYSTACK_ROUTERS = ['aldryn_search.router.LanguageRouter', ] … -
Django image saving to certain size
I nees help saving images using django but when its saved I want it to be a certain size. I looked up some solutions online but none of them worked so i had to do it manually. Im using Django 1.11 and Python 3.6. -
Bulk_create is not working with batch_size parameter
I'm trying to use bulk_create, but it is only creating one object instead of the batch_size I stipulated. I'm using a variable for batch_size, so maybe that's the issue, but I can't think of why it should be a problem. Here's the code: x = 40 / 2 if 5 > 4: objs = ModelT( name=instance.name, author=instance.author, content=instance.content ) ModelT.objects.bulk_create(objs1, batch_size=x) I've also tried it with: ModelT.objects.bulk_create(objs1, x) and did not work either. -
Django model form validate using id's
Model, class ABC(models.Model): x = models.ForeignKey(A) y = models.ForeignKey(B) Model form, class ABCForm(forms.ModelForm): class Meta: model = ABC fields = '__all__' How can I validate this model form using ID's of x and y. I don't want to use plain django form or clean methods. Can I do it something like ? ABCForm(data={'x_id': 123, 'y_id': 431}) -
must be instance django
This is the merchant model: class Merchant(models.Model): merchant_token = models.CharField(max_length=255, unique=True) and this is transaction model wich the first field is linked to merchant_token on Merchant model: class Transaction(models.Model): transaction_merchant_token = models.ForeignKey(Merchant, on_delete=models.CASCADE) First i get the merchant token with POST request then i get the merchant field with : merchant = Merchant.objects.get(merchant_token__exact=posted_token) but when i want to insert new transaction with posted token : new_transaction = Transaction( transaction_merchant_token=merchant.merchant_token ) new_transaction.save() i get ValueError exception: Cannot assign "93C38:9VLlOUuaRq7J8boHyX80cI5MYy8yCpsb": Transaction.transaction_merchant_token must be a Merchant instance. -
OfflineGenerationError - Key not in Manifest Json
The Django Error: OfflineGenerationError at / You have offline compression enabled but key "e3efe8ea14c9eeeff843e0280b54e1d92c293a5018e6d4a0be93a65997d8e246" is missing from offline manifest. You may need to run "python manage.py compress". Here is the original content: Then it shows my CSS file content. {% load static %} @font-face { font-family: 'fontawesome'; src: url('{% static "global/fontawesome-5.0.13/fa-regular-400.woff2" %}') format('woff2'), url('{% static "global/fontawesome-5.0.13/fa-regular-400.woff" %}') format('woff'); } @font-face { font-family: 'NotoSans'; src: url(" {% static 'global/NotoSans-Regular.ttf' %}") format('truetype'); } @font-face { font-family: 'NotoSans'; src: url(" {% static 'global/NotoSans-BoldItalic.ttf' %}") format('truetype'); font-weight: bold; font-style: italic; } @font-face { font-family: 'NotoSans'; src: url(" {% static 'global/NotoSans-Italic.ttf' %}") format('truetype'); font-style: italic; } @font-face { font-family: 'NotoSans'; src: url(" {% static 'global/NotoSans-Bold.ttf' %}") format('truetype'); font-weight: bold; } @font-face { font-family: 'NotoSerif'; src: url(" {% static 'global/NotoSerif-Regular.ttf' %}") format('truetype'); } @font-face { font-family: 'NotoSerif'; src: url(" {% static 'global/NotoSerif-BoldItalic.ttf' %}") format('truetype'); font-weight: bold; font-style: italic; } @font-face { font-family: 'NotoSerif'; src: url(" {% static 'global/NotoSerif-Italic.ttf' %}") format('truetype'); font-style: italic; } @font-face { font-family: 'NotoSerif'; src: url(" {% static 'global/NotoSerif-Bold.ttf' %}") format('truetype'); font-weight: bold; } {% if newdesign %} @font-face { font-family: Concourse T3; src: url('{% static "global/concourse_t3_bold_italic-webfont.woff2" %}') format('woff2'), url('{% static "global/concourse_t3_bold_italic-webfont.woff" %}') format('woff'), url('{% static "global/concourse_t3_bold_italic-webfont.ttf" %}') format('ttf'); font-weight: bold; font-style: italic; … -
Is it possible to apply group membership when authenticating a user with django-mama-cas and django-cas-ng?
I am using django-mama-cas (2.4.0) and django-cas-ng (3.5.10) to manage user authorisation (single sign on, single log off, group membership) across a few django (1.11) projects. I am able to apply user attributes (first_name, last_name, email address) from the cas server to the cas-ng clients using the callback 'mama_cas.callbacks.user_name_attributes' in mama-cas and setting CAS_APPLY_ATTRIBUTES_TO_USER = True on my cas-ng clients. On my mama-cas server, I also add the user to a number of groups (snippet below) which I want to then apply to the users on the cas-ng clients. group = Group.objects.get(name=groupname) user.groups.add(group) However, when I try using the callback 'mama_cas.callbacks.user_model_attributes' in mama-cas none of the group memberships are applied to my clients (I check this via the admin interface and via the django shell). Is applying group membership from mama-cas to cas-ng possible or am I doing something wrong? If it's not possible my next best idea was to create some boolean custom user attributes, i.e. user.is_member_groupA etc but would welcome advice. Thanks in advance -
Django ORM Count group and subgroup
In my django project i had a table with a column named 'key_id'. Until today i had to group different values of this values, count it and display the largest result. I did this: maxpar = temp_test_keywords.objects.filter(main_id=test_id).values('key_id').annotate(total=Count('key_id')).order_by('-total').first() maxMax = maxpar['total'] all done. Today, we deceide to add another field to table, 'key_group'(could be 1,2,3,4) and now i have to use the same query for group and count max key_id field but related also for key_group. For example before if in my table there was 5 record with key_id=187 and 3 with 112 my query had to return 5, now if for that 5 records 4 contain 'key_group=1' and one = 2 query have to return 4 Hope i was clear Thanks in advance Luke