Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access this touple value in Django template to display properly?
I want to display amount of expenses for each category in this table. But I don't know how to access this queryset value which represent the amount. VIEWS.PY CODE class CategoryListView(ListView): model = Category paginate_by = 5 def get_context_data(self, *, category_object_list=None, **kwargs): categories = Category.objects.annotate(Count('expense')) queryset = categories.values_list('name', 'expense__count') return super().get_context_data( category_object_list=queryset, **kwargs) TEMPLATE.HTML CODE <table border="1"> <thead> <tr> <th>category</th> <th>expenses</th> <th>actions</th> </tr> </thead> <tbody> </tbody> {% for category in object_list %} <tr> <td> {{ category.name|default:"-" }} </td> {% for number in category_object_list %} <td>{{ number }}</td> {% endfor %} <td> <a href="{% url 'expenses:category-update' category.id %}">edit</a> <a href="{% url 'expenses:category-delete' category.id %}">delete</a> </td> {% endfor %} </tr> I ended up on this terrible result and code... Does anyone what should I do know? What to change/add? Thank you in advance for any help! -
Django, def total summary line
This statement show client on each line with his total sales, i would like to add a summary line with the sum of all sales of all clients class statement(models.Model): client = models.ForeignKey('Client', on_delete=models.CASCADE) def sales(self): invoices = self.client.invoice_set.all() sales = 0 for invoice in invoices: sales += invoice.total_invoice() return round(sales, 2) -
Django custom Auth form. How to show error messages
Another Django form question -.- So, I have this form which works just fine, but it won't show any error messages. I'm pretty new to customising forms, so my question is that, do I need to specify anything else in order for my messages to show up? Forms.py file class UserLoginForm(AuthenticationForm): error_css_class = "error" def __init__(self,*args,**kwargs): super(UserLoginForm, self).__init__(*args,**kwargs) username = forms.CharField(widget=forms.TextInput( attrs={'class': 'input','placeholder': 'Username','label':''} )) password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'input','placeholder': 'Password','label':''} )) HTML File: {%block content%} <form class="form" method="POST"> {% csrf_token %} <fieldset class="form-group text-center text-uppercase"> <h1 class="sign-in__header">Sign up</h1> {% for field in form %} <p> {{ field }} {{ field.help_text }} </p> {% endfor %} </fieldset> <div class="form-group"> <button class="submit" type="submit">Sign in</button> </div> {% for field in form %} <div>{{ field.errors}}</div> {% endfor %} </div> </form> </div> {%endblock content%} -
can't change user avatar
In my app I allow users to have a profile avatar and I allow users to change their avatar from their profile. for the user profile answer the following view: class CustomerDetailUpdateView1(LoginRequiredMixin, UpdateView): model = User form_class = CustomerDetailUpdateForm1 template_name = 'customer/customer-profile1.html' def get_object(self): # print(forms.context_data) return self.request.user def get_success_url(self): return reverse("customer:customer-update") the code of form is: class CustomerDetailUpdateForm1(ModelForm): class Meta: model = User fields = ['email', 'full_name', 'avatar', 'country', 'city', 'address', 'phone_number' ] widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'full_name': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.TextInput(attrs={'class': 'form-control'}), 'city': forms.TextInput(attrs={'class': 'form-control'}), 'country': forms.Select(attrs={'class': 'form-control'}) } in template: <div> {{ form.as_p }} </div> everything works except when the user tries to change his avatr. error does not occur BUT the avatar does not change. can someone help me with the explanation what is the problem ??? -
Django channels get the current channel
I want to save messages to my database, but I want to divide them by channels, currently I load messages from other channels from the database, I am wondering how can I get something unique about a certain channel so I could have a field in my model named channel for that? -
How to get a Field inbetween a sentence? Using django/css for a survey
I basically have a simple question: I do a survey with django and use css/bootstrap. How do I get a text after my first CharField without creating another Fieldset? Basically, I want to have something like that: "I would pay ... for this." How to get the Field inbetween a sentence? Can I somehow use Div("Text") or something? Thanks a lot! Example how it looks now and should look class SurveyPolicy(forms.Form): policy6a = forms.CharField( # required=False, label='', widget = forms.Textarea(attrs={'rows':1}) ) policy6b = forms.IntegerField( # required=False, label='', widget=forms.NumberInput() ) def __init__(self, *args, **kwargs): super(SurveyPolicy, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'survey-form' self.helper.label_class = 'col-lg-12' self.helper.field_class = 'col-lg-12' self.helper.layout = Layout( Fieldset( "<hr><h5 style='color: #2D2D2D; text-align: center; font-family: Roboto;'>I would pay ...</h5>", Div('policy6a', css_class='form-group row-ml-0 mb-0'), Div('policy6b', css_class='form-group row-md-0 mb-0'), # css_class='row', ), -
How to make full text search in PostgreSQL to search any order of words in the input search_text and also if there are words between them
I'm trying to use Django full-text search but I'm having a problem: I've followed this documentation, and it works quite well. But my problem is that I don't want the postgress to consider the order or permutation of the words I search. I mean I want the result of searching "good boy" and "boy good" to be the same. and also when I search "good boy" I want to see the "good bad boy" in the results. But none of these happen and I can't query "good bad boy" with typing "boy good" or even "good boy" (Because of the "bad" missing). I've tried to split search_text by space and then & the search queries like this in order to remove the order of words but it didn't work. I changed this code: search_query = SearchQuery( search_text ) search_rank = SearchRank(search_vectors, search_query) to this: s = SearchQuery(search_text.split(' ')[0]) for x in search_text.split(' ')[1:]: s = s & SearchQuery(x) search_query = s search_rank = SearchRank(search_vectors, search_query) -
How do I know which Django function and arguments are being called on the click of a button?
I am looking at someone else's Django project and I am able to access the website they have created using their Docker set up. So in the Django project I can see a bunch of Python scripts that have a whole lot of different functions. What I need to find out is which function (and also what arguments are used for this function) is being used on the click of a button which submits the form. How do I do this? Considering the HTML of the button gives just this and no indication of what's actually happening when the button is clicked: <div class="mt-2 ml-3 mb-3"> <button name="submit" id="id_submit" class="btn btn-primary btn-sm"> Submit for Approval </button> <button name="save" id="id_save" class="btn btn-secondary btn-sm"> Save </button><h1></h1> </div> Where do I look to find the function and its arguments? I can make a good guess at which function it is just by the name of it but I would also like to know which argument values are used. How do I do this? -
Javascript not working when using built tags in Django
I'm learning django weeks from now, but I'm being curious why the function of my table search is not working well. When I search something on table search, the first row is gone. When the time I used this tags below to get all data from database the function did not work well.Without using loop below the function works fine but I need to attach in database it didn't work. Any idea why is this happening? thanks in advance. :) {% for item in user_information %} <tr> <td>{{item.first_name}}</td> </tr> {% endfor %} Views.py def new(request): if request.session.has_key('is_logged'): user = User.objects.all() return render(request, 'dash_new.html',{'user_information':user}) return redirect('/') table {% extends 'navigation.html' %} {% block content %} <table style="width: 100%;" id="example" class="table table-hover table-striped table-bordered"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> </tr> </thead> <tbody> {% for item in user_information %} <tr> <td>{{item.first_name}}</td> <td>{{item.last_name}}</td> <td>{{item.email}}</td> <td>{{item.username}}</td> <td>{{item.date_joined}}</td> </tr> </tbody> {% endfor %} <tbody> </tfoot> </table> {% endblock %} -
why the value in ManyToManyField doesn't change and keep the same in Django framework?
i want to change the value in the field manytomany to become unbook instead of book , and to store in database but instead it just redirect without change in the value i am new in Django i don't know where the problem but i think the problem in views.py in line 13 ,not sure but i think post_id not define in anywhere but here "post_id=post_id" the right one define it like this because of tutorial i see it , so i am not sure about it here is the code views.py def booking_system(request): user = request.user if request.method == 'POST': post_id_for = request.POST.get('post_id') post_obj = Medicine.objects.get(id=post_id_for) if user in post_obj.Booked.all(): post_obj.Booked.remove(user) else: post_obj.Booked.add(user) like, created = BookingSystem.objects.get_or_create(user=user, midicine_id=post_id_for) if not created: if like.value=='Book': like.value='UnBook' else: like.value='Book' post_obj.save() like.save() return redirect('medicine_1:all_medicine') models.py class Medicine(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) medicine_title = models.CharField(max_length=100) Booked = models.ManyToManyField(User, default=None, blank=True, related_name='Booked') @property def num_book(self): return self.Booked.all.count() def __str__(self): return self.medicine_title BOOK_CHOICES=( ('Book','Book'), ('UnBook','UnBook'), ) class BookingSystem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) value = models.CharField(choices=BOOK_CHOICES , default = 'Book', max_length = 8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.medicine}-{self.value} medicine.html {% if albums %} {% for album in … -
How pass queryset to djangofilter
in my django app i would pass a queryset where retrieve groups of the current user as filter. Now I did this code and it works as aspected. But in the searchbox in html i do not have filter class DatiBoeView(LoginRequiredMixin,SingleTableMixin,FilterView): queryset = DatiBoe.objects.all() model = queryset table_class = DatiBoeTable template_name = 'sito_boe/boefilt.html' filterset_class = filtroTableS form_class = DatiBoeForm paginate_by = 10 def get_queryset(self): #print(self.request.user) # print(self.request.user.groups.all()) itemset_queryset = Boe.objects.filter(id__in=self.request.user.groups.all()) queryset = DatiBoe.objects.filter(boa_id__in=itemset_queryset) return queryset If i don't put queryset = DatiBoe.objects.all() at start i receive error. How can pass my queryset from get_queryset function to filterset_class? -
Docker pull Django image and run container
So, I have followed this tutorial by Docker to create a Django image. It completely works on my local machine by just running a docker-compose up command from the root directory of my project. But, after pushing the image to docker hub https://hub.docker.com/repository/docker/vivanks/firsttry I am pulling the image to another machine and then running: docker run -p 8020:8020 vivanks/firsttry But it's not getting started and showing this error: EXITED(0) Can anyone help me on how to pull this image and run it? -
How to return a huge generated ZIP file in Django?
I would like to return a really big generated ZIP file in Django. The ZIP would include from 1000 to 5000 PDF files. These PDF files are stored on Amazon S3. I am using Heroku, and it has a 30 second timeout. So I can't get all the files and send a response in time. What I tried is generating the ZIP file, in the backend, where I don't have this timeout limit. But Heroku has a 1GB Memory limit. So i can't do that either. This is the code I used to perform this task: from zipfile import ZipFile def make_incoming_zip_file(): zip_obj = ZipFileIncomingInvoices.objects.get(zip_file="") invoices = get_invoices(year, quarter) with ZipFile("invoices.zip", "w") as zf: for idx, invoice in enumerate(invoices): file_path = "work_folder/incoming_invoice.pdf" with open(file_path , "wb") as f: f.write(invoice.invoice_file.read()) zf.write(filename=file_path , arcname=f"{idx+1} {invoice}.pdf") zip_obj.zip_file = File(open("invoices.zip", "rb")) zip_obj.save() What would be the best way to achieve this task? Thank you -
How to use the autocreated Django models.py from Database
I have a problem, I have a database with the following tables: Images(recipeID,image_url) Recipe(recipeID,recipe_title) Preperation(recipeID,preparation) Ingredients(ingredientID,recipeID,amount,unit,unit2,ingredient) I auto-created a models.py file with Django from the database with the following command: python manage.py inspectdb > models.py. In this file, he created all the models and three "strange" models: AllRecipesIngredient, AllRecipesRecipe, and AllRecipesRecipeIngredients. Now I want to know what they are and how I can use the recipes from one model or class like recipes.objects.all(), at the moment it would just give me the title or the preparation. I think the "strange" models he created are a part of what I need but I found no working solution so I hope you can help me. Here is the code: from django.db import models class Images(models.Model): rezept = models.ForeignKey('Rezepte', models.DO_NOTHING, db_column='Rezept_ID', blank=True, null=True) # Field name made lowercase. image_url = models.CharField(db_column='Image_URL', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Images' class Rezepte(models.Model): rezept_id = models.AutoField(db_column='Rezept_ID', primary_key=True, blank=True) # Field name made lowercase. rezept_title = models.CharField(db_column='Rezept_Title', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Rezepte' class Zubereitungen(models.Model): zubereitungs = models.OneToOneField(Rezepte, models.DO_NOTHING, db_column='Zubereitungs_ID', primary_key=True, blank=True) # Field name made lowercase. zubereitung = models.TextField(db_column='Zubereitung', … -
Can't access health check
I am currently working on a web app using Django. I used this app.yaml and it is deployed successfully on google app engine. However, I couldn't access /_hc, because Django checks whether the url is in url patterns and it just responds with 'Page not found'. How do I fix this? runtime: python37 entrypoint: bash -c 'gunicorn -b :$PORT projectservice.wsgi' liveness_check: path: "/_hc" check_interval_sec: 30 timeout_sec: 4 failure_threshold: 2 success_threshold: 2 handlers: # This configures Google App Engine to serve the files in the app's # static directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to the main app. # It is required when static routes are defined, but can be omitted # (along with the entire handlers section) when there are no static # files defined. - url: /.* script: auto # [END django_app] -
How to check if `MultiSelectField` is empty or not in Django?
In my model I have a field department which is a MultiSelectField and I give the blank=True to that field for some reasons. Now I want to check if user fills the field or not. I have tried to get data from request.POST and gave it a condition using len() function like this if len(field) == 0: but I got an error. Everything works just fine until I added teacher_year = request.POST['teacher_year'] models.py class CustomUser(AbstractUser): teacher_department = MultiSelectField(choices=department_choice, blank=True) forms.py class TeacherRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['teacher_year', ...] views.py def teacherRegisterView(request): form = TeacherRegisterForm() template_name = "attendance/login-register/teacher_register.html" if request.method == "POST": form = TeacherRegisterForm(request.POST) teacher_year = request.POST['teacher_year'] if len(teacher_year) == 0: messages.warning(request, "Just a remind! You didn't select deparment!") return redirect('teacher_register') elif form.is_valid(): form.save() messages.success(request, "Your account was created! You can log in now.") return redirect('/') return render(request, template_name, {'form': form}) the error I got django.utils.datastructures.MultiValueDictKeyError: 'teacher_year' -
displaying data from django model in template with celery
I am working on a django project. In the project, I am scraping some data from a website and storing the results into a django model. I want to now display this data in a django template as and when it is saved in the model. this is my code so far mainapp/views.py from django.shortcuts import render from .tasks import get_website from .models import Articles def index(request): if request.method == 'POST': website = request.POST.get('website') title = request.POST['title'] author = request.POST['author'] publish_date = request.POST['publish_date'] get_website.delay(website, title, author, publish_date) return render(request, 'output.html') return render(request, 'index.html') def output(request): return render(request, 'output.html') in the index page, I have a form which when submitted starts the scraping process through the celery task get_website(). mainapp/tasks.py @shared_task def get_website(website, title, author, publish_date): ... return save_function(article_list) @shared_task(serializer='json') def save_function(article_list): print('saving extracted data') new_count = 0 for article in article_list: try: new_article = Articles( Title = article['Title'], Link = article['Link'], Website = article['Website'], Author = article['Author'], Publish_date = article['Publish_date'], ) new_count += 1 new_article.save() except Exception as e: print(e) break return print('finished') All of the scraped data is stored in a list article_list and is passed to save_function() to save the data into the django model Articles. I want … -
Multi file upload in django
I want to upload multiple files through a form field. I tried many solutions including here on stackoverflow and medium.com This is my latest approach to tackle the problem. I have bank_statement field in my form for which I have to accept multi file upload option. I tried to override the POST method in order for bank_statement field to take multiple file upload using the multi_upload function in views.py as shown below. However, it still shows one upload button for the field when I open the page. What am I doing wrong and how do I fix it? models.py class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) status=models.CharField(max_length=254, choices=Status_Choices, default='Incomplete') first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) personal_photo=models.FileField(upload_to=content_file_name, default=None, blank=True) bank_statement=models.FileField(upload_to=content_file_name, default=None, null=True, blank=True) forms.py class RegForm(ModelForm): class Meta: model=Customer fields=['status','customerReg','first_name', 'last_name','personal_photo','bank_statement'] #readonly_fields=['status'] widgets={ 'status':forms.TextInput(attrs={'readonly':'readonly'}), 'bank_statement':ClearableFileInput(attrs={'multiple':True}), view.py def multi_form(request): #view for multi-form page form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): reg=form.save(commit=False) reg.customerReg=request.user reg.save() messages.success(request, "Your Response has been recorded") context={'form':form} return render(request, 'customer/success.html', context) else : return render(request, 'customer/index.html', {'form': form}) else: context = {'form': form} return render(request, 'customer/index.html', context) def multi_upload(request): if request.method == "POST": form=RegForm(request.POST, request.FILES) files=request.FILES.getlist('bank_statement') if form.is_valid(): for f in files: file_instance=Customer(bank_statement=f) file_instance.save() else: form=RegForm() return render(request, … -
Add additional information to request
I have an e-commerce website I'm working on, and I'd like it to be able to do something like this: class Shop(ListView): # Set the model as Product, the rest is handled by Django model = Product # Name of HTML File to show template_name = 'store/shop.html' # What to refer to in the HTML file (injection) context_object_name = 'products' # If the request.method is POST (a filter request) def post(self, request, *args, **kwargs): # Function from utils.py min_price, max_price, products = filter_shop(request) print(min_price, max_price) # Function from utils.py data = cartData(self.request) # Assigning keys to keys in context which can then be referenced in the html # Pass is in the completed query as a option, plus cartitems for the cart context_dict = {'products': products, 'cartitems': data['cartItems'], 'min_price': min_price, 'max_price': max_price, 'categories': category_choices()} return render(request, 'store/shop.html', context_dict) def get(self, request, *args, **kwargs): category = self.kwargs['category'] if category == 'custom': return super().get(request, *args, **kwargs) elif category == 'men': context_dict = {'men-coats': 'on'} request = request + context_dict return self.post(request, *args, **kwargs) What's happening is that the get request looks for something in the URL, and then needs to run the request as if it is a post request, I just … -
Django: How do I query posts for showing to users?
EXAMPLE to elaborate my problem -> I am a user named arthor and i have created many posts. when i go to the link https:example.com/posts/arthor then i want to see all my posts that i have created. similarly if another user name julia goes to https:example.com/posts/julia then she should see her posts that she created but if she goes to https:example.com/posts/arthor then she should see the arthor i.e my posts only. ISSUE i am facing -> i have created somewhat correct views but in the get_queryset i have postlist which takes myposts and filter them. In the filter at the place of uploaded_by i have given self.request.user.profile which gives the current user not the user of the link that i being entered in the url. such as if url https:example.com/posts/arthor is triggered then i want uploaded_by=arthor urls.py urlpatterns = [ path("posts/<str:username>", views.UserPostList.as_view(), name="posts"), ] models.py class MyPost(models.Model): pic = models.ImageField( upload_to="users/post_images/%y/%m/%d", null=True ) subject = models.CharField(max_length=200) message = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now=True) uploaded_by = models.ForeignKey(to=Profile, on_delete=CASCADE, null=True) def __str__(self): return "%s" % self.subject views.py class UserPostList(LoginRequiredMixin, SelectRelatedMixin, generic.ListView): login_url = "accounts:signin" raise_exception = False model = models.MyPost select_related = ('uploaded_by',) context_object_name = 'myposts' template_name = 'posts/user_post_list.html' def get_queryset(self): si … -
How to send multiple model from a classbased view in django
I made a booklist where cover image can be uploaded inside Booklist class. For more image I added another class called Bookcover. Now in Views.py how can I send both Booklist and Bookcover's by using BookListView models.py file is below from django.db import models from django.utils import timezone class Booklist(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length = 100) cover = models.ImageField(null=True, blank=True, default='default-book.jpg') description = models.TextField() date_posted = models.DateTimeField(default=timezone.now) price = models.DecimalField(decimal_places=3, max_digits=100) def __str__(self): return self.title class Bookcover(models.Model): post = models.ForeignKey(Booklist, default=None, on_delete=models.CASCADE) covers = models.ImageField(upload_to = 'images/') def __str__(self): return self.post.title here is views.py file from django.shortcuts import render from django.views.generic import ListView from .models import Booklist, Bookcover def home(request): return render(request, template_name='home/index.html') class BookListView(ListView): model = Booklist template_name = 'home/index.html' context_object_name = 'books' ordering = ['-date_posted'] -
Scrapy spider not working on Django after implementing WebSockets with Channels (cannot call it from an async context)
I'm opening a new question as I'm having an issue with Scrapy and Channels in a Django application. The reason why I'm using channels is because I want to retrieve in real-time the crawl statuses from Scrapyd API, without having to use setIntervals all the time, as this is supposed to become a SaaS service which could potentially be used by many users. I've implemented channels correctly, if I run: python manage.py runserver I can correctly see that the system is now using ASGI: System check identified no issues (0 silenced). September 01, 2020 - 15:12:33 Django version 3.0.7, using settings 'seotoolkit.settings' Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Also, the client and server connect correctly via the WebSocket: WebSocket HANDSHAKING /crawler/22/ [127.0.0.1:50264] connected {'type': 'websocket.connect'} WebSocket CONNECT /crawler/22/ [127.0.0.1:50264] So far so good, the problem comes when I run scrapy via the Scrapyd-API 2020-09-01 15:31:25 [scrapy.core.scraper] ERROR: Error processing {'url': 'https://www.example.com'} raceback (most recent call last): File "/Users/Andrea/anaconda3/envs/DjangoScrape/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/Users/Andrea/anaconda3/envs/DjangoScrape/lib/python3.6/site-packages/scrapy/utils/defer.py", line 157, in f return deferred_from_coro(coro_f(*coro_args, **coro_kwargs)) File "/private/var/folders/qz/ytk7wml54zd6rssxygt512hc0000gn/T/crawler-1597767314-spxv81dy.egg/webspider/pipelines.py", line 67, in process_item File "/Users/Andrea/anaconda3/envs/DjangoScrape/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File … -
Nested ManytoMany field not in the Response
I am trying to write a nested serializer which would add serialize 2 models in the same view. Serialization seems to work fine since changes get reflected in the database but I am not able to get the many-to-many related field data in the response. I have been trying to figure out what the issue might be but still no progress. Here is my code: Model class User(AbstractBaseUser): AccountName = models.ManyToManyField(Account, through='User_Account', through_fields=('user', 'acc'), related_name='AccountData', blank=True) EmailId = models.EmailField(max_length=128, blank=False, null=False) USERNAME_FIELD = 'EmailId' REQUIRED_FIELDS = ['AccountName'] class Account(models.Model): AccountName = models.TextField(max_length=100, blank=False, null=False) Serializer class AccountCreationSerializer(ModelSerializer): class Meta: model = Account fields = ["AccountName"] class SignUpSerializer1(ModelSerializer): AccountData = AccountCreationSerializer(read_only=True, many=True) class Meta: model = User fields = ['EmailId', 'AccountData', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def validate(self, attrs): attrs = super(SignUpSerializer1, self).validate(attrs=attrs) attrs.update({"AccountData": self.initial_data.get("AccountData")}) return attrs def create(self, validated_data): AccountName_data = validated_data.pop('AccountData') acc = Account.objects.create(AccountName=AccountName_data) userAcc = User.objects.create_user(**validated_data) if acc: userAcc.AccountName.add(acc) print("added") return userAcc View class SignUpView(APIView): serializer_class1 = SignUpSerializer1 def post(self, request, *args, **kwargs): if request.data['CreateAccount']: serializer = self.serializer_class1(data=request.data) is_valid_serializer = serializer.is_valid(raise_exception=True) if is_valid_serializer: with transaction.atomic(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: raise Exception("Bad error") Request1 "EmailId" : "xyz@gmail.com", "AccountData":{"AccountName":"TestAcc1"}, "CreateAccount": true, "password" … -
Django Rest Multiple Image Upload to React-Native
It is been three days and I couldn't manage to upload images. Looked over every possible post on the internet and couldn't find a solution. I would be appreciated if someone helps me. I am really stuck. I got errors for the many to many relationship fields below and Couldn't able to upload any images. KeyError: 'dopings' and 'photos' Here is my models def upload_location(instance, filename): return '/images/%s-%s' % (str(datetime.now()),instance.file) class Picture(models.Model): file = models.ImageField(upload_to=upload_location) slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.file.delete(True) super(Picture, self).delete(*args, **kwargs) class Dopings(models.Model): name = models.CharField(verbose_name="Doping Name",max_length=225) def __str__(self): return self.name class ListingDopings(models.Model): doping = models.ForeignKey(Dopings,on_delete=models.SET_NULL, verbose_name="Doping", null=True, blank=True) expire_date = models.DateField() class Listings(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='listing_user', null=True, blank=True) categoryName = models.ForeignKey(GameCategories,on_delete=models.SET_NULL, verbose_name="Category Name", null=True, blank=True) currency = models.ForeignKey(Currency,on_delete=models.SET_NULL, verbose_name="Currency", null=True, blank=True) price = models.IntegerField(default=0) date = models.DateField(auto_now=True) title = models.CharField(verbose_name="Title",max_length=225, null=True,blank=True) description = models.TextField(null=True,blank=True) slug = models.SlugField(max_length=555, blank=True) photos = models.ManyToManyField(Picture,blank=True) isActive = models.BooleanField(default=False) dopings = models.ManyToManyField(ListingDopings, blank=True) def __str__(self): return self.title My Serializers class ListingSerializer(serializers.ModelSerializer): photos = PictureSerializer(many=True, required=False, allow_null=True) dopings = DopingSerializer(many=True, required=False, allow_null=True) class Meta: model = Listings fields = ( 'id', 'categoryName', 'currency', … -
Export postgres table to yaml file
I am working in django and trying to figure out how to export a table i have in my database to a yaml file, but cant find the solution to it..probably some simple change.. Right now i have a written a bash to export my customer table to a CSV file that works fine: export_customer.sh echo "Enter the directory path to save the file" read path_to_save file_name="myFile.csv" psql --dbname=mydb --host=localhost --username=mydb -c "COPY ( select name, id from customers ) to stdout DELIMITER ',' CSV HEADER" > "${path_to_save}/${file_name}" My customer table look something like this: id name ------------------- 1 xxxxx 2 yyyyy Does anyone now how to export this into a yaml file instead?