Rectangle 27 3

Rating.filter(company__in=[company_a, company_b]).distinct()
IndicatorRatingOptions.filter(company__in=[company_a, company_b]).distinct()

python - In Django I have a complex query where I need only the unique...

python django django-models
Rectangle 27 0

rule_object = Ruleinfo()

This just instantiates a new model object. It is not saved or assigned values. Since it is not saved it does not have an id value.

assigning your rule_object values: rule, from, to, priority, and cisp values, should fix your problem.

IntegrityError error while saving value of to foreign key in django - ...

django django-models django-forms django-views
Rectangle 27 0

formfield_for_foreignkey

You will have to append the current object value to the Q in the kwargs["queryset"].

How to limit choices in a foreign key in Django but always include cur...

django django-models django-forms django-admin
Rectangle 27 0

formfield_for_foreignkey

You will have to append the current object value to the Q in the kwargs["queryset"].

How to limit choices in a foreign key in Django but always include cur...

django django-models django-forms django-admin
Rectangle 27 0

The original idea of Django Rest Framework's serialization of relations is to not change values of related fields. It means that your payload should contain a pk of PhotoData object, not a dataset for it. It's like in models you can't assign a dict to a foreign key field.

Good (works only with serializers.PrimaryKeyRelatedField which contains problems itself):

payload = {"image_data": 2}

Bad (not works in DRF by default):

payload = {"image_data": {'thisdata': '{}'}}

Actually the data model that you provided doesn't need PhotoData at all (you can move thisdata field to Photo), but let's assume you have a special case even when Zen of Python says Special cases aren't special enough to break the rules..

PhotoDataField
class PhotoDataField(serializers.PrimaryKeyRelatedField):

    def field_to_native(self, *args):
        """
        Use field_to_native from RelatedField for correct `to_native` result
        """
        return super(serializers.RelatedField, self).field_to_native(*args)

    # Prepare value to output
    def to_native(self, obj):
        if isinstance(obj, PhotoData):
            return obj.thisdata
        return super(PhotoDataField, self).to_native(obj)

    # Handle input value
    def field_from_native(self, data, files, field_name, into):
        try:
            int(data['image_data'])
        except ValueError:
            # Looks like we have a data for `thisdata` field here.
            # So let's do write this to PhotoData model right now.
            # Why? Because you can't do anything with `image_data` in further.
            if not self.root.object.image_data:
                # Create a new `PhotoData` instance and use it.
                self.root.object.image_data = PhotoData.objects.create()
            self.root.object.image_data.thisdata = data['image_data']
            self.root.object.image_data.save()

            return data['image_data']
        except KeyError:
            pass
        # So native behaviour works (e.g. via web GUI)
        return super(PhotoDataField, self).field_from_native(data, files, field_name, into)
PhotoSerializer
class PhotoSerializer(serializers.ModelSerializer):

    image_data = PhotoDataField(read_only=False, source='image_data')

    class Meta:
        model = Photo
        fields = ("id", "user", "image_data")
payload = {"image_data": '{}'}
resp = requests.patch(request.build_absolute_uri("/api/photo/1/"), payload)

and the "good" request also

photodata = PhotoData.objects.get(pk=1)
payload = {"image_data": photodata.pk}
resp = requests.patch(request.build_absolute_uri("/api/photo/1/"), payload)
"image_data": <photodata's thisdata value>,

But, even if you will fix the validation problems with this approach it still be a huge pain in ass as you can see from my code (this is only thing DRF can offers you when you want to "break a normal workflow", Tastypie offers more).

class PhotoDataSerializer(serializers.ModelSerializer):
    class Meta:
        model = PhotoData
        fields = ("id", "thisdata")


class PhotoSerializer(serializers.ModelSerializer):
    image_data = PhotoDataSerializer()  # or serializers.RelatedField

    class Meta:
        model = Photo
        fields = ("id", "user", "image_data", "test")

and now define a specific method in your api's view that you will be able to use to set the data for any photo

from rest_framework import viewsets, routers, generics
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status

# ViewSets define the view behavior.


class PhotoViewSet(viewsets.ModelViewSet):
    model = Photo
    serializer_class = PhotoSerializer

    @action(methods=['PATCH'])
    def set_photodata(self, request, pk=None):
        photo = self.get_object()
        serializer = PhotoDataSerializer(data=request.DATA)
        if serializer.is_valid():
            if not photo.image_data:
                photo.image_data = PhotoData.objects.create()
                photo.save()
            photo.image_data.thisdata = serializer.data
            photo.image_data.save()
            return Response({'status': 'ok'})
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

Now you can do almost the same request as you doing now, but you have much more extensibility and division of responsibilities in code. See the URL, it's appended when you have @action's wrapped method.

payload = {"thisdata": '{"test": "ok"}'}
resp = requests.patch(request.build_absolute_uri("/api/photo/1/set_photodata/"), payload)

Thank you! This is an excellent answer. I did over simplify my reasons for having thisdata as a related model for the OP. I have done some research since you posted this and understand a lot more your reasoning. This was a massive help. again thanks

python - Getting non_field_errors using JSONField() - Stack Overflow

python django django-rest-framework
Rectangle 27 0

You are just getting to the empty forms in your formset.

TableFormSet = formset_factory(InventoryRowForm, extra=6)

Every time you hit this view, a formset with six extra empty forms will be created. Then later in your for loop, the call to form.save(commit=False) will not return an InventoryRow with an associated Product object, hence the DoesNotExist error when you later try to access the product.sale_price.

You should add an if that checks that the form is "bound"[1]:

for form in table_formset.forms:
    if form.is_bound:
        t = form.save(commit=False)
        t.single_price = t.product.sale_price
        t.invoice = invoice
        #...
        t.save()

python 2.7 - how to get value from my foreign key in django form - Sta...

django python-2.7 django-models django-forms
Rectangle 27 0

I do not understand the point of Admin over here. From the code, what I understood is you creating a simple django form for your site and getting the error on form submission. If that's case, the solution is quiet easy. This error is generated because you are try to save a record in your Note model without any reference to User. As there's a db constraint on the foreign key field, it raises the error. Solution is easy, just add owner to the list of fields in the form or modify the save method to assign an owner to the note. If you'll use the first option, the user will be able to see and select the owner. And if you want to pre-populate that particular field, pass initial value to the form.

Thank you for posting . I think that is one of the most stupid thing in Django framework.This totally crazy. I log on as UserA , i go to create a new note and i need to decide which user in creating this post.So i will see thousands of username in the list. Have you where seen that in any website? Of course you need to note to be auto-populated by the user that is logged in.This all happens cause in django there is sessions for user.

I read the documentation but i dint understand.Can you help me . Something like that ? owner = NoteForm(initial={'username': 'instance'}, auto_id=False) in model Note ?

You only want to pre-populate username? Have a look FormView. It has a function get_initial() which is used by Form to get initial values for fields. It returns a dictionary. In that dict, add {'username': self.request.user.username} and your form will be initialized with the required username.

python - Django Admin class to auto-populate user field - Stack Overfl...

python django admin auto-populate
Rectangle 27 0

Edit: After looking on the full error message I can see the error is not solely related to extending User. The error happens when rendering checkboxes and corresponding labels that are used to assign prints to UserProfile you are editing/adding. Django admin is calling Print.__unicode__ for rendering label for each Print instance, which in turn access (on line 33 of /threedee/website/models.py) the Print's "printer" attribute which is a foreign key to User. And for some reason one of the Prints does have invalid printer value which doesn't point to any User.

Can't really tell what is really happening here without seeing the Print model, I recommend you checking the Print database table (should be named website_print) and find if there is anything unusual (are you using PostgreSQL?). If you are not having any important data there, truncating whole Print table should do the trick.

I would just comment on others answers but there doesn't seem to be a way of doing that for me. You need to combine both Alexey Sidorov's and Like it's answers:

First use django shell to create UserProfile instances for existing users - just run commads provided by Like it's answer in the shell (python manage.py shell).

You will be able to comment once you have enough "reputation points".

Thanks for that. I've just done those things and still get the same error message: dpaste.com/815515 - not sure what to try next.

Ok, I can see where is the problem probably, I've edited my aswer

Fantastic! I truncated the table website_print because there was only a bit of data there anyway. Thanks v. much.

Django: Issues with extending User model - Stack Overflow

django django-models django-admin
Rectangle 27 0

The way you have designed there is no direct way to access it. As its one-to-many type of relation.

though you can loop on result.driver_set.all and that will give you access to driver object access and you can fetch user_id access.

{% for result in result_list %}
            <li>
            {% if result %}
                <a href="/rides/ridedetails/{{ result.pk }}">{{ result.type }}</a>
                <em>{{ result.ride_comment }}</em>
                {% for item in result.driver_set.all %}
                  {{item.user_id}}
                {% endfor %}
             {% endif %}
            </li>
        {% endfor %}

Hi I have tried the above code, I can get the username of the User object using this 'item.user_id'. But How can I access other User attributes like email. I have tried like 'item.user_id.email', but that is not working

I got it :) item.user_id.email gives the email, Earlier I dont have any value in the email field, so I got empty and thought the code is not worked. Thanks

python - Accessing Foreign Key values from a foreign key referenced mo...

python django django-models django-views
Rectangle 27 0

Driver is actually the through table of a many-to-many relationship between Ride and User. You should make that explicit, by declaring a ManyToManyField on Ride:

users = models.ManyToManyField(User, through=Driver)

Now you can access that relationship more directly in the template:

{% for result in result_list %}
  ...
  {% for user in result.users.all %}
    {{ user.username }}
  {% endif %}

Although I'd repeat what other comments have said: your relationship seems backwards, in that surely a ride should only have a single driver.

python - Accessing Foreign Key values from a foreign key referenced mo...

python django django-models django-views
Rectangle 27 0

Rating.filter(company__in=[company_a, company_b]).distinct()
IndicatorRatingOptions.filter(company__in=[company_a, company_b]).distinct()

Cool. I kinda threw it together off the top of my head. I knew the distinct() was the key part. I've edited my original answer to show what you've discovered.

python - In Django I have a complex query where I need only the unique...

python django django-models
Rectangle 27 0

Your model is broken. The way you have it, an Image can have multiple Blogs but a Blog can only have one Image. You want it the other way round, so the ForeignKey should be defined on the Blog model, pointing to Image. Then your template will work as it is.

One further note: please don't get all Blogs and then call reversed on them. That's horribly inefficient. Instead, get the db to return them in reverse order:

Blog.objects.all().reverse()

Even better, define a creation time field on the model and order by that.

python - How do I access a value from a foreign key in Django template...

python django django-models django-templates foreign-keys
Rectangle 27 0

This will do what you want. Basically it checks if the form is being rendered on an existing ModelA object and then if it is, it changes the queryset for the ModelB field to filter all active ModelB objects plus the one that is currently assigned.

class ModelAAdminForm(forms.ModelForm):
    class Meta:
        model = ModelA

    def __init__(self, *args, **kwargs):
        super(ModelAAdminForm, self).__init__(*args, **kwargs)
        if self.instance.id and self.instance.modelb:
            q = Q(active=True)| Q(id=self.instance.modelb.id)
            self.fields['modelb'].queryset = ModelB.objects.filter(q)
        else:
            self.fields['modelb'].queryset = ModelB.objects.filter(active=True)


class ModelAAdmin(admin.ModelAdmin):
    form = ModelAAdminForm

How to limit choices in a foreign key in Django but always include cur...

django django-models django-forms django-admin
Rectangle 27 0

The images field in your Blog model has a ForeignKey relationship with Image but you are treating it as a ManyToMany relationship (judging by the {% with blog.images_set.all ... %} in your template).

Depending on how you are modelling the relationship, you can either change the images field from:

images = models.ForeignKey('myapp.Image')
images = models.ManyToManyField('myapp.Image')

migrate your database and then you can use

{% with blog.images.all ... %}

in your template. This would indicate that a blog can have multiple images and an image can belong to multiple blogs. Alternatively you can move the relationship to the Image model:

class Image(models.Model):
     ...
     blog = models.ForeignKey(Blog)

and use:

{% with blog.image_set.all ... %}

in your template (see reversing the relationships in the docs). This would indicate that a blog can have multiple images, but an image only every belongs to one blog post.

python - How do I access a value from a foreign key in Django template...

python django django-models django-templates foreign-keys
Rectangle 27 0

I wouldn't advice to use a CharField to store Foreign Key id's. It will prevent you from using standard SQL queries for simple operations, thus will prevent you from using the related features in the Django ORM.

It's usually best to give your database a logical structure and not make structure sacrifices for the performance. There are many other ways to improve performance, like indexing and caching. If you do it like that it will give you the most flexibility for the future.

django - Is it good practice to save multiple Foreign Keys into CharFi...

django django-models django-queryset
Rectangle 27 0

From what I see, your model looks just fine. The error is funny; it is saying that the key to the attribute you are calling as "title" cannot be anything other than a string, but if I'm not mistaken, the string here is the key "title" and the value is the CharField() field, together representing a key/value pair in the Post document in your MongoDB. Try isolating the problem by jumping into the django shell:

python manage.py shell

and building your Post object from scratch. Use the model that dragonx has mentioned. Simple is best to debug these problems. If you are getting the same error when you try either to call Post.objects.create(p) for a Post object p, or when you call p.save(), try re-writing the Post model and give it another shot.

Finally, you can show us your settings.py file and see what your mongodb settings are there. If you say you are using django-nonrel, then there are basic checks you can make to ensure that python, django, and mongodb are talking to each other.

python - Why do I get an InvalidDocument exception when saving an obje...

python django mongodb django-nonrel
Rectangle 27 0

If you only need images to be read-only, you can do this using a nested serializer. If it has to be writable, you may have some issues as nested serializers have problems with writing in DRF < 3.0, especially in many-to-many cases like this.

You would have to write a serializer for images, similar to this:

class MovieImageSerializer(serializers.ModelSerializer):
    img_link = serializers.URLField()
    img_describe = serializers.CharField()

    class Meta:
        model = MovieImage
        fields = ('img_link', 'img_describe', )

and add it to your current serializer as a replacement for the field, similar to this:

class MovieSerializer(serializers.ModelSerializer):     
    images = MovieImageSerializer(many=True, read_only=True, source='movieimage_set')

    class Meta:
        model = Movie
        fields = ('link', 'title', 'images')
{
    "link": "https://test.com/id=1", 
    "title": "TEST", 
    "images": [
        {
            "img_describe": "the value",
            "img_link": "a link"
        }
    ]
}

You can find more information on nested relationships in the Django REST Framework documentation.

python - how to get the value in the Foreign key in django restframewo...

python django django-rest-framework
Rectangle 27 0

This will do what you want. Basically it checks if the form is being rendered on an existing ModelA object and then if it is, it changes the queryset for the ModelB field to filter all active ModelB objects plus the one that is currently assigned.

class ModelAAdminForm(forms.ModelForm):
    class Meta:
        model = ModelA

    def __init__(self, *args, **kwargs):
        super(ModelAAdminForm, self).__init__(*args, **kwargs)
        if self.instance.id and self.instance.modelb:
            q = Q(active=True)| Q(id=self.instance.modelb.id)
            self.fields['modelb'].queryset = ModelB.objects.filter(q)
        else:
            self.fields['modelb'].queryset = ModelB.objects.filter(active=True)


class ModelAAdmin(admin.ModelAdmin):
    form = ModelAAdminForm

How to limit choices in a foreign key in Django but always include cur...

django django-models django-forms django-admin
Rectangle 27 0

I encountered this error because I was passing extra arguments to the save method in the wrong way.

instance_name.save(..., force_update=True)

If you get an error that you cannot pass force_insert and force_update at the same time, you're probably passing some custom arguments the wrong way, like I did.

This a nice solution within django. From the shell just import your model class (if you aren't using shell_plus) and then do MyModelClass.objects.first().save(force_update=True)

postgresql - IntegrityError duplicate key value violates unique constr...

django postgresql duplicates unique-constraint database-integrity