Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set-Cookie is not working in Chrome and Dolphin - with two websites
Please see this question and answer from 8 months ago. The answer fixed the problem for a while, but today I discovered that login and logout works again separately for each of my websites (domains), in Chrome and in Dolphin. But, everything works as before in Firefox, Edge and Opera. Did something change in those browsers regarding cookies from other domain names and how do I fix it so that login and logout will work simultaneously in both websites? The users login or logout or sign up to one website, and I want them to login or logout from the other website too, automatically, and it works with Firefox, Edge and Opera. Currently if they login or logout to one website, it doesn't affect the other website (with Chrome or Dolphin). The Django view code is: @csrf_exempt def set_session(request): """ Cross-domain authentication. """ response = HttpResponse('') origin = request.META.get('HTTP_ORIGIN') if isinstance(origin, bytes): origin = origin.decode() netloc = urlparse(origin).netloc if isinstance(netloc, bytes): netloc = netloc.decode() valid_origin = any(netloc.endswith('.' + site.domain) for site in Site.objects.all().order_by("pk")) if (not (valid_origin)): return response if (request.method == 'POST'): session_key = request.POST.get('key') SessionStore = import_module(django_settings.SESSION_ENGINE).SessionStore if ((session_key) and (SessionStore().exists(session_key))): # Set session cookie request.session = SessionStore(session_key) request.session.modified … -
TypeError: Cannot read property 'file' of undefined, while updating Django model
I update my model with axios and file field causes some error. I use PATCH method for updating and this means i can include only one field to change. For example when i only post new picture, my image field will be updated and i can leave other fields empty. So updating only my image fields works. But now when i try to update only my name field, next error occurs. TypeError: Cannot read property 'file' of undefined And next thing is that when i update my image field and name field at the same time, this also works and my model gets updated. This is really confusing error but i hope someone knows what could cause issue here. Thanks in advance! My form handling method: handleFormSubmit = (event) => { event.preventDefault(); let form_data = new FormData(); form_data.append('name', event.target.elements.name.value); form_data.append('email', event.target.elements.email.value); form_data.append('location', event.target.elements.location.value); form_data.append('sport', this.state.sport); form_data.append('image', this.state.file.file, this.state.file.file.name); console.log(form_data.image); const profileID = this.props.token let url = `http://127.0.0.1:8000/api/profile/${profileID}/update` axios.patch(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => console.log(res)) .catch(error => console.err(error)); } In the frontend i also use ReactJS and for Form, Ant Design Form, but it shouldn't matter -
POSTGRESQL and Django app: could not receive data from client: Connection reset by peer
I am running a django app with postgresql, nginx and gunicorn. I have a script where data is pulled from one table in the DB, modified and then needs to replace the existing data in that one table. In the same script, a few tables are also being updated. When runnning the script, it always results in 502 Bad Gateway because the server times out because of something in the script. Being fairly new the topic, I am struggling to figure out what is going on with the following error. I only have the following log to work with from postgres: 2020-08-22 14:57:59 UTC::@:[8228]:LOG: checkpoint starting: time 2020-08-22 14:57:59 UTC::@:[8228]:LOG: checkpoint complete: wrote 1 buffers (0.0%); 0 WAL file(s) added, 0 removed, 1 recycled; write=0.101 s, sync=0.005 s, total=0.132 s; sync files=1, longest=0.005 s, average=0.005 s; distance=65536 kB, estimate=70182 kB 2020-08-22 14:58:50 UTC:address-ip(45726):pierre@dbexostock:[25618]:LOG: could not receive data from client: Connection reset by peer 2020-08-22 14:58:50 UTC:address-ip(45724):pierre@dbexostock:[25617]:LOG: could not receive data from client: Connection reset by peer I think the issue is inside of the connections to the database in the script: #connect to db engine = create_engine('postgresql+psycopg2://user:password@amazon.host.west', connect_args={'options': '-csearch_path={}'.format(dbschema)}) #access the data in the historical_data table conn = engine.connect() metadata … -
django how to use filter for ForeignKey
Hi thank you for watching. My question is how do I filtering for category category [fruits, vegetable] post [apple, banana, onion] For example, If I click fruits show apple, banana python 3 / django 3 project/app/models.py from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.PROTECT) category category1 name=fruits category2 name=vegetable post post1 title=apple category=fruits post2 title=banana category=fruits post3 title=onion category=vegetable python manage.py shell >>> from post.models import * >>> category = Category.objects.all() >>> print(category) <QuerySet [<Category: vegetable>, <Category: fruits>]> >>> post = Post.objects.all() >>> print(post) <QuerySet [<Post: apple>, <Post: banana>, <Post: onion>]> thank you for reading until end. -
Using login view provided by django instead of custom login view
I am working on a django website. I have my own custom user model. and this is my login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) return redirect('/category/all') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") I wanted to shift to the login_view provided by django to get features such as next after login which does not happen with my custom view. So in my urls can I just use login view or do i have to make some changes in my templates and user model or is it not possible to shift to pre provided login view after having a custom user model. -
How to nest up to 5 models in Django Admin page?
I have a book object which needs to be categorized up to sub 5 categories. The business requirement required the admin to add these categories page by page by first adding first-level categories and then click on each on to add second-level categories, After that, click on each one to add the third-level and so on up to 5. the below figure can describe the idea. Django inlines can add two objects of different models on the same page Which can help me only for the second-level categories, but what if I want to click in that second object to add subs inside it? Is that possible in Django? from the DB side, I think one table with the following attributes: key, value, and parent can help me in storing all the categories and whenever I wanted them on the client side I can arrange them before sending them in views. But the issue is on the admin side, how can I do it in that way? Thank you. -
Django Polling App gives an error of "No Polls are Available"
I did a search on all past answers but unable to get a clue. In the Django Polling App tutorial, I have reached generic views. After defining views.py, urls.py and the templates (index.html, detail.htmls and results.html) when i go to the url localhost:8000/polls/ I get the message no polls are available. If I go to the url localhost:8000/polls/1/ I can see the "What's New?" question with choices. My files below : views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from .models import Question, Choice from django.urls import reverse from django.views import generic from django.utils import timezone # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): """ Excludes any questions that aren't published yet. """ return Question.objects.filter(pub_date__lte=timezone.now().date()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', {'question': question, 'error_message': "You didn't select a choice.",}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) urls.py from django.urls import path from . import views app_name = … -
I'm trying to run the package, pip install psycopg2==2.7.* ,on my pycharm terminal so I can deploy my site but i get the message that appears
Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/a8/8f/1c5690eebf148d1d1554fc00ccf9101e134636553dbb75bdfef4f85d7647/psycopg2-2.8.5.tar.gz ERROR: Command errored out with exit status 1: command: /Users/applecare/PycharmProjects/learning_log/11_env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/w6/sqx_mjh176x08sjppl82f1l80000gn/T/pip-install-8j8wbzsu/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/w6/sqx_mjh176x08sjppl82f1l80000gn/T/pip-install-8j8wbzsu/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: /private/var/folders/w6/sqx_mjh176x08sjppl82f1l80000gn/T/pip-install-8j8wbzsu/psycopg2/ Complete output (23 lines): running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. WARNING: You are using pip version 19.2.3, however version 20.2.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. -
Django ignore 500 errors
I have developed an ecommerce store in Django where I am using twilio sms functionality. Using twilio, sms only sends if number is in proper format and valid. message = client.messages.create( body="Dear costumer, this is sample msg", to= number, from_= contact ) So I want a way through which if twilio raise an error in sending sms, this errors gets ignore [Don't raise Server Error 500 in prod]. And Website functionality remains normal. Is there any way to cater it? -
Static files doesn't update - Django
This is the second time i'm commenting about this problem and I really hope you can help me this time since i've gained some more information about the problem. So the problem is basically that all my Django projects doesn't update the static files (this also includes projects which I have downloaded). So I can fx still see the old styling from the css files but the changes is not displayed. When i insert the css or js directly into the html file i can see it though. I thought that it maybe had something to do with my browsers stored caches but I have tried to do a hard refresh, clearing all my caches, installing whitenoise and forced browser to reload the css file by adding an extra parameter to the end of the src tag. I have also tried python manage.py collectstatic and almost everything else on this thread. When the problem bagan to occur I was working with the implementation of stripe. I don't neccessarily think that stripe is the problem since the problem occured hours after i had already implementet the checkout site. I just think it's worth at least mentioning. Some of my venv packages: … -
I cannot go to the page I want
Hello I have a post blog where I have a homepage with posts and if you click on it you are redirected to the post_detail page. Now I want the users to allow to delete their comments which I achieved but I want them to stay on the same post_detail page. I could not come over it and hope that someone can help me. Thanks in advance. post_detail.html <div class="container"> <br> <h1 style="text-align:center;">{{post.post}} </h1> <p style="font-size:small;text-align:center;">{{post.created_on}}</p> <button type="button" class="btn btn-secondary float-right" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Yorum At</button> <br> <br> <br> {% for i in commentmodel_list%} <h4 >{{i.comment}}</h4> {% if i.author_security == user%} <a style="float:right;color:red;"href="{% url 'forum:delete' slug=post.slug comment_id=i.id %}"><i class="fas fa-minus-circle"></i></a> {% endif %} {% if i.author is none %} <p style="font-size:small;">Anonim | {{i.created_on}}</p> {% else%} <p style="font-size:small;"><a style="text-decoration:none;" href="#">@{{i.author}}</a> | {{i.created_on}}</p> {% endif %} <hr> <br> {% endfor %} </div> urls.py app_name='forum' urlpatterns=[ path('', views.PostList.as_view(), name='post'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('delete/<slug:slug>/<comment_id>/',views.delete_post,name='delete') ] views.py def delete_post(request,slug=None,comment_id=None): comment_delete=Comment.objects.get(id=comment_id) comment_delete.delete() post = Post.objects.get(slug=slug) return redirect('forum:post_detail', slug= post) -
render author name from text model as foreignkey in django
I want to render the author of each post to the template in my models.py file class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email", max_length=250, unique=True) date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='Last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) full_name = models.CharField(verbose_name="Full name" ,max_length=150, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = MyAccountManager() def __str__(self): return self.full_name # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True class Text(models.Model): title = models.CharField(max_length=200, null=True) document = models.TextField(max_length=None, null=True) requirements = models.TextField(max_length=200, null=True) date_created = models.DateField(auto_now_add=True ,null=True) deadline = models.DateField(null=True) author = models.ForeignKey(User ,on_delete=models.CASCADE,null=True) def __str__(self): return self.title NB: i want to render it in the home page so here is my home view def home(request): user = request.user form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): obj = form.save(commit=False) author = User.objects.filter(email=user.email).first() obj.author = author form.save() form = TextForm() texts = Text.objects.all().order_by('-id') context = {'form':form,'texts':texts} return render(request,'main/home.html' ,context) i want to do something like author_name = Text.author.full_name and then render author_name to the template i'm not sure if this is how to do … -
Deleting a value from a field of model in django
I am working on basic ecommerce website in django.I am having the following view that checks for a successful order. def handlerequest(request, id): order=Order.objects.get(id=id) items=order.orderitem_set.all() verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': order.save() print('order successful') else: order.dstatus="Cancelled" order.save() return render(request, 'handlerequest.html', {'response': response_dict,'order':order}) The items here refer to the products that a user has chosen to buy.My product models is as below with size model.(I have removed some fields) class Siz(models.Model): size=models.CharField(max_length=3,null=True,blank=True) class Product(models.Model): name=models.CharField(max_length=10) size=models.ManyToManyField(Siz) What I have done is that in my siz model I have added several sizes(eg. S,L,M) and for product I have selected the sizes which are available for each product. Now my concern is that whenever someone orders something then after checking in the view that the order is successful , I want to remove the size of the item ordered from the product.(For Example if someone orders a product AB of size L then from available size of that product I want to remove L) The following is my orderitem and order model for reference. class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) complete=models.BooleanField(default=False,null=True,blank=False) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,) size=models.ForeignKey(Siz,on_delete=models.SET_NULL,null=True) I also want to keep in mind that if there are multiple items that a … -
Django: Create a form for another other user existing in DB. ('Users' object has no attribute 'get')
I'm creating a cloud panel for our cloud Database, and I'm having some issues by creating a form for other users and rendering it. This is my forms.py from django.forms import ModelForm from main.models import Users class UsersForm(ModelForm): class Meta: model = Users fields = '__all__' exclude = ['last_login'] And then inside the views.py, I'm trying to create a form for other user with: form = UsersForm(model) return render(request, 'service_desk/ticket_list_edit.html', {'form': form}) I'm trying to pass in the user model to the form, but as you can see I'm getting an error -
Ajax success function not working: Django JSONResponse not sending
In the code below, I am using onclick (I know it may not be the best practice but for my particular situation I think it works best) to activate an ajax call to dynamically update the content on my Django template. As of now, the data is going to the back-end, and the Comment object is being created. However, when returning a JSONResponse, the template is not using the data from this JSONResponse to update the page in any way. I have tried testing with alerts but to no avail. I am new to JS so I would love a little help! Thank you very much. Django View: def sochome(request, oid): society = Society.objects.filter(id=oid).first() membership = SocietyMembership.objects.get(member=request.user, society=society) response_data = {} if request.method == 'POST': postID = request.POST.get('post_id') comment_content = request.POST.get('comment') response_data['post_id'] = postID response_data['comment'] = comment_content post = SocPost.objects.filter(id=postID).first() SocComment.objects.create(post=post, author=request.user, content=comment_content) # print(response_data, file=sys.stderr) # print("SUCCESS JSON RESPONSE TO CLIENT SIDE", file=sys.stderr) return JsonResponse(response_data) context = { 'membership': membership, 'posts': society.posts.all().order_by('-date_posted') } return render(request, 'blog/sochome.html', context) HTML: < script type = "text/javascript" > function update_comment(post_id) { $.ajax({ type: 'POST', url: "{% url 'blog-sochome' oid=membership.society.id%}", data: { 'post_id': post_id, 'comment': document.getElementById(post_id.toString()).value }, dataType: 'text', success: function(data) { alert("ajax completed … -
Reverse for 'update_profile' not found. 'update_profile' is not a valid view function or pattern name
I hope you're well. Just one question that's been bothering me a lot lately... I got the issue only when I update my form. The update works after refreshing the page. views.py in user folder #update detail @method_decorator(login_required(login_url='/earlycooker/login/'),name="dispatch") class UserProfileUpdateView(UpdateView): model = UserProfile template_name = 'profile-update.html' form_class = UserProfileForm success_message = "Profile updated" def form_valid(self, form): form.instance.user = self.request.user form.save() return super(UserProfileUpdateView, self).form_valid(form) def get_success_url(self): return reverse('update_profile',kwargs={'slug':self.object.slug}) def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.user != request.user: return HttpResponseRedirect('/') return super(UserProfileUpdateView, self).get(request,*args,**kwargs) urls.py in user folder path('details/<slug:slug>/', UserProfileUpdateView.as_view(), name="update_profile"), profile-update.html in user folder {% url 'user:update_profile' slug=user.userprofile.slug %} -
Django Monolithic vs Microservices
I always had this doubt and want to clear it up. Django architecture is somewhat similar to microservices architecture in the sense all the apps in a Django project are isolated which is the same case in Microservices architecture. If one app fails, it doesnt affect other apps. So is it fair considering a Monolithic Django App to be a Microservices architecture? -
Custom Registration form in django shows "This field is required" even when it's filled
I have created a multiform Registration form but even when I type in all the details it says "This field is required". I have not used {{ form }}. Instead I have used fields for the input. register.html: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <small>{{ error }}</small> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <small>{{ error }}</small> </div> {% endfor %} {% endif %} <div class="center"> <div class="form_outer"> <form method="POST"> {% csrf_token %} <div class="page slidePage"> <div class="field"> <div class="label">Username*</div> <input type="text" name="username" id="username" class="form-control"> </div> <div class="field"> <div class="label">Firstname*</div> <input type="text" name="username" id="first_name" class="form-control"></div> </div> <div class="field"> <div class="label">Lastname*</div> <input type="text" name="username" id="last_name" class="form-control"></div> </div> <div class="field"> <button type="button" class="nxt nextBtn-1">NEXT</button> </div> </div> <div class="page"> <div class="field"> <div class="label">Email</div> <input type="text" name="email" id="email" class="form-control"> </div> <div class="field"> <div class="label">Password</div> <input type="password" name="password1" id="password1" class="form-control"></div> </div> <div class="field"> <div class="label">Password Confirmation</div> <input type="password" name="password2" id="password2" class="form-control"></div> </div> <div class="field buttons"> <button type="button" class="prev-1 prev">BACK</button> <button type="submit" class="submit">SUBMIT</button> </div> </div> </form> </div> </div> forms.py: class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') class Meta: … -
Pre_Save reciever not updating item's stock
I have a cart item model and I want it to decrease the stock when the ordered field is set to true but I don't think I'm doing it right. CartItem model: class CartItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) size = models.ForeignKey(Size, on_delete=models.CASCADE, null=True) quantity = models.IntegerField(default=1) My Pre_save receiver: @receiver(pre_save, sender=CartItem) def decrease_stock_receiver(sender, instance, *args, **kwargs): if instance.ordered is True: print("check stock: " + str(instance.size.stock)) instance.size.stock -= instance.quantity print("decrease stock: " + str(instance.size.stock)) -
Connect call failed ('127.0.0.1', 6379)
I am creating simple chat server by following this tutorial here https://channels.readthedocs.io/en/latest/tutorial/part_2.html ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) can any helpmeout for this I saw one of the solutions "Try changing 127.0.0.1:6379 to redis:6379" in Docker [Errno 111] Connect call failed ('127.0.0.1', 6379) but did not understand how to do that Thank you in advance -
How to avoid 2 equal loopings | Django
I got this code: i = 1 for item in cart: data_ps[f"itemId{i}"] = item data_ps[f"itemDescription{i}"] = item.category.name data_ps[f"itemAmount{i}"] = item.sell_price data_ps[f"itemQuantity{i}"] = '1' i += 1 total_value = format(((shipping_price + cart_price) / installment), '.2f') data_ps['installmentValue'] = total_value response = requests.post('https://ws.sandbox.pagseguro.uol.com.br/v2/transactions', headers=headers, params=params, data=data_ps) if response.status_code == 200: for item in cart: Sell.objects.create(item=item, date=timezone.now(), discount=Decimal(0.00), total_paid=cart.get_total_price(), buyer=request.user, ) As you can see, there are 2 for item in cart loop. After the first one, I need to get a request.post and then check if the status_code is equal 200. If so, the code gerenates another for item in cart loop. I was wondering if there is a way to avoid the second looping adding all this information inside the first one, because it just update a record in my database ('Sell.objects.create'). Any idea? Thank you -
How to load spesific data with ajax in django?
I was want to learn "how ajax working on django ?" so I found this project from web and started the working on this https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html I got something from that project but reverse engineering is did not work :/ When I run the project of this link and create a person was everything ok, like if I do not write the firstname as required input ajax gives me an eror. My button is too should working like this. But later when I wrote my own code block and pressed the (mydata) button I did not get an eror or something so I think ajax did not work and I do not know why Script.js This script is in the document.ready function $('#mydata').on('click', function(){ $firstname = $('#firstname').val(); if($firstname == ""){ alert("Please complete the required field"); }else{ $.ajax({ url: 'mydata', type: 'POST', data: { firstname: $firstname, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(response){ console.log('working!') $('#result').html(response); } }); } }); Views.py def mydata(request): firstname = request.GET.get('firstname') members = Member.objects.filter(firstname=firstname) context = {'member': members} return render(request, 'crud/index.html', context) index.html <form class="form-inline"> {% csrf_token %} <div class="form-group"> <label>Firstname</label> <input type="text" id="firstname" class="form-control" style="width:30%;" required="required"/> <label>Lastname</label> <input type="text" id="lastname" class="form-control" style="width:30%;" required="required"/> <button type="button" id="create" class="btn btn-sm btn-primary">Create</button> … -
Record user IP address in Django During Development, not 127.0.0.1
Using Django 3.0.8, I am trying to record a user's IP address during development to ensure my database isn't spammed by multiple submissions from the same IP Address. I am currently using Django's in-built request.META.get("REMOTE_ADDR") as per the Django docs, but this only returns the 127.0.0.1 when I print out to the terminal. Is there a more robust way to obtain the IPv4/IPv6 address during development? -
Django model class relationships
I'm trying to map out the relationship between my models and before I spend to much time creating the form to create the objects on the client side I want to check it's the most efficient way of doing so. I am creating form that allows me to create a Workout. Each Workout consists of multiple exercises. However, I want the ability to be able to group exercises into Sets (Supersets). So you can either perform one exercise on its own OR 2 or 3 exercises back to the group. e.g. Workout Exercise: 1 Sets 4 Reps 12 Exercise: 2 Sets 3 Reps 10 Superset: 3 Exercise a Exercise b Sets 4 Reps 3 Exercise: 4 Sets 4 Reps 3 I current Have a Workout class with a ManyToMany to my Set class, which then has a ManyToMany to the Exercise Class. Each exercise needs to have sets and reps etc. However, something doesn't feel right about creating a 'Set' object, then assigning exercises to it. Especially when creating a single exercise object. My models currently look like the following: class Workout(models.Model): title = models.CharField(max_length=50) account = models.ForeignKey("customer.Account", on_delete=models.PROTECT) date_created = models.DateField(_('Creation date'), auto_now_add=True) set_of_exercises = models.ManyToManyField("gym.Set", blank=True) def __str__(self): … -
Is there a way in django to automatically create model objects
Hello, recently I have been using django-allauth for external auth ... But I have a question is there a way were like if there is a new user registered using django-allauth It will create the User object Is there like now a way that if there's a new user added to the Users object in the django models, it will make another model object in the example model called Profile, with all the information gather there ... Like the Profile model is watching for changes in the User object and when there is one it will make the appropriate object ... I know it is a bit confusing but please I would like to know ...