Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Looks like your app is listening on 127.0.0.1. You may need to listen on 0.0.0.0 instead." Django project deployment to Railway app error
I want to deploy my Django project to the Railway app(deployment application). I have followed the instructions from this article but still I am getting this error "Looks like your app is listening on '127.0.0.1'.you may need to listen on '0.0.0.0' instead. " I don't know how to get rid of this error. Any help is accepted. -
Could not parse the remainder: '[i]' from 'l[i]' - Django
I am trying to use 'for i in r' as a way to simulate 'for i in range()' as shown in https://stackoverflow.com/a/1107777/14671034 . The r in my case is just a list of numbers from 0 to 10. 'l' is list of objects, here is .html file : {% for i in r %} {% for j in l[i] %} <tr> <td>{{j.a}}</td> <td>{{j.b}}</td> </tr> {% endfor %} {% endfor %} here is the part of views.py: am = [i for i in range(len(list_of_objs))] context = {'l': list_of_objs, 'r': am} everything worked just fine when i was passing list of object instead of list of numbers -
Install PGAdmin4 on Ubuntu
I'm from Iran and i need to install PGAdmin4 for my Ubuntu. To be honest i spent 12 hours time to install this application but after this i realized that the packets coming from server are disable due to internet restrictions from government. is there a way for me to install it ? the issue is raised when i trying to run this command : sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' the command line is waiting for receive a response but didn't get it. I installed Postgres but i can't install PGAdmin4. can anyone help me out ??? thanks a lot for your comments. I try to install PGAdmin4 but i couldn't do that. please help me... thanks -
save .xlsx file writen by pandas and export as a django model
I am going to have a web app that does some processing on user data and is going to give him/her back an excel file of processed data in Django. here is my app/views.py function: @login_required(login_url='/signin/') def processing(request): ... # read imported file (uploaded by user) and do the process. # finally have 3 uf, vf, wf array. ... # save the file in "excel_file = models.FileField" from pandas import DataFrame, ExcelWriter data = { 'uf': uf, 'vf': vf, 'wf': wf, } excel_data = DataFrame(excel_data) despiked = Despiking( #other models excel_file=excel_data.to_excel(???), ) despiked.save() return render(request, 'filteration/despiking.html', context=context) how can I save the excel_data into its model (excel_file) and create its media into Media directory? I already have read django pandas dataframe download as excel file question, but wasn't able to fix the problem with HttpResponse. any help would be greatly appreciated -
django mysql connection don't respect databases settings in settings.py
This is my database connection string in settings.py. DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "HOST": "127.0.0.1", "PORT": os.getenv("DB_PORT", '3306'), "NAME": os.getenv("DB_DATABASE", 'sm'), "USER": os.getenv("DB_USER", 'root'), "PASSWORD": os.getenv("DB_PASSWORD", ''), } } As above the host specified 127.0.0.1 but when I run python manage.py runserver database connection error with the wrong hostname. django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'172.18.0.1' (using password: NO)") As you can see I wrote hostname 127.0.0.1 but in the project, it is connecting 172.18.0.1 I really appreciate, it if someone gives me an answer to this issue. Thank you. -
How to add icons or emoji in django admin buttons
So I have some buttons in django admin and I need to add something like that: ⬅️➡️↩️↪️ to my admin buttons, but I have 0 idea how to do this and I feel like I am the first ever person to ask that question on the internet, google didnt help :)) Can you guys suggest something? Button for rotating photo in admin Tried to paste this ⬅️➡️↩️↪️ in the name of buttons, but it doesnt work like that xD -
How to set html attributes to Django form created using model
I have model class Listings(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField(max_length=180) desc = models.CharField(max_length=900) price = models.IntegerField(validators=[MinValueValidator(1)]) img = models.ImageField(upload_to='uploads') timestamp = models.DateTimeField(auto_now_add=True) And form class class ListingForm(ModelForm): class Meta: model = Listings fields = ('title', 'category', 'price', 'desc', 'img') labels = { 'desc': 'Description', 'img': 'Upload photo', 'price': 'Starting price' } I want to add HTML attributes like min="0" or remove required from my img = models.ImageField(upload_to='uploads') for example. How can I implement this? I found in stack overflow method with widgets = {'price': IntegerField(attrs='min': 0}) and I also tried ...forms.IntegerField... but I had TypeError: __init__() got an unexpected keyword argument 'attrs' And I also found solution with def __init__(self, *args, **kwargs): super(Listings, self).__init__(*args, **kwargs) self.fields['price'].widget.attrs.update({ 'min': 1 }) (I added it to my form class) But also did not work super(Listings, self).__init__(*args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type [05/Jan/2023 19:22:01] "GET /create_listing HTTP/1.1" 500 60691 -
Django compare two users of a model and if one is the current user return the other user
I have this really simple friendship model that just consists of two users. After all if user1 is friends with user2 then user2 is friends with user1 automatically. I would like to filter all the results by the current user and if a row contains the current user I would like to return the other user. So basically I want to return all records if the current user is either userone or usertwo and if the current user is usertwo swap the values so the current user is userone. Currently it works but only one way using the following model, serializer and view Model: class Friendship(models.Model): userone = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friendone" ) usertwo = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friendtwo" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ["userone", "usertwo"] def __str__(self): return "{} is friends with {}".format(self.userone, self.usertwo) def save(self, *args, **kwargs): if self.userone == self.usertwo: return "Same person friendship should happen mentally" else: super().save(*args, **kwargs) serializer: class FriendSerializer(serializers.ModelSerializer): profile2 = serializers.SerializerMethodField() class Meta: model = Friendship fields = [ "usertwo", "profile2" ] def get_profile2(self, obj): profile2_obj = Profile.objects.get(id=obj.usertwo.profile.id) profile2 = ProfileSerializer(profile2_obj) return profile2.data and view: class FriendList(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = … -
Why is django.conf.urls.static.static returning an empty list?
I'm trying to allow serving files from my media directory, but the media url isn't getting included... here's my code: from django.conf.urls.static import static urlpatterns = [ ... ] if settings.LOCALHOST_DEVELOPMENT: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) From a Django shell session: >>> from django.conf import settings >>> settings.LOCALHOST_DEVELOPMENT True >>> settings.MEDIA_URL '/media/' >>> settings.MEDIA_ROOT '/Users/[my username]/code/survey_server/media' >>> from survey_server import urls That last call return a list of urls without media url... >>> from django.conf.urls.static import static >>> static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) [] ... and it looks like the media url wasn't included because that static call is returning an empty list. Why is this empty? -
Combining serializers and sorting with filtering
I have a problem with the API JSON (serializers). I need to display only the last added price for a store and sort by lowest price for an article. There is no possibility to change the relationship in the database. DB schema looks like. DB Schema models.py from django.db import models class Shop(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.data() def data(self): return "{}".format(self.name) class Article(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.data() def data(self): return "{}".format(self.name) class Price(models.Model): article = models.ForeignKey(Article, on_delete=models.PROTECT, related_name='prices') shop = models.ForeignKey(Shop, on_delete=models.PROTECT, related_name='shops') name = models.CharField(max_length=100) date = models.DateField(null=True, blank=True) def __str__(self): return self.data() def data(self): return "{} {}".format(self.name, self.date) serializers.py from .models import Article, Price, Shop from rest_framework import serializers class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ['name', 'date'] class ShopSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True) class Meta: model = Shop fields = ['name', 'prices'] def to_representation(self, instance): bdata = super().to_representation(instance) bdata ["prices"] = sorted(bdata["prices"], key=lambda x: x["date"], reverse=False) return bdata class ArticleSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True) class Meta: model = Article fields = ['name', 'prices'] views.py from .models import Shop, Article, Price from rest_framework import viewsets, permissions, filters from apitest.serializers import ArticleSerializer, PriceSerializer, ShopSerializer #from rest_framework.response import Response #from django.db.models import Prefetch class … -
Saving to database an object after celery task is finished successful
I'm a newbie and need some help with saving some datas after a successful celery task, i have these models and serializers: texts/models.py class MyTexts(models.Model): TxTitle=models.CharField(max_length=300) TxText=models.TextField() TxAnnotatedText=models.TextField(blank=True) TxAudioURI=models.CharField(max_length=200, blank=True) TxSourceURI=models.CharField(max_length=1000,blank=True) TxTLang=models.ForeignKey(Language, related_name="TextLang",on_delete=models.CASCADE) TxtUser=models.ForeignKey(Learner, related_name="TextUser",on_delete=models.CASCADE) TxtTag=models.ForeignKey(to="tags.MyTags",on_delete=models.CASCADE,related_name="TextTags",blank=True,null=True) TxtArchived=models.BooleanField(default=False) TxtDifficulty=models.IntegerField() def __str__(self) -> str: return self.TxTitle Learner/models.py class Learner(AbstractUser): SelLanguage=models.OneToOneField(Language,on_delete=models.CASCADE,null=True,related_name="SelLanguage") is_teacher=models.BooleanField(default=False) can_post=models.BooleanField(default=False) level=models.IntegerField(default=0) def __str__(self) -> str: return self.username Learner/serializer.py from django.contrib.auth import authenticate, get_user_model from djoser.conf import settings from djoser.serializers import TokenCreateSerializer User = get_user_model() class CustomTokenCreateSerializer(TokenCreateSerializer): def validate(self, attrs): password = attrs.get("password") params = {settings.LOGIN_FIELD: attrs.get(settings.LOGIN_FIELD)} self.user = authenticate( request=self.context.get("request"), **params, password=password ) if not self.user: self.user = User.objects.filter(**params).first() if self.user and not self.user.check_password(password): self.fail("invalid_credentials") # We changed only below line if self.user: # and self.user.is_active: return attrs self.fail("invalid_credentials") language/models.py class Language(models.Model): LgName=models.CharField(max_length=40) LgDict1URI=models.CharField(max_length=200) LgDict2URI=models.CharField(max_length=200) LgGoogleTranslateURI=models.CharField(max_length=200) LgExportTemplate=models.CharField(max_length=1000) LgTextSize=models.IntegerField() LgRemoveSpaces=models.BooleanField() LgRightToLeft=models.BooleanField() LgSkills=models.TextField() def __str__(self) -> str: return self.LgName language/serializers.py class LanguageSerializer(serializers.ModelSerializer): class Meta: model=Language fields='__all__' tags/models.py class MyTags(models.Model): T2Text=models.CharField(max_length=30,blank=True) T2Comment=models.CharField(max_length=200,blank=True) TagsUser=models.ForeignKey(Learner, on_delete=models.CASCADE,related_name="MyTagsUser",blank=True) TagsText=models.ForeignKey(to="texts.MyTexts",on_delete=models.CASCADE,related_name="MyTagsText",blank=True) TagsLang=models.ForeignKey(Language,on_delete=models.CASCADE,related_name="MyagsLang",blank=True) TagsArchived=models.BooleanField(blank=True) tags/serializers.py class MyTags(models.Model): T2Text=models.CharField(max_length=30,blank=True) T2Comment=models.CharField(max_length=200,blank=True) TagsUser=models.ForeignKey(Learner, on_delete=models.CASCADE,related_name="MyTagsUser",blank=True) TagsText=models.ForeignKey(to="texts.MyTexts",on_delete=models.CASCADE,related_name="MyTagsText",blank=True) TagsLang=models.ForeignKey(Language,on_delete=models.CASCADE,related_name="MyagsLang",blank=True) TagsArchived=models.BooleanField(blank=True) and these two endpoints in texts/view.py: @api_view(['POST']) def match_patterns_request_view(request): username = request.data.get("username" ) document = request.data.get("document") language = request.data.get("language") user=Learner.objects.get(username=username) priority=user.level task = match_patterns.apply_async(args=(username,document,language),priority=priority) return Response(status=status.HTTP_200_OK, data={"id":task.id}) @api_view(['GET']) def match_patterns_result_view(request, task_id): task_result = AsyncResult(task_id) # Check … -
how to pass `request` info to Django form Widget
I am trying to pass a filter queryset for a Django form widget. Normally, I would do something like # views.py class MyView(SuccessMessageMixin, CreateView): model = MyModel form_class = MyCreateForm template_name = 'create.html' success_message = "You new object has been created." success_url = reverse_lazy('mymodel-index') # forms.py class MyCreateForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'title', 'car', # etc ] widgets = { 'car': forms.widgets.Select( required=True, queryset=Car.objects.all(), # I need to filter this to the current user ), } However, I need to filter the queryset (in the car select Widget) to by the currently logged in user. I could try passing the user to __init__ from the View, but I don't know how to access that from the Meta subclass. Any pointers in the right direction would be appreciated. -
Postgres db index not being used on Heroku
I'm trying to debug a slow query for a model that looks like: class Employee(TimeStampMixin): title = models.TextField(blank=True,db_index=True) seniority = models.CharField(blank=True,max_length=128,db_index=True) The query is: Employee.objects.exclude(seniority='').filter(title__icontains=title).order_by('seniority').values_list('seniority') When I run an explain locally I get "Gather Merge (cost=1000.58..196218.23 rows=7 width=1)\n Workers Planned: 2\n -> Parallel Index Only Scan using companies_e_seniori_12ac68_idx on companies_employee (cost=0.56..195217.40 rows=3 width=1)\n Filter: (((seniority)::text <> ''::text) AND (upper(title) ~~ '%INFORMATION SPECIALIST%'::text))" however when I run the same code on Heroku I get costs of 1000x, seemingly because the former is using an index while the second is not: "Gather Merge (cost=216982.26..216982.90 rows=6 width=1)\n Workers Planned: 2\n -> Sort (cost=215982.26..215982.26 rows=3 width=1)\n Sort Key: seniority\n -> Parallel Seq Scan on companies_employee (cost=0.00..215982.25 rows=3 width=1)\n Filter: (((seniority)::text <> ''::text) AND (upper(title) ~~ '%INFORMATION SPECIALIST%'::text))\nJIT:\n Functions: 4\n Options: Inlining false, Optimization false, Expressions true, Deforming true" I confirmed the model indexes are identical for my local database and on Heroku, this is what they are: indexname | indexdef ----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------- companies_employee_pkey | CREATE UNIQUE INDEX companies_employee_pkey ON public.companies_employee USING btree (id) companies_employee_company_id_c24081a8 | CREATE INDEX companies_employee_company_id_c24081a8 ON public.companies_employee USING btree (company_id) companies_employee_person_id_936e5c6a | CREATE INDEX companies_employee_person_id_936e5c6a ON public.companies_employee USING btree (person_id) companies_employee_role_8772f722 | CREATE INDEX companies_employee_role_8772f722 ON public.companies_employee USING btree (role) companies_employee_role_8772f722_like | … -
Cannot assign "1": "Account.country" must be a "Country" instance
class MyAccountManager(BaseUserManager): ... class Country(models.Model): country_name = models.CharField(max_length=50) class Account(AbstractBaseUser): image = models.ImageField(upload_to='photos/profils/', default='media/photos/profils/constantly_img.jpg') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True) GENDER_CHOICES = [ ('MALE', 'Мужской'), ('FEMALE', 'Женской') ] gender = models.CharField(max_length=7, choices=GENDER_CHOICES) birthday = models.DateField() phone_num = models.CharField(max_length=50) password = models.CharField(max_length=50) country = models.ForeignKey(Country, on_delete=models.PROTECT) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_num', 'country'] When i am creating the superuser in terminal and if i want to populate the Account.country field by binding it to the Country model. I got an error. What am I doing wrong? -
Django Windows ./manage.py
I have saw a lot of posts regarding about how to do ./manage.py for windows and linux but i find the instructions unclear as a beginner. I have tried using "chmod +x manage.py" in my django project directory ("C:\Users\user\Django\Project") in windows command prompt and it does not work as it is not recognised by an internal or external command. So how would you do this in Windows? -
ValueError: Cannot assign "'1'": "Post.user" must be a "User" instance
I am doing a group project for a bootcamp and we just started Django for the back-end. We also are using React for front-end. Our project is basically a knockoff reddit. We have a User model: `from django.db import models class User(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.CharField(max_length=100, unique=True) username = models.CharField(max_length=32, unique=True) password = models.CharField(max_length=255) def __str__(self): return '%s' % (self.username)` and a Post model: `from django.db import models from auth_api.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=255) formBody = models.TextField(null=True, blank=True) imageURL = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True)` Our Post Serializers(pretty unfamiliar with this): `from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): user = serializers.CharField(required=True) class Meta: model = Post fields = ('id', 'user', 'title', 'formBody', 'imageURL', 'created',)` And our Post Views: `from django.shortcuts import render from rest_framework import generics from .serializers import PostSerializer from .models import Post from auth_api.models import User class PostList(generics.ListCreateAPIView): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer` The idea was when a user created a post their info would be saved with the post so that way when we display the post we could say who … -
Django website runs but none of the frontend shows
I am running my Django website using Amazon Linux EC2 instance. Everything runs correctly but for some reason, the actual front end of the website is not displayed. It even shows the title of the website in the search bar but can't display the actual content for me to interact with the website. It is just a white screen. Any help would be greatly appreciated. When I load the website, the GET requests display in my CLI: "GET / HTTP/1.1" 200 847, "GET /static/js/main.b1d3e335.js/ HTTP/1.1" 302 0, etc. I'm not sure what to try next. I used the collectstatic command for Django so I am thinking there may be a problem with the static files. But it is weird that my actual title of the website displays in the search bar but everything else is simply a white screen. -
Is it possible to include a view directly from the html?
I would like to know if it's possible, with Django, to include a view in another view like: Declare a view: def ads(request): param = ["first_ads_title"] return render(request, "blog/ads.html", context={"param": param}) With the following html : <div>ads {{ param[0] }}</div> And be able to call it from another html view like: <body> <h1>hello article {{ article }}</h1> {% include "blog/ads" %} </body> To display first_ads_title in my body ? -
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
I have been getting this error anytime i run my project with (runserver_plus --cert-file cert.crt)...I already installed the django extensions and pyOpenSSL I tried running without the (--cert-file cert.crt), that one seems to work fine buh doesnt provide me with what I am looking for . -
Is saving the user object to sessions safe to do when logging them in?
I am writing my own 2FA functionality (I know that django-otp and django-two-factor-auth exist, this is just for fun). Everything is fine except for the log in view. I know that you can use the following to authenticate the user: user = authenticate(request, username=cd['username'],password=cd['password']) login(request, user) What I want to do though is pass the user variable into the .view function that I will be using to do the 2FA on. That way, once the user enters their totp, I can use the already authenticated user as the user in the login function. Everything is fine other than on how to pass this data along. Is it safe security wise to pass the user along via sessions? I would do: request.session['authenticate_user'] = user And in the 2FA view put the following to retrieve the user: user = request.session.get('authenticate_user', None) I know that passing the password along is not safe, even if it is encrypted. Is the way I am proposing alright to do though? If not, what should you do instead? I have contemplated posting the password and user to the view using the requests module. Would this be security safe as an alternative, assuming it is not safe to … -
Merging Paginator and export html to xlsx and large amount of data
I'm trying to create a way to export the HTML table to xlsx, but I have a large amount of data in the queries. So I need to use pagination with Paginator so the browser doesn't load the data all at once and end up causing TimeOut. But when applying the Paginator and exporting, it only exports what is on the current page. Any suggestions to improve this code, such as creating a loop so that it can export all pages? View function: def export_project_data(request, pk): if str(request.user) != 'AnonymousUser': # só vai ter acesso se for diferente de AnonymousUser individuals_list = Individual.objects.filter(Project=pk) traps = Sample_unit_trap.objects.filter(Project=pk) page = request.GET.get('page', 1) paginator = Paginator(individuals_list, 1000) try: individuals = paginator.page(page) except PageNotAnInteger: individuals = paginator.page(1) except EmptyPage: individuals = paginator.page(paginator.num_pages) path_info = request.META['PATH_INFO'] context = { 'individuals': individuals, 'pk': pk, 'traps': traps, 'header': 'export_project_data', 'path_info': path_info } return render(request, 'inv/index.html', context) HTML paginator code: <div class="table-div"> {% if individuals.has_other_pages %} <ul class="pagination pagination-sm"> {% if individuals.has_previous %} <li><a href="?page={{ individuals.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in individuals.paginator.page_range %} {% if individuals.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ … -
Highcharts. Django won't load. Highcharts with Django
There is a wonderful library of js - Highcharts. I'm trying to link it to Django, and everything actually works, but not when I'm trying to insert a variable with content into data. Here's the code. This function returns what I substitute in data in Highcharts. def get_series(context): data_ser = [] for i in context: if i in ['One', "Two", "Three", "Four", "Five"]: data_ser.append({ 'name': i, 'y': context[i], 'z': 22.2 }) data_ser = json.dumps(data_ser) return data_ser And this is the jquery code itself <script> $(document).ready(function () { var data_ser = '{{ data_ser|safe }}' console.log(data_ser) Highcharts.chart('container', { chart: { type: 'variablepie' }, title: { text: 'Stats' }, series: [{ minPointSize: 10, innerSize: '20%', zMin: 0, name: 'countries', data: data_ser }] }); }) </script> In series in data, I try to substitute data_ser, but the graph is not output. Although, if you write it manually, then everything will work. Similar code works: `<script> $(document).ready(function () { var data_ser = '{{ data_ser|safe }}' console.log(data_ser) Highcharts.chart('container', { chart: { type: 'variablepie' }, title: { text: 'Stats' }, series: [{ minPointSize: 10, innerSize: '20%', zMin: 0, name: 'countries', data: [ { "name": "One", "y": 50.0, "z": 22.2 }] }] }); }) </script>` I really hope … -
I want to implement the dj-rest-auth Google OAuth feature, but I cannot understand where to get code to access google endpoints
I cannot understand where to get code or acsess_token to login user with google. I cannot find the endpoint to which I should send a request to get a code as a response. And I somewhat confused how to implement dg-rest-auth SocialAuth feature( I want my app to be able to login users with github, facebook and google). I have found these endpoint for Google OAuth2 https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://127.0.0.1:8001/ &prompt=consent&response_type=code&client_id=364189943403-pguvlcnjp1kd9p8s1n5kruhboa3sj8fq.apps.googleusercontent.com &scope=openid%20%20profile&access_type=offline Implicit Grant https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://127.0.0.1:8001/ &prompt=consent&response_type=code&client_id=364189943403-pguvlcnjp1kd9p8s1n5kruhboa3sj8fq.apps.googleusercontent.com &scope=openid%20%20profile Could you guys analyse my code and tell me what's wrong or what needs to be improved, please? And can you please provide me with a link to proper Google and Facebook Docs for OAuth2? settings.py Django settings for resume_website_restapi project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-b#t)ywiymb&@+mv^%j$p&4*y)iq2z-1da*z@beo4s-6-qu9ba%' # SECURITY WARNING: don't run with debug turned on … -
In django, how do you code this type of relationship model?
here's my code: from django.db import models class Parent(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.name) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.name) Parents in my database: Rogan Smith Doe In admin dashboard: First, I create a child that has a name of John and his parent is Smith.. it works! Now, after that, whenever I create a child that also has a name of John and this time with a parent of Doe or Rogan, it says: "Child with this Name already exists." here I tried searching on google but I can't seem to find the answer. Not a native english speaker here, please bare with me. -
Not able to Sumit data from Vue Js to Django Rest
I built a web app with Vue js and Django, django rest framework , I am only able to post data from the backend. When I try and fill in the data from the form with vue js nothing posts. here is my code hope someone smart can solve this. Thank you for your help it is appreciated. I followed the tutorial from: https://blog.logrocket.com/how-to-build-vue-js-app-django-rest-framework/ I attempted it twice there may be some code issues with her code. but I am open for anyone to help thank you. Tasks.vue <template> <div class="tasks_container"> <div class="add_task"> <form v-on:submit.prevent="submitForm"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" v-model="title" /> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" id="description" v-model="description" ></textarea> </div> <div class="form-group"> <button type="submit">Add Task</button> </div> </form> </div> <div class="tasks_content"> <h1>Tasks</h1> <ul class="tasks_list"> <li v-for="task in tasks" :key="task.id"> <h2>{{ task.title }}</h2> <p>{{ task.description }}</p> <button @click="toggleTask(task)"> {{ task.completed ? "Undo" : "Complete" }} </button> <button @click="deleteTask(task)">Delete</button> </li> </ul> </div> </div> </template> <script> export default { data() { return { tasks: [], title: "", description: "", }; }, methods: { async getData() { try { // fetch tasks const response = await this.$http.get( "http://localhost:8000/api/tasks/" ); // set the data returned as tasks this.tasks = response.data; …