Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Compare Foreign Key Value to Attribute of another Model
I'm still relatively new to Django, but I decided to try to build a personal portfolio of personal projects I've worked on. I've set it up so that you land on the home page. From there, you can click on a language. Then if I've used a framework for that language, I want to display it to the screen or if I have a project I did not using a framework in that language, it would be displayed here as well. To do this, I've set up a foreign key from frameworks to languages and from JobNoFramework to Language. I have put in a framework object for Django to test it. If I change the comparison operator to !=, it displays, but as soon as I make it == it doesn't work, even though if I say {{frameworks.language}} - {{languages.language}} I get Python - Python. I'd really appreciate any help. Here's the relevant code: Models: from django.db import models from datetime import date # Create your models here. class Language(models.Model): language = models.CharField(max_length = 30) image = models.ImageField(upload_to='images/') def __str__(self): return self.language class Framework(models.Model): framework = models.CharField(max_length = 30) language = models.ForeignKey(Language, on_delete=models.CASCADE) def __str__(self): return self.framework class JobNoFramework(models.Model): job … -
Make User Profile Visible to All Users Include AnonyMouseUser() on Django
I'm trying to create UserProfileView with user's username in the url. Actually, it works somehow with the actual settings. The issue is, any username extension in the url redirects to the logged in user's profile. And, no info comes to the template when I try to go to profile without signing in. Here's my code, any help is appreciated. models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) email = models.EmailField(max_length=150) bio = models.TextField(max_length=280, blank=True) avatar = models.ImageField(default='default.jpg', upload_to='avatars/') def __str__(self): return '@{}'.format(self.user.username) def save(self): super().save() img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size, Image.BICUBIC) img.save(self.avatar.path) views.py class UserProfileView(SelectRelatedMixin, TemplateView): model = Profile template_name = 'accounts/profile.html' select_related = ('user',) def get_context_data(self, *args): context = super().get_context_data(*args) profile = Profile.objects.filter(user=self.kwargs) context['profile'] = profile return context def get_success_url(self): return reverse('accounts:profile', kwargs={'username': self.object.user.user.username}) urls.py urlpatterns = [ path('<str:username>/', views.UserProfileView.as_view(), name='profile') ] profile.html (how I call the related data in the template) <h3>{{ user.profile }}</h3> <p>{{ user.profile.email }}</p> <p>{{ user.profile.bio }}</p> <h3>{{ profile }}</h3> -
writing data from parent model to another database with django routers
I have models, for example ParentModel and ChildModel where ParentModel is a parent to a child model and those models belong to different apps, for example pm_app and c_app: #pm_app class ParentModel(model.Model): #some fields #c_app class ChildModel(ParentModel): #some other fields and I have django routers in my project. class ParentModel: def db_for_write(self, model, **hints): # some options return 'default' class ChildModel: def db_for_write(self, model, **hints): # some options return 'other_db' When ChildModel is filled with some data so does the ParentModel, but router doesn't work at that moment, default db stays empty, the entry appears in the 'other_db'. So is there a way to resolve this issue? I didn't add the code from the actual project, because I think it is unnecessarily complicated. -
Defining custom signup for django-allauth
I have been trying to user a custom signup form in django-allauth. However, I get the error: django.core.exceptions.ImproperlyConfigured: Module "main.forms" does not define a "SocialAccountSignupForm" class Below is my custom social account form: from allauth.account.forms import SignupForm class SocialAccountSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(SocialAccountSignupForm, self).__init__(*args, **kwargs) def clean(self): email = self.cleaned_data.get("email") username = self.cleaned_data.get("username") if Profile.objects.filter(email=email).exists(): if Profile.objects.filter(email=email, is_active=False).exists(): p = Profile.objects.filter(email=email, is_active=False).delete() elif Profile.objects.filter(email=email, is_active=True).exists(): raise forms.ValidationError("A user with this email already exists.") if Profile.objects.filter(username=username).exists(): if Profile.objects.filter(username=username, is_active=False).exists(): p = Profile.objects.filter(username=username, is_active=False).delete() elif Profile.objects.filter(username=username, is_active=True).exists(): raise forms.ValidationError("A user with this username already exists.") super(SocialAccountSignupForm, self).clean() return self.cleaned_data And in my settings file I have: ACCOUNT_SIGNUP_FORM_CLASS = 'main.forms.SocialAccountSignupForm' I do not understand why this is causing me this error as the class is inside my main/forms.py file. -
Django POST save and delete
I'm attempting to save records into a model using the modelform (this part is working as intended) and delete records from the same model using a checkbox (can't figure this piece out). I am creating a comprehensive view so I'm not creating using a def variable(reqeust, id) function and my intention is to have both POST methods redirect back to the same page. How would I go about deleting a model record using a checkbox and POST? I will add an @login_required decorator later. Here is my code: models.py: class ReportDirectory(models.Model): report_name = models.CharField(max_length=300, unique=True, blank=False) report_desc = models.TextField() report_type = models.CharField(max_length=300) report_loc = models.TextField() slug = models.SlugField(unique=True, max_length=300) last_update = models.DateTimeField(null=True) main_tags = models.CharField(max_length=300) # Renames the item in the admin folder def __str__(self): return self.report_name class Favorite(models.Model): directory_user = models.ForeignKey(User, on_delete=models.CASCADE) user_report = models.ForeignKey(ReportDirectory, on_delete=models.CASCADE) favorited = models.BooleanField() def __str__(self): return str(self.directory_user)+" - "+str(self.user_report) views.py: from django.shortcuts import render,redirect from django.views import generic from .models import ReportDirectory, Favorite from django.contrib.auth.models import User from .forms import FavoriteForm def report_directory(request): favorite = Favorite.objects.filter(directory_user=request.user.id, favorited=True) reports = ReportDirectory.objects.exclude(favorite__directory_user=request.user.id, favorite__favorited=True) favform = FavoriteForm(initial={'directory_user':request.user,},) context = { 'reports':reports, 'favorite':favorite, 'favform':favform } if request.method =='POST' and 'favorited' in request.POST: form = FavoriteForm(request.POST) if form.is_valid(): … -
IntegrityError at /posts/12/new-comment/ NOT NULL constraint failed: posts_comment.author_id
Well i am adding commenting system in my project but got an integrity error. I dont know how to solve this. I have already asked this question one time but now one answer it. But now i am asking it again i hope someone will answer it with brief detail. I shall be very thankful to you. view.py class CommentCreateView(CreateView): redirect_field_name='posts/post_detail.html' model = Comment form_class = CommentForm template_name = "posts/snippets/comment_form.html" def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post,related_name='comments', on_delete=models.CASCADE) body = models.TextField() create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username def get_absolute_url(self): return reverse("posts:post_detail", kwargs={"pk": self.pk}) traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/posts/12/new-comment/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: posts_comment.author_id) was the direct cause of the following exception: File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File … -
Heroku Django Admin returns 'FileNotFoundError at /admin/projects/project/add/'?
I am trying to setup a Django admin page to be able to update my project portfolio directly. Everything works fine until I click on the 'add project' button. Then I'm hit with an error: I do not understand what it is looking for. Any insight would be helpful as I've tried searching google/stack and haven't found a similar issue with a solution. If you need more information, let me know and I'll update my question. -
Django-channels Is it possible to send a message and wait for a response?
There is a very handy way to send a message and wait for a backward message in django-channels testing module: from channels.testing import WebsocketCommunicator communicator = WebsocketCommunicator(app, url) connected, subprotocol = await communicator.connect() await communicator.send_json_to(data=my_data) resp = await communicator.receive_json_from(timeout=my_timeout) Is it possible to write code of real consumer in same style? I mean something like that: class MyConsumer(AsyncJsonWebsocketConsumer): async def some_method(): await self.send_json(some_json) response = await self.receive_json(timeout=some_timeout) # do something with response -
TypeError: 'module' object is not iterable errors occurs when I create my first Django apps
During creating my first apps in Django named 'main' but it gives an error provides below. I check all of the previous answers but not capable to solve my problems. Can anyone help me to solve the issue? Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Saidul\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I create my views … -
Incompatible foreign key when attempting to link tables in Django?
I am trying to make a couple basic models, and link them together with a foreign key. First tool class tool1(models.Model): tool_id = models.CharField( max_length=100, primary_key=True, verbose_name="Tool", ) description = models.CharField( default="", max_length=100, verbose_name="Description", help_text="Describe tool here", ) dateOfAdd = models.DateField( default=datetime.today, verbose_name="Date" ) Referencing tool class Tool2(models.Model): tool1 = models.ForeignKey( Tool, default=None, on_delete=models.PROTECT blank=True ) For some reason the other tools I reference work, but this one will not. I get the following error: django.db.utils.OperationalError: (3780, "Referencing column 'tool1' and referenced column 'tool_id' in foreign key constraint [FK Name] are incompatible.") I cannot figure out why this is happening because the referencing tool is successfully referencing multiple other tools, but it will not link to this one. What is the reason for this error? And how can I fix it so that I can link the tables? -
When running my docker image for my Django project I'm getting a "ModuleNotFoundError: No module named 'try_django'" error
So long story short, I'm trying to use docker to take my Django project to production through Heroku. This is my first ever Django project, first time using Docker as well. Currently I'm getting an error when I try to run my image, this is my first attempt at testing that it runs just fine. I did check that it would run with gunicorn before I put it into the docker image. That worked just fine, although my website didn't look like what it was supposed to, but that's the whole point of docker right? As of right now my website looks just fine with the classic: (try_django) bash-3.2$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2020 - 18:31:48 Django version 2.2, using settings 'try_django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Now I'm just trying to get this project deployed. I can see that the image is created just fine: simple-dj-docker latest 11554361b373 17 minutes ago 1.24GB My next step is to run: docker run -it -p 80:8888 simple-dj-docker In return I get: [2020-10-15 18:13:15 +0000] [6] [INFO] Starting gunicorn 20.0.4 [2020-10-15 … -
How to make my admin_order_pdf function better
I have this function to have a pdf file with orders details but it is not showing all details required in template so I am trying to write the admin_order_pdf function in a better way as it is not generating the full context of the order context. I am not sure whether converting it to a class based view will make it better and even how to do that. Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing----------------> <<-------------------------From here nothing is showing--------------------------> {% for order_item in order.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td> {{ order_item.item.title }}</td> <td> {% if order_item.item.discount_price %} <del>${{ order_item.item.price }}</del> {{ order_item.item.discount_price }} {% else %} ${{ order_item.item.price }} {% endif %} </td> <td>{{ order_item.quantity }}</td> <td>{% if order_item.variation.all %} {% for variation in order_item.variation.all %} {{ variation.title|capfirst }} {% endfor %} … -
__str__ returned non-string (type Product)
I'm getting __ str __ returned non-string (type Product) when I try to add OrderItem in my Django project models.py: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date_ordered = models.DateField(auto_now_add=True, blank=True, null=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return self.transaction_id class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return self.product class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() image = models.ImageField(null=True, blank=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.name) @property def imageUrl(self): try: url = self.image.url except: url ='' return url admin.py: admin.site.register(Customer) admin.site.register(Product) admin.site.register(Order) admin.site.register(Tag) admin.site.register(OrderItem) I get the same error when I try this: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() image = models.ImageField(null=True, blank=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return 'test' Sometimes I get this error when I try to add/delete items (in Orders, OrderItems, Products) -
Django F Date Expresion generated from static field
I am trying to get a series of ages from a persons list, but the age generated change with each query because is the age in a specific event so i can accomplish this with a simple loop, extracting the timedelta from the diference: [ (event_date - user.birth_date).days/365.25 for user in User.objects.all() ] event_date is always a datatime.date object anr user.birth_date too. I consider it a "Static" field or constant because it is outside the database. This gives me the correct results, but since I am doing this many times and i have other calculations to do I wanted to generate the ages from the database using the F() expresion. ``from django.db.models import ExpressionWrapper, fields diference = ExpressionWrapper( event_date- F('birth_date'), output_field=fields.DurationField()) qs_ages= self.annotate(age_dist=diference) this should give me a field named age_dist that will be a timedelta contains the total days between the two dates, so now I should do this and should give me the same result as above. [ user.age_dist.days/365.25 for user in User.objects.all() ] But this does not work, the result is a time delta of microseconds What i am doing wrong? and how should I include the static value of event_date to the expression? And... going beyond. … -
How to filter and get an "object" instead of a "quesryset" in Django Rest Framework
I am trying to filter the users by passing the email_id through URL by passing email_id and getting that particular user. I tried doing this using django-filters but I got a queryset with one object inside it but instead I need the object itself. here's the model - class User(models.Model): """This is the Users model where all users data will be saved""" first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_id = models.EmailField(max_length=100, default="") city = models.CharField(max_length=20, blank=True) state = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=20, blank=True) zip_code = models.CharField(max_length=6, blank=True) mobile_number = models.CharField(max_length=10, blank=True) birthdate = models.DateField(blank=True, null=True) photo_url = models.URLField(max_length=255, blank=True) gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, related_name='user_gender') joined = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.first_name + ' ' + self.last_name I tried using this viewset but it gives me a queryset instead of an object and I coudn't put my mind around on it. class UserFilter(filters.FilterSet): class Meta: model = User fields = { 'email_id': ['iexact'] } class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [DjangoFilterBackend] filterset_class = UserFilter This is the url I am currently passing - http://127.0.0.1:8000/api/v1/users/?email_id__iexact=somemail@gmail.com -
How best to store predictions from machine learning model in Django?
I know Django is well suited for deploying a machine learning model. But all of the tutorials on deploying a machine learning model do not use the standard Django models. When we need to get a prediction, we simply refer to the model as if it were a function, and then we pass the data to the client as a json file. I am satisfied with this option for providing data, if not for a few shortcomings. I will list them below. Let's say that I want to provide the user with filtering data by some parameter. Django provides a model-based filtering mechanism only (tell me if it doesn't). I have no idea how I can filter out a json response that doesn't use serializers and models. My site page should display 200 predictions. These predictions must change every day, but during the day they are unchanged (they depend on today's date). How good is it for performance if every user GET request to that page leads to the machine learning model algorithm being called 200 times? Is there some kind of solution that will allow me to solve these two problems? -
In a Django Rest Framework APIView, using nested serializers for grouping, how can I get only the results that meet all filter criteria?
I have a model of Documents, a model of Authors and a model of Groups. A document must belong to an author and also to a group. So the document model has foreign key constraints to the other two tables. Document model class Document(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='documents') group = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=240, unique=True) description = models.TextField(max_length=999, blank=True) body = models.TextField() active = models.BooleanField(default=True) publication_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Author Model class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=60, unique=True) description = models.TextField(max_length=999, blank=True) Group Model class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=60, unique=True) description = models.CharField(max_length=240, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Then I have my serializers: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = "__all__" read_only_fields = ['user'] def create(self, validated_data): author = Author.objects.create(user=self.context['request'].user, **validated_data) return author class DocumentSerializer(serializers.ModelSerializer): active = serializers.BooleanField(initial=True) author_name = serializers.StringRelatedField(read_only=True, source='author') class Meta: model = Document fields = "__all__" And of course DocumentsByAuthorSerializer which groups Documents by Authors: class DocumentsByAuthorSerializer(serializers.ModelSerializer): documents = DocumentSerializer(many=True, read_only=True) class Meta: model = Author fields = ['id','name', 'documents'] read_only_fields = ['user'] def create(self, validated_data): author = Author.objects.create(user=self.context['request'].user, **validated_data) return author Finally, I have my view … -
Django checkbox for filter
Im having some problem when I want to keep a checkbox checked. When I send the form all the checkbox are checked. so idk how to change the if statement for that :( <div class="form-group"> <label >Marca</label> {% for brand in q %} <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="{{brand.brand}}" name="test" value="{{brand.brand}}" {% if marca %} checked="checked" {%endif%}> <label class="custom-control-label" for="{{brand.brand}}" style="cursor: pointer;">{{brand.brand}}</label> </div> {% endfor %} </div> And here is the view: marca = request.GET.get('test') if marca : products = products.filter(brand__name__in=request.GET.getlist('test')) All the other things are fine. It shows me the brands that I choose. So I just want to keep the checkbox that I checked :( and I think the problem is that If statement in the template -
Uploading image in Django returns error "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte"
So I have a nested serializer and I'm trying to upload an image, the image there but when I try to set it to use it on the serializer I'm getting the error. My code: models.py class Pet(models.Model): pet_id = models.UUIDField('pet uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) name = models.CharField('Pet name', max_length=255, null=False, blank=False) class Attachment(models.Model): attachment_id = models.UUIDField('attachment uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) pet_id = models.ForeignKey(Pet, on_delete=models.CASCADE) name = models.FileField(upload_to='photos/', null=False, blank=False) upload_at = models.DateTimeField('Time it was uploaded', max_length=50, null=False, blank=False ) serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = ('name','upload_at') class PetSerializer(serializers.ModelSerializer): attachments = AttachmentSerializer(many=True) class Meta: model = Pet fields = ('pet_id','name', 'attachments') def create(self, validated_data): attachments = validated_data.pop('attachments') pet = Pet.objects.create(**validated_data) for att in attachments: Attachment.objects.create(pet_id=pet, **att) return pet views.py parser_classes = (MultiPartParser, FormParser) def create_pet(self, request): img = BytesIO(request.FILES.get('file_1').read()) img.seek(0) data = Image.open(img) new_data = request.data.copy() new_data['attachments'] = [{'name':data, 'upload_at':datetime.now()}] serializer = self.get_serializer(data=new_data) if not serializer.is_valid(): return Response({'error':serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response({'data':serializer.validated_data}, status=status.HTTP_201_CREATED) but I'm getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Any thoughts about this? Thanks in advance. -
concatenating string variables to obtain value
How would I concatenate these two string variables in Django templates? At the moment question.correct_answer is the position the correct answer should be (so if there were 4 potential answers and the first answer was correct, question.correct_answer would return 1 instead of the value the answer holds. I have tried the below code, but it shows a string of 'question.answer_1' <h5 class="homework_desc"> {{ question.answer_4 }}</h5> <br> <h4 class="homework_correct hidden" id="{{question.id}}"> {{'question.answer_'|add:question.correct_answer}} </h4> -
What code should we write in "Templates" to display "zhanr" (in Post model)?
I want create a blog application and write in "templates/blog/detail.html": <a href='#'>{{ post.zhanr.genre }}</a> but it doesn't show in browser, i don't know why. you sure about "Mozu in model", I added information about "genre" in database. my model: in Post model i use ManyToManyField for Mozu model from django.db import models class Mozu(models.Model): genre = models.CharField(max_length=250, help_text='نوشتن موضوع') def __str__(self): return self.genre class Aks(models.Model): img = models.ImageField() class Post(models.Model): title = models.CharField(max_length=250) zhanr = models.ManyToManyField(Mozu, help_text='موضوع انتخب کنید') image = models.ManyToManyField(Aks ,null=True, blank= True) video = models.FileField(null=True, blank= True) desc = models.TextField() date = models.DateTimeField() how_time = models.IntegerField(null=True, blank= True) def __str__(self): return '{}-{}'.format(self.title, self.date) my view: i want using Zanr in detail.html from django.shortcuts import render, get_object_or_404 from .models import * from django.views import generic from django.contrib.auth.decorators import login_required, user_passes_test class IndexView(generic.ListView): template_name = 'blog/index.html' context_object_name = 'posts' def get_queryset(self): return Post.objects.all().order_by('date') class DetailView(generic.DetailView): model = Post template_name = 'blog/detail.html' -
django form queryset for image URL
I have a form that links an image model to another model. I'm trying to preview the images in the form, not like the default dropdowns menu, but I'm struggling with the image URL. I tried image.urlbut it's not working my models.py class Images(models.Model): image = models.ImageField(unique=False,upload_to='images/') def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':pk}) #connect days and images together class DayImage(models.Model): date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE) images = models.ForeignKey('luach.Images',related_name='images',on_delete=models.CASCADE) def get_absolute_url(self): return reverse("dayimage_detail",kwargs={'pk':self.pk}) my forms.py class DayImageForm(forms.ModelForm): class Meta: model = DayImage fields = ('images',) my views.py def create_day_image_view(request,pk): date = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': form = DayImageForm(request.POST) if form.is_valid(): dayimage = form.save(commit=False) dayimage.date = date dayimage.save() return redirect('date_detail',pk=date.pk) else: form = DayImageForm() context = {'form': form,'date': date,} return render(request,'luach/dayimage_form.html',context=context) my dayimage_form.html <form method="POST"> {% csrf_token %} <select class="image-picker"> {% for image in form.images %} <option data-img-src="{{image.value.images.image.url}}" value="{{forloop.counter}}">{{image.label}}</option> {% endfor %} </select> <button type='submit' class='btn btn-success'>save</button> <a class="btn btn-danger" href="{% url 'date_detail' pk=date.pk %}">cancel</a> </form> -
Model inheritance many to one, and return view to template
Struggling again. I would like to apply model inheritance to a template. I have 2 models. Customerprofile and Customerquote. I would like the customerquote to inherit the data records from customerprofile. The model has done this in the backend setup as the models below. The issue is I have 3 seperate fields in the customerquote template for title, firstname and surname with fields. Title, firstname and surname. I would like that I setup a dropdown in the customerquote that when I select firstname all the firstname records appear in the dropdown, when I select the firstname option, Surname and title fields are automatically populated based on inheritance of customerquote and the associated record linked to address 1, is this possible. I have included the template setup below, which in it's basic form is not working even for firstname, before looking at the next steps/ Please see curent setup, is their a way that I can do this and save to new model customerquote, the new instance? Create your models here. class Customerprofile(models.Model): Title = models.CharField(max_length=5, blank=True) Firstname = models.CharField(max_length=100, blank=True) Surname = models.CharField(max_length=100, blank=True) Mobile = models.CharField(max_length=11, validators=[int_list_validator(sep=''), default='12345678901') Email = models.EmailField(max_length=100, blank=True) Datecreated = models.DateField(default=now) Profilefield = models.IntegerField(default="12345678", blank=True) … -
Django rest Framework - Custom Json Response
i'm new into Python and Django Rest Framework. I'm trying to return a "custom" json response but i can't figure it out how to achieve the result i want. I'm building an Ecommerce api where i have "boxes" with "products", this BoxProduct model was created because i need a relation between Products and Boxes, but the same product can be in different boxes, ex: Product.id=1 is in box_id=2 and box_id=4. That's why i created this middle model. BoxProduct Model class BoxProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING, null=True, related_name='box_product') box = models.ForeignKey(Box, on_delete=models.DO_NOTHING, null=True, related_name='box_box') product_price = models.DecimalField(max_digits=8, decimal_places=0, null=True, blank=True) I tried to link the serializers of Product and Box but i didn't get wat i want. BoxProduct Serializer class BoxProductSerializer(serializers.ModelSerializer): product = ProductSerializer(many=True, read_only=True) box = BoxSerializer() class Meta: model = BoxProduct fields=['box', 'product'] The idea is to have a returned json like this: { "box_id": 232323, "box_name": "Box name Test", "products": [ { "name": "product name 1", "type": "product_type" }, { "name": "product name 2", "type": "product_type" }, { "name": "product name 3", "type": "product_type" } ] } What would be the best approach to do this? Thanks for your help! -
hi i am getting "CSRF Failed and CSRF cookie not set." error
{"detail": "CSRF Failed: CSRF cookie not set."} error in postman , i am using django rest_framework for developing ios android backend . when i first time clear all cookies and use my login api is working fine this will give me all info about user as per my code but after that when i try to hit any api using post method its always give crsf failed. i also use csrf_exempt decorator in view and urls.py and also tried CsrfExemptMixin from brace package. my login code is from django.contrib.auth import login,logout from django.shortcuts import render,redirect # local py files from .models import * from .serializers import * from app_apis.models import * # third party from rest_framework import (generics, permissions) from knox.views import LoginView as KnoxLoginView from rest_framework.response import Response from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.models import AuthToken from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from braces.views import CsrfExemptMixin from django.middleware.csrf import get_token # Register API class RegisterView(CsrfExemptMixin,generics.GenericAPIView): serializer_class=RegisterUserSerializer @method_decorator(csrf_exempt) def post(self,request,*args, **kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() print logout(request) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(CsrfExemptMixin,KnoxLoginView): permission_classes = (permissions.AllowAny,) def get(self,request): example={ "username":"user_name", "password":"Your Password" } return Response(example) @method_decorator(csrf_exempt) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) …