Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Secure Third Party API data using Django?
I'm using a third party API Key for my website. I have done some modification on that API and now I'm using it for my own site. I want to secure that API data by adding a restriction on any user (Authenticated or Anonymous ). I want to add a time limit on the data provided by the API. So, if anybody uses the same data after a certain period of time then it will show an error. As well as I want some restrictions on users IP. So, a user can access my website a fixed number of time. -
How to make true query in django_elasticsearch_dsl like icontains in django?
Need using django_elasticsearch_dsl search by given text. It should works as for full word and for only part of world. Like for "Example" and "xample". Using python 3.6, django_elasticsearch_dsl 7.0 Have found in documentation that django "icontains" query is similar to "match_phrase" in elasticsearch_dsl.query, but seems it does not work for me. titles = TitleDocument.search().query( Q("match", title=kwargs['text']) or Q("match", slug=kwargs['text']) or Q("match", page_title=kwargs['text']) or Q("match_phrase", menu_title=kwargs['text']) or Q("match_phrase", meta_description=kwargs['text']) ) Does not work for part of word (ex. "neve", full is "never") But Django query works good ti = Title.objects.filter(meta_description__icontains=kwargs['text']) Use only one field to filter by just for example I expect to find something looks like django icontains filter. Need to find not only for full word match. -
Error when handling multiple forms in the same View
I'm trying to create a view that handles two forms with models related by a ForeignKey. The purpose of this form is to add a Bedroom and the Lights related to that Bedroom on the same page. #views.py def add_bedroom(request, pk): get_property_id = pk data = {'property':get_property_id} property_reference = Property.objects.get(pk=get_property_id) if request.method == 'POST': bedroom_form = AddBedroomForm(request.POST, request.FILES, initial=data) lighting_form = LightingBedroomAddForm(request.POST) if bedroom_form.is_valid() and lighting_form.is_valid(): bedroom = bedroom_form.save() add_lighting = lighting_form.save(commit=False) add_lighting.bedroom = bedroom add_lighting.save() return HttpResponseRedirect(reverse('properties:property_detail', args=[pk])) else: print('Error') bedroom_form = AddBedroomForm(initial=data) lighting_form = LightingBedroomAddForm() context = { 'add_bedroom_form':bedroom_form, 'add_lighting_form':lighting_form, 'title':"Add Bedroom", 'reference':property_reference, } return render(request, 'properties/add-bedroom.html', context) For some reason it doesn't work and my guess is that when I assign this add_lighting.bedroom = bedroomit doesn't get the id value. I get the POST printed but it just reloads the page(I don't have validation errors). What am I doing wrong here? I've checked this Link1 and this Link2 #models.py class Bedroom(models.Model): type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50) bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30) image = models.ImageField(null=True, blank=True) ensuite = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom') def __str__(self): return str(self.pk) class LightingBedroom(models.Model): type = models.CharField(db_column='Type', choices=LIGHTING_TYPE_CHOICES, max_length=30) bulb_type … -
how to check if a user is logged in when using third party login system?
I have a web app which is based on django (version 2.0+), the user can only login with third party authentication. My question is like, can I still use the technique like: "if request.user.is_authenticated():" (https://stackoverflow.com/questions/3644902/how-to-check-if-a-user-is-logged-in-how-to-properly-use-user-is-authenticated) to see if user is logged in? Some background: After third party login, user profile is available. At the moment the structure of the database is still at design phase. -
Calculating income and expenses per month
Hello developers How to calculate income with date .For example income of last month income of last year and income of this month. models.py class Add(models.Model): income = models.IntegerField(blank=True, null=True) expense = models.IntegerField(default=0) date = models.DateTimeField(default=timezone.now, null=True, blank=True) -
Django Query for two related models
I have an Order model that is related to Booking model as ForeignKey field. So, an Order can be related to multiple Booking objects. class Order(models.Model): shop=models.ForeignKey(Shop, on_delete=models.CASCADE, blank=True, null=True) user=models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, blank=True, null=True) order_id=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4) order_date=models.DateField(default=date.today) class Booking(models.Model): order=models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True) service=models.ForeignKey(Service, on_delete=models.CASCADE, blank=True, null = True) My goal is to show Order with the related Booking objects like this: <ul> {% for order in orders %} <li>{{ order.order_id }}</li> <ul> {% for booking in BOOKINGS WITH THIS ORDER ID %} <li>{{ booking.service }}</li> {% endfor %} </ul> {% endfor %} </ul> In the template, with in each order, I want to be able to loop through bookings with that order id. I am having trouble figuring out how to make the proper query to achieve that in the template. I thought about creating a dictionary object to store and pass the related booking object details, but this does not seem to be the proper way to do this. def shopDashboardPastBookings(request): orders = Order.objects.filter(shop_id = shopID ).exclude(order_date__gte = (datetime.now() - timedelta(days=1)) ) bookings = {} for order in orders: booking_query = Booking.filter(order = order ) bookings[order.order_id] = booking_query // should I be making separate queries for … -
How to receive user input from FilteredSelectMultiple widget?
I am trying to create form using FilteredSelectMultiple widget. I managed to get it showing on my page, but faced difficulties receiving user input from it. For now, after I click submit button page just refresh and shows same form again instead of going to designated page. What I am doing wrong? My code so far: forms.py class DrgSkaiciuokle(forms.Form): drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(), label="Pasirinkite atvejį sudarančius DRG", widget=FilteredSelectMultiple("DRG kodai", is_stacked=False), required=True) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) #I have no idea if this part is right: def clean_drg_pasirinkimas(self): drg_pasirinkimas = self.cleaned_data['drg_pasirinkimas'] return drg_pasirinkimas views.py def DRG_skaiciuokle(request): if request.method == 'POST': form = DrgSkaiciuokle(request.POST) pasirinkti_DRG = form.cleaned_data['drg_pasirinkimas'] context = { 'pasirinktiDRG': pasirinktiDRG, } #This page should be opened after submitting form instead of refresh return render(request, 'DRGskaiciuokle_valid.html', context) else: form = DrgSkaiciuokle() context = { 'form': form, } return render(request, 'DRGskaiciuokle.html', context) my html file: {% extends "base_generic.html" %} {% block content %} <div id='frame'> <div id='sk_head'> <h3>Kaštų konvertavimo skaičiuoklė</h3> <h4>Pagal DRG metodiką</h4> </div> <form> <div id='sk_body'> <fieldset> <legend>Įveskite duomenis</legend> <form action="" method="post"> {% csrf_token %} <table> {{ form.media }} {{ form.as_table }} <script type="text/javascript" src="{% url 'jsi18n' %}"></script> </table> <input type="submit" value="Skaičiuoti"> </form> </fieldset> </div> </form> … -
Invalidating cached AJAX response when session changes
Server-side, Django is caching a certain view we always load with AJAX, based on whether the user role changes, which is passed through headers. Using Vary headers for this: url(pattern, cache_page(CACHE_TIMEOUT)(vary_on_headers('USER_ROLE')(MyView.as_view())), name='myview') Here's how the header is sent: $.ajax({ url: url, cache: true, beforeSend: request => request.setRequestHeader('User-Role', document.USER_ROLE), success: response => loadView(response) }); Where document.USER_ROLE is set in a relevant place on page load and its values are different strings based on whether the user is logged in or not, and on their role. Then, as you can see, client-side we are also caching the response. This means if the user logs in or logs out they will get a non-pertinent cached version of the view. Therefore I need some way to invalidate the client cache, that is, to pass cache: false if the user role changes. I have thought of using a cookie: // get current user role on page load before making the ajax request // compare role to the last, stored in a cookie, and if changed, disable caching document.USER_ROLE = '{{ user.role_str }}'; document.SHOULD_CACHE_VIEW = true; const lastUserRole = Cookie.get('lastuserrole'); if (document.USER_ROLE !== lastUserRole) { Cookies.set('lastuserrole', document.USER_ROLE); document.SHOULD_CACHE_VIEW = false; } And then we can use … -
Django Form is not valid but not giving me an error
In the below form If I uncomment "Product" field my form is not working.I think there is something wrong with my html file. I am not including whole model code only the neccessary code. lead/models.py class Lead(models.Model): address_line = models.CharField(_("Address"), max_length=255, blank=True, null=True) street = models.CharField(_("Street"), max_length=55, blank=True, null=True) city = models.CharField(_("City"), max_length=255, blank=True, null=True) state = models.CharField(_("State"), max_length=255, blank=True, null=True) postcode = models.CharField(_("Post/Zip-code"), max_length=64, blank=True, null=True) country = models.CharField(max_length=3, choices=COUNTRIES, blank=True, null=True) website = models.CharField(_("Website"), max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) assigned_to = models.ManyToManyField(User, related_name='lead_assigned_users') account_name = models.CharField(max_length=255, null=True, blank=True) tags = models.ManyToManyField(Tags, blank=True) contacts = models.ManyToManyField(Contact, related_name="lead_contacts") ctype = models.CharField(default=None,max_length=20, choices=TYPE, blank=True, null=True) product = models.CharField(default=None,max_length=255, blank=False, null=True) common/models.py class Products(models.Model): name = models.CharField(max_length=50,null=False,blank=False) def __str__(self): return self.name lead/view.py @login_required def create_lead(request): template_name = "create_lead.html" users = [] if request.user.role == 'ADMIN' or request.user.is_superuser: users = User.objects.filter(is_active=True).order_by('email') elif request.user.google.all(): users = [] else: users = User.objects.filter(role='ADMIN').order_by('email') form = LeadForm(assigned_to=users) if request.POST: form = LeadForm(request.POST, request.FILES, assigned_to=users) if form.is_valid(): lead_obj = form.save(commit=False) lead_obj.created_by = request.user lead_obj.save() if request.POST.get('tags', ''): tags = request.POST.get("tags") splitted_tags = tags.split(",") for t in splitted_tags: tag = Tags.objects.filter(name=t) if tag: tag = tag[0] else: tag = Tags.objects.create(name=t) lead_obj.tags.add(tag) if request.POST.getlist('assigned_to', []): lead_obj.assigned_to.add(*request.POST.getlist('assigned_to')) assigned_to_list = … -
find and quickly solve the production problem
usually in code without putting in production each time verifies that it works well. but at the time of production in heroku we always have an error if we write heroku logs --tail we always have the same static files but usually it's a library not well installed but use. generally to find the error one checks requirements.txt and the documentation and the code there is not a faster method -
Custom registration form. Confirm password
I used custom form for register users. I want do validation for confirm password. forms.py: class RegistrationForm(UserCreationForm): '''Register for new users''' email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = get_user_model() fields = {'username', 'password1', 'password2', 'email', 'first_name', 'last_name'} def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user template: <div class="input-group register"> {{ form.password.errors }} <label for="id_password1">Password: </label> {{ form.password1 }} </div> <div class="input-group register"> {{ form.password.errors }} <label for="id_password2">Confirm password: </label> {{ form.password2 }} </div> views.py def registration_view(request): context = {} context.update(csrf(request)) context['form'] = RegistrationForm() if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() newuser = auth.authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password2'] ) auth.login(request, newuser) return redirect('home') else: context['form'] = form return render(request, '/registration.html', context) How can I add validation for password(also confirm password)? -
upload base64 video file using django
I have a user model that i want to add a video field to it, i used Base64ImageField to upload the image for the user and PDFBase64File for the files implementing Base64FileField, so i want VIDEOBASE64File validator for the video to accept video types like mp4, ...etc class PDFBase64File(Base64FileField): ALLOWED_TYPES = ['pdf'] def get_file_extension(self, filename, decoded_file): try: PyPDF2.PdfFileReader(io.BytesIO(decoded_file)) except PyPDF2.utils.PdfReadError as e: return 'non-valid' return 'pdf' I want a validator for the video to accept certain extension of videos. -
Django - how to redirect the first logged in user to a loading page
Definition of The first logged in user: the first one to authenticate, meaning no one else in that moment is logged in except him. This django webapp needs to rely on a third parties rest api (Microsoft powerbi), which get paid per minute, but it also provide the possibility to turn on and off the server programmatically with a rest api call to azure. The most obvious way to turn on and off the server, it seems to be to react at the first login and the last logout. The issue here, is that the server needs about 30 seconds to start. And I need to redirect the user to a "loading" page, and when server is up, i would redirect him again to the home page. currently, I detect the first login with a receiver, in my views.py I have: @receiver(user_logged_in) def sig_user_logged_in(sender, user, request, **kwargs): print("user logged in: %s at %s" % (user, request.META['REMOTE_ADDR'])) queryset = get_current_users() if queryset.count() == 0: headers_capacity = azure_auth_capacity() print("resuming capacity...") resume_pbi_capacity(headers_capacity) print("redirecting to loading page...") # Both following tries to redirect does not work #return '/loading/' #return render_to_response("loading.html") Here I would redirect the user to a loading page as you see, since … -
How can I have the fields for each language shown using Django Forms and django-modeltranslation?
I have a Model with fields available in English and another language e.g. title and title_langcode. I have a Django Form that allows users to edit the fields of a model, based upon the TranslationModelForm from django-modeltranslation. The user needs to be able to enter details for the field in both languages, so there is a Textbox for title and title_langcode. At the moment, only title is appearing as that is all that is present in Fields. How can I let the user edit both language fields in the same form? -
Function to copy fields from a model to another model in django
I want to merge 2 different models with different but overlapping fields. I try to write a function that copy the fields with its data from model A to model B. def create_field(): old = DetailItem.objects.all() new = CrawlItem.objects.all() for item in old: c = CrawlItem.objects.get(title=item.title, description=item.description, link=item.link, cpvcode=item.cpvcode, postalcode=item.postalcode ) c.save() and i don't know whereis the mistake. I want to have a model that contains the data from the old model and some new fields. Here is my code for the two models: class DetailItem(Base): title = models.CharField(max_length=500) description = models.CharField(max_length=20000) link = models.URLField() cpvcode = models.ManyToManyField('CPVCode',related_name='cpv') postalcode = models.ForeignKey('PostalCode',on_delete=models.SET_NULL,null=True,blank=True,related_name='postal') def __str__(self): return self.title class CrawlItem(Base): guid = models.CharField( primary_key=True, max_length=500) title = models.CharField(max_length=500) link = models.URLField() description = models.CharField(max_length=2000) pubdate = models.DateTimeField() detail = models.ForeignKey('DetailItem',on_delete=models.SET_NULL,null=True,blank=True,related_name='crawldetail') def __str__(self): return str(self.title) This is what I want to get: class CrawlItem(Base): guid = ... title = ... link = ... cpvcodes = ... postalcode = ... pubdate = ... vergabestelle = ... vergabeart = ... anmeldefrist = ... description = ... Any ideas how to get there are highly appreciated! -
Django : the database needs something to populate existing row
models . py : class Equipe(models.Model): NomEquipe = models.CharField(max_length=10,unique=True) Description = models.CharField(max_length=10,unique=True) class planning (models.Model): datedebut= models.DateField datefin=models.DateField nbrH=models.TimeField class Conseiller(models.Model): Matricule = models.CharField(max_length=10,unique=True) Nom = models.CharField(max_length=200) Prenom = models.CharField(max_length=200) Tel = models.CharField(max_length=200) Mdp = models.CharField(max_length=200) Email = models.EmailField(max_length=200) File = models.CharField(max_length=200) Preavis = models.BooleanField(default=False) sup = models.CharField(max_length=200) Equipe = models.ForeignKey(Equipe, on_delete=models.CASCADE) planning = models.ForeignKey(planning , on_delete = models.CASCADE) WHEN I try to execute Manage.py makemigrations a have the errors and i need to fix this -
How to create a list of dictionaries from a dictionary with lists of different lengths
I want to create a list of dictionaries with the same index element from each list. I have a this dictionary: d = {'name': ['bob', 'john', 'harry', 'mary'], 'age': [13, 19, 23], 'height': [164, 188], 'job': ['programmer']} The desired output is: d2 = [{'name': 'bob', 'age': 13, 'height': 164, 'job': 'programmer'}, {'name': 'john', 'age': 19, 'height': 188}, {'name': 'harry', 'age': 23}, {'name': 'mary'}] I have tried something like this: d2 = [dict(zip(d, t)) for t in zip(*d.values())] But my output is: d2 = [{'name': 'bob', 'age': 13, 'height': 164, 'job': 'programmer'}] I think this is happening because the lists have different lengths -
What's an appropriate way to setup consumer driven contract testing for django api and react clients?
I just learned a new term called consumer driven contract testing. I was thinking maybe it can help me solve my problem with writing tests for a django api provider and react frontend architecture project. The frontend and the Django API backend are in separate repos and have their own unit tests. However, once in a while there will be error because the frontend is assuming some fields that are not returned by the Django service backend. I initially thought about writing end to end test, but they are slow to run and highly brittle. I found this consumer driven contract testing and it sounds like the right thing. But when i google around, i cannot find anything suitable. Even Pact seems to be solely for just converting the contract to consumer tests. What's a suitably easy way to have consumer driven contract testing for this scenario? -
I want to send an email at 11 am everyday
I want to send an email at 11 am everyday by using Python. But I do not know hot to send at 11 am everyday.Now,I can write a code to send an email. from django.core.mail import EmailMessage def send?email(self): email = EmailMessage(subject, message, None, email_to) email.send(fail_silently=False) I checked this document,but I could not find how to send an email at designated time. https://docs.python.org/3/library/email.message.html -
How do i correctly implement web scrapping into my api
I'm making a django api that is able to return a definition of a word to a user this word is looked up by using a word=(put word here) url, this api scrapes dictionary.com to get the definition if it does not already exist inside my database, than adds it to my database if it exists on their site. i'm just trying to figure out how to actually structure it correctly instead of just throwing it into my view. I want to be able to return json to the end user with suggestions if a word is not found in the database or on their websites by scrapping their recommendations. I have tried returning json responses inside the view if a 404 error happens. Always throws a error i'm under the assumption my whole structure is wrong. def get_queryset(self): word = self.kwargs['word'] headers = {"User-Agent": "user agent stuff"} if not Word.objects.filter(word=word).exists(): page = requests.get(f"https://www.dictionary.com/browse/{word}?s=t", headers=headers) soup = BeautifulSoup(page.content, 'html.parser') try: output = soup.find("div",{"value": "1"}).get_text() test = Word(word=self.kwargs['word'].strip(), meaning=output) test.save() except: return return Word.objects.all() i expect the user to be able to get a definition if the word exists or if it doesn't to be able to return recommendations that i … -
django api throwing 500(internal server) error with connection to mysql
I get 500(Internal Server Error) for the below code, cant able to identify the problem. Please help me urls.py from django.conf.urls import url from .audfile import daywisedetail,hourwisedetail urlpatterns = [ url(r'^pyapi/api/daywise/(?P<start_date>[\w-]+)/(?P<end_date>[\w-]+)/$',daywisedetail.as_view()), url(r'^pyapi/api/hourwise/(?P<start_date_val>[\w-]+)/(?P<end_date_val>[\w-]+)/$',hourwisedetail.as_view()), ] audfile.py from rest_framework.views import APIView from django.http import JsonResponse from django.http import HttpResponse from django.shortcuts import render from django.views.generic import View from django.template.loader import get_template from rest_framework.response import Response from rest_framework import status import MySQLdb sdatabase = MySQLdb.connect(host="localhost",user="root",passwd="password",db="main") class daywisedetail(APIView): def get(self,request,start_date=None,end_date=None,format=None): db = sdatabase cursor = db.cursor() daydetail = """select id, values, name, email from day_users where date(reg_date) between '%s' and '%s' """ % (start_date,end_date) cursor.execute(daydetail) getdaydetailresult = cursor.fetchall() mainlist=[] for v0 in getdaydetailresult: for v1 in v0: mainlist.append(v1) data = { "hours": mainlist } return Response(data) class hourwisedetail(APIView): def get(self,request,start_date_val=None,end_date_val=None,format=None): db = sdatabase cursor = db.cursor() hourwisedata = """select id, values, name, email from hour_users where date(reg_date) between '%s' and '%s' """ % (start_date_val,end_date_val) cursor.execute(hourwisedata) hourwisedataresult = cursor.fetchall() mainlist1=[] for v2 in hourwisedataresult: for v3 in v2: mainlist1.append(v3) data1 = { "days": mainlist1 } return Response(data1) If i have single class(daywisedetail), api is working properly, if i am adding second class(hourwisedetail), both the apis are showning 500 responce. cant able to find where is the … -
Check Django migrations status programmatically
I need to run an initial migration for a Django project without allowing system checks (because the error will be resolved by creating the models) Right now, I'm using a custom command like so: class Command(BaseCommand): help = "Init project by launching initial migration without system checks" requires_system_checks = False def handle(self, *args, **options): management.call_command("migrate", "app", "0001_initial") This command is run by the script that bootstrap the environment (with docker-compose) It runs really well the first time, as no migrations have been executed. If I restart it however, this custom command forces the project to revert migrations back to 0001_initial. Is there a clean way to check programmatically if a migration has been executed ? I think I could get some values from the django_migrations table, but I'd rather use something cleaner if it exists. Thanks for your help! -
How to make django site https in windows10
How to make django site https in windows10. I am using public IP not local host. I tried putting the following code in settings.py got from Error "You're accessing the development server over HTTPS, but it only supports HTTP" CORS_REPLACE_HTTPS_REFERER = False HOST_SCHEME = "http://" SECURE_PROXY_SSL_HEADER = None SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False SECURE_HSTS_SECONDS = None SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_FRAME_DENY = False I get the following error [09/Sep/2019 12:50:18] code 400, message Bad request version ('Gð\x1a\x15Ä«Öõß/\x02h|.\x9a\x11,\x93') [09/Sep/2019 12:50:18] You're accessing the development server over HTTPS, but it only supports HTTP. I even made DEBUG = False But no use still the same error. Now my issue is I am lost in trying to implement SSL in django on Windows 10 OS -
How to predict in multiple and simultanous Keras classifier sessions?
I know similar questions has been asked before and I have read all of them but none solved my problem. I have a Django project in which I am using CNNSequenceClassifier from sequence_classifiers which is a Keras model. The model files have been fit before and saved to particular destinations from which I again load them and predict what I want. clf = CNNSequenceClassifier(epochs=2) When I load the model I do this, due to the suggestions I found in searches, which is using the global model before loading the model, and then the other two lines: global clf clf = pickle.load(open(modelfilenameandpath, "rb")) global graph graph = tf.get_default_graph() and before predicting I use graph.as_default() with graph.as_default(): probs = clf.predict_proba(the_new_vecs) K.clear_session() I put K.clear_session() because I predict in a for loop and sometimes the next item of the for loop's prediction gets mixed up with the last one and raises tensorflow errors. But clearly K.clear_session() clears the session and makes it easy for the new item's prediction to work fine. The problem is in my views.py I have two functions which trigger prediction. And sometimes I need to use both simultanously. But since the probject is using Tensorflow Backend, only one session … -
I requested axios post form-data, but I got a 400 bad request response
I want to request to django by nuxt. I requested axios post form-data, and recieved 400 bad request response. I tried changing headers methods: { async submitPost() { this.post.userId = "1"; this.post.date = "123"; this.post.category = "1" const config = { headers: { "Content-Type": "multipart/form-data" } }; const formData = new FormData(); for (let data in this.post) { formData.append(data, this.post[data]); } try { for (var key of formData.entries()) { console.log(key[0] + ", " + key[1]); } let response = await this.$axios.$post("/posts/", formData, config); this.$router.push("/"); } catch (e) { console.log(e.response); } this.dialog = false; } }