Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database routing parameter transmission problem
class AuthRouter: def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ params = hints.get('params') return 'default' def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ params = hints.get('params') return 'default' I want to pass some parameters to **hints, but I don’t know how to do it, can you tell me, thank you very much! I tried the following methods, but none of them work # read TestModel.objects({'params': 'Hello World'}).filter() # {TypeError}'UserManager' object is not callable TestModel.objects.filter(hints={'params': 'Hello World'}) # {FieldError} Cannot resolve keyword 'hints' into field ... # write TestModel.objects.filter().first().save(hints={'params': 'Hello World'}) # {TypeError}save() got an unexpected keyword argument 'hints' -
How to get the instance when upload file using model FileField in Django
I have a Customer model and I have a upload model, linked to Customer: model.py class BasicUploadTo(): prefix = '' suffix = dt.now().strftime("%Y%m%d%H%M%S") def upload_rules(self, instance, filename): (filename, extension) = os.path.splitext(filename) id = instance.customer_id.customer_id.user_id return os.path.join(str(id), "Docs", f"{self.prefix}_{self.suffix}{extension}") def upload_br(self, instance, filename): instance1 = Customer.customer_id self.prefix = "BR" dir = self.upload_rules(instance, filename) return dir class AttachmentsBasic(models.Model): customer_id = models.OneToOneField("Customer", verbose_name="client ID", on_delete=models.DO_NOTHING, blank=False, null=True) br = models.FileField(upload_to=BasicUploadTo().upload_br, verbose_name="BR", null=True, blank=True) class Customer(models.Model): customer_id = models.OneToOneField("UserID", blank=False, null=True, verbose_name="Client ID", on_delete=DO_NOTHING) ... class UserID(models.Model): user_id = models.CharField(max_length=5, blank=False, verbose_name="Client ID") class Meta(): verbose_name = "Client" verbose_name_plural = "Client" def __str__(self): return f"{self.user_id}" form.py: class ClientUploadForm(ModelForm): class Meta: model = AttachmentsBasic fields = ( "br",) def __init__(self, path, *args, **kwargs): super(ClientUploadForm, self).__init__(*args, **kwargs) print(path) for x in self.fields: self.fields[x].required = False def save(self, client_id, commit=True): clientDoc = super(ClientUploadForm, self).save(commit=True) print(self) instance = Customer.objects.get(customer_id__user_id=client_id) clientDoc.customer_id = instance if commit: clientDoc.save() return clientDoc views.py def clienInfo(request, client): clientsIDs = [c.customer_id.user_id for c in Customer.objects.all()] if client in clientsIDs: matching_client = Customer.objects.filter(customer_id__user_id=client) if request.method == "POST": instance = Customer.objects.get(customer_id__user_id=client) uploadForm = ClientUploadForm(request.POST, request.FILES, instance.customer_id.user_id) if uploadForm.is_valid(): uploadForm.save(request.POST["customer_id"]) else: print("Client's document form got error.") else: print("Client form got error.") uploadForm = ClientUploadForm sale = sales.objects.all() return … -
enable to verify whether data exists in database for login
i am a beginner i am trying to do a post request to get the coer_id and password from the client and then i am trying to check whether they exists in database or not .i am enable to perform it.it will be really helpful if you can tell me how i can correct it or do it . models.py from django.db import models from django.core.validators import RegexValidator class student_register(models.Model): name=models.CharField(max_length=100) father_name=models.CharField(max_length=100,null=True) bhawan=models.CharField(max_length=100,null=True) branch=models.CharField(max_length=40,null=True) coer_id=models.CharField(max_length=12,unique=True,null=True) phone_regex=RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17) password=models.CharField(max_length=100) serializer.py from django.db.models import fields from rest_framework import serializers from .models import student_register class register_serializers(serializers.ModelSerializer): class Meta: model = student_register fields = '__all__' class login(serializers.ModelSerializer): class Meta: model = student_register fields = ['coer_id','password'] views.py from rest_framework.response import Response from rest_framework import viewsets from .models import student_register from .serializer import register_serializers from .serializer import login from rest_framework.decorators import api_view from rest_framework import status class register_view(viewsets.ModelViewSet): queryset= student_register.objects.all() serializer_class= register_serializers @api_view(['POST']) def check_login(request): serializer=login(data=request.data) if serializer.is_valid(): if student_register.objects.filter(coer_id=serializer['coer_id']).exists(): if student_register.objects.filter(password=serializer['password']).exists(): return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) this is the error which i get when i send the json file and post it Internal Server Error: /login/ Traceback (most … -
Where is class "django.template.Node " defined in Django source code
I am reading Django official guide and came across a statement as below: When Django compiles a template, it splits the raw template text into ‘’nodes’’. Each node is an instance of django.template.Node and has a render() method. A compiled template is a list of Node objects. But I did not find django.template.Node definition in Django source code, where is it please ? -
how can i route from one nginx serve to another?
i have a containerized nginx server currently setup with https (nginx.main) and it's serving my django app that's in another container. unfortunately, django is not responding with the static files - and i've read that's a normal thing. so, what i'd like to do is setup another instance of nginx to do that for me (nginx.static) nginx.main default.conf config that i've tried: ...some stuff going to --> server { listen 4430 ssl; listen [::]:4430 ssl default ipv6only=on; server_name avnav.com; ssl_certificate /etc/nginx/_cert/etc/letsencrypt/live/avnav.com/fullchain.pem; ssl_certificate_key /etc/nginx/_cert/etc/letsencrypt/live/avnav.com/privkey.pem; ssl_dhparam /etc/nginx/_cert/etc/letsencrypt/live/dhparam.pem; ...some security stuff... location / { proxy_pass http://django_app; proxy_set_header Host avnav.com; } location /media { proxy_pass http://nginx_static; } } nginx.main nginx.conf config: upstream django_app { server droplet.ip:8000; } upstream nginx_static { server droplet.ip:8082; } nginx.static default.conf config: server { listen 8080 default; server_name localhost; location / { root /usr/share/nginx/static/; } at first i thought it was an issue with alias vs root, but not so. the volumes are setup so that the host static files are mounted to /usr/share/nginx/static in nginx.static. inside that folder, there are subfolders for css, js, etc. nginx.main runs on port 8081:8080 django runs on 8000 nginx.static runs on 8082:8080 -
Access blocked by CORS policy: No 'Access-Control-Allow-Origin'
I am using the following versions Python 3.9.6 Django 3.2.3 django-cors-headers==3.7.0 I have the following in my settings.py CORS_ALLOW_ALL_ORIGINS=True CORS_ORIGIN_WHITELIST = ('http://localhost:3000',) For some reason, one of the API call fails out with this error. Access to fetch at from origin has been blocked by CORS policy: No 'Access->Control-Allow-Origin' header is present on the requested resource. If an opaque response serves >your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I am not able to understand why I get this error. Here are the relevant request and response details as extracted from Google Chrome Developer tools General Request URL: http://10.0.123.123:8998/api/box?unit=101&box=TOT000000000051345&login_user_id=USERID&reserve_locn=101 Request Method: OPTIONS Status Code: 200 OK Remote Address: 10.0.123.123:8998 Referrer Policy: strict-origin-when-cross-origin Response Headers Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: * Access-Control-Max-Age: 86400 Connection: keep-alive Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Tue, 07 Sep 2021 01:15:10 GMT Server: nginx/1.20.1 Vary: Origin Request Headers OPTIONS /api/box?unit=101&box=TOT000000000051345&login_user_id=USERID&reserve_locn=101 HTTP/1.1 Host: 10.0.123.123:8998 Connection: keep-alive Accept: / Access-Control-Request-Method: GET Access-Control-Request-Headers: content-type Origin: http://10.0.123.123:8999 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Sec-Fetch-Mode: cors Referer: http://10.0.123.123:8999/ Accept-Encoding: gzip, deflate Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 -
How to connect AWS Elasticache Redis from a local machine for a Django project?
I've Redis chace installed on both my local and aws elasticache. My Django project runs well on my local machine with Redis. However, when I connect to my redis remotely on aws, I get the following error. Error 10060 connecting to xyz.0001.use2.cache.amazonaws.com:6379. A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. I have the following Django settings for the local redis: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } And this the Django settings for the remote redis instance: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://xyz.0001.use2.cache.amazonaws.com:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } Again, when I switch from local to remote caches settings, I get that error above. I know that I it is not possible to connect ElastiCache outside AWS unless you have a vpn connection. So, I've set up the vpn client end point on aws and connected to it using the aws vpn client. I can successfully connect via vpn as shown below. Any idea why I still can't connect from my local machine to the remote redis … -
raise ValueError('Filename must be a string') ValueError: Filename must be a string when upload file to AWS S3 in Django
I have used Django to develop a web app. In the frontend, the user is supposed to upload an image by upload button to AWS S3. But I got the error at s3_client.upload_file: raise ValueError('Filename must be a string') ValueError: Filename must be a string view.py def save_pic(request): print("save_pic") if request.method == 'POST': image = request.FILES.get('image') print(image) img_name = image.name ext = os.path.splitext(img_name)[1] img_path = os.path.join(settings.IMG_UPLOAD, img_name) with open(img_path, 'ab') as fp: for chunk in image.chunks(): fp.write(chunk) import boto3 from botocore.exceptions import ClientError s3_client = boto3.client('s3', aws_access_key_id='XXX', aws_secret_access_key='XXX', region_name='XXX') try: with open(img_path, 'rb') as fp: response = s3_client.upload_file(fp, 'etp-tms', 'image_0.jpg') except ClientError as e: print(e) try: data = {'state': 1} except: data = {'state': 0} return JsonResponse(data) return JsonResponse(data="fail", safe=False) HTML: function renderCover(value, row) { return '<input id="image-input" accept="image/*" type="file" />\n' + '<img id="image-img" /> ' } function upload() { //alert("upload"); var formdata = new FormData(); formdata.append("image", $("#image-input")[0].files[0]); formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val()); $.ajax({ processData:false, contentType:false, url:'/save_pic/', type:'post', data:formdata, dataType:"json", success:function (arg) { if (arg.state == 1){ alert('success') }else { alert('fail') } },error: function () { alert("error") } }) } when I upload the img, the error occurs at response = s3_client.upload_file(fp, 'etp-tms', 'image_0.jpg').: raise ValueError('Filename must be a string') ValueError: Filename must be … -
putting fields labels in django table in first row
I want to: print the label in the first row set with of each field to 45px put the first column where C will enumerate 1,2,3,... according to the rows. it should be something like this: V x1 x2 direct RHS C1 field field field field C2 field field field field C3 field field field field in the body of page.html: <table> {% for form in formset %} <tr> {{ form.label }} {% for item in form %} <td style="width:10px; text-align: center">{{ item }}</td> {% if not item.label_tag = 'direction' %} ...do something... {% endif %} {% endfor %} </tr> {% endfor %} </table> in forms.py: class linprog_vars(forms.Form): x1 = forms.FloatField(label='x1') x2 = forms.FloatField(label='x2') direct = forms.CharField(label='direct') rhs = forms.FloatField(label='rhs') En views.py def linprog(request): extra_lines = 3 formset = formset_factory(linprog_vars, extra=extra_lines) context = {'formset': formset} return render(request, 'linprog/linprog.html', context) -
Django Models Data is not shown in Bootstrap Modal
I have faced a problem to pass the model data to Bootstrap modal. The information is not displayed in Bootstrap modal but when I try to pass data to a normal template, the information is shown. Can you guys please help me to find out where is the problem. I will be very appreciated for your help! Here is the code. catalog.html <div class="row"> {% for getdata in furniture %} <div class="col-md-4"> <a class="" href="{{ getdata.update_view_count_url }}" data-toggle="modal" data-target="#product_modal"> <div class="card text-center mb-5"> <img src="{{baseUrl}}/{{getdata.furnitureImg}}" alt="" class="card-img-top mt-3 px-2"> <div class="card-body"> <h3 class="card__fName text-uppercase">{{getdata.furnitureName}}</h3> <h2 class="card__fPrice">${{getdata.unitPrice}}</h2> <a href="{{ getdata.add_to_cart_url }}" class="card__button text-uppercase"> <i class="uil uil-shopping-cart"></i> Add To Cart </a> </div> </div> </a> </div> {% endfor %} {% include 'user/product.html' %} </div> models.py def update_view_count_url(self): return reverse("ecommerce:view", kwargs={ 'slug': self.slug }) urls.py from django.urls import path from . import views from . import recommendation from .views import ItemDetailView, CartDetailView, OrderSummaryView app_name = 'ecommerce' urlpatterns = [ path('view/<slug>/', views.updateViewToItem, name='view'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), ] views.py class ItemDetailView(DetailView): model = Furniture template_name = "user/product.html" # View the item after clicking def updateViewToItem(request, slug): item = get_object_or_404(Furniture, slug=slug) viewed_item = User_Views.objects.filter(userId=request.user, furnitureId=item) if viewed_item.exists(): get_viewed_item = User_Views.objects.get(userId=request.user, furnitureId=item) get_viewed_item.viewCount += 1 get_viewed_item.save() else: view … -
Why can't I get Axios to set CSRF token headers?
I have an HTTP only cookie that was set by Django for session based authentication. When I try to make a POST request in my Next.Js app I get detail: "CSRF Failed: CSRF token missing or incorrect.". I know I need the X-CSRFToken header but Axios won't set it for me. The cookies are being sent in the request just not as a header. My post request looks like: axios .post(`${process.env.NEXT_PUBLIC_API_URL}/shops`, createShopFormData, { xsrfHeaderName: 'X-CSRFToken', xsrfCookieName: 'csrftoken', withCredentials: true, }) .then((response: AxiosResponse) => { console.log(response); }) .catch((error: AxiosError) => { console.log(error.response?.data.message); }); }; -
Django and nginx: How to add url prefix to all the django urls
I have the following nginx config: I am running two servers Nodejs(port:3000) and django(port:8000) http { server { listen 80; server_name localhost; location / { proxy_pass http://127.0.0.1:3000; <-- NODEJS APP } location /api { proxy_pass http://127.0.0.1:8000; <-- DJANGO APP } } } I want to access Django at {domain_name}/api and anything other than that will be fetched from Nodejs I want to access all the /admin and whatever urls mentioned in the Django at /api Is there any way to do that. I know i can add /api infornt of all the urls in the urls.py. But this can be dynamic. So I dont want to disturb the urls. -
Inspect response when i use a view Class-based views - Django
I need to inspect the response for know the params of pagination. I try used Pdb but the application stops. I think to overwrite some method like def dispatch(self, request, *args, **kwargs): but i don't know if the best way, someone could guide me ? class PostsFeedView(LoginRequiredMixin, ListView): template_name = 'posts.html' model = Post ordering = ('-created',) paginate_by = 10 context_object_name = 'posts' # import pdb; pdb.set_trace() -
find the total time a user spent in python
How to read text file line by line than filter time details and sum the time. Basically I need to find the total time a user spent in hours.for example: TL:1 2/23/12: 9:10pm - 11:40pm getting familiar with Flash 2/29/12: 12:50pm - 2:00pm getting familiar with Flash 3/1/12: 6:00pm - 11:40pm getting familiar with Flash 3/3/12: 3:00pm - 7:00pm step-debug Energy Game code 3/4/12: 8:00pm - 11:40pm start carbon game 3/5/12: 2:00pm - 3:00pm 4:00pm - 4:30pm carbon game 3/6/12: 11:30am - 1:30pm carbon game data structures and classes for the first action 3/7/12: 11:00am - 5:00pm tested basic concept 3/8/12: 1:00am - 1:30am changed vector calling, 10:30am - 2:30pm 4:00pm - 5:00pm wrote code to draw points indicator and marshal the data -
Django: Is there a way to play local video in VLC or something else when the django view is requested on click event from html?
I am building python django application where I need to play a video when request is made from web browser. Scenerio: When I click a button from webapp then I should be directed to next page, and video should play on either mediaplayer such as VLC or something else(pop-up). I tired python openCV and VLC library, but had a very little luck because It wait for video to finish playing, so it doesn't render the page and kills the django server. Here is the code I was trying: play_video() opens the openCV frame and start playing the video, but django view doen't render def index(request): person = person.objects.all() context = {'donors': donors} play_video() return render(request, 'index.html', context) -
File arrangement different in Ubuntu server
I have a problem retrieving the last file from some files with these filenames: On Windows localhost: On Ubuntu server: Its all arranged by year and by quarter. I need the last file for 1 of my scripts, and the way I access it is by doing: filenames = os.listdir(edgar_path) last_file = filenames[-1] It works fine on my localhost on my Windows PC, but it's working unexpectedly on the Ubuntu server. When I try to print the last file being retrieved, it's different on the server. logger.debug('last_file') logger.debug(last_file) Windows localhost result: Ubuntu Server result: It's the same script, with the same files but for some reason, it's returning the wrong file in the servers script. Any idea what might cause this? Any help is appreciated. -
how to solve CORS error using react and django on aws
I have my application in production where www.foo.com is the frontend on s3 built with reactjs and api.foo.com is the backend built with django. Both the front end and backend are on cloudfront. now whenever i try to hit the endpoint create i get the following result in the console. Access to XMLHttpRequest at 'https ://api.foo.com/create/' from origin 'https ://www.foo.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js:177 POST https ://api.foo.com/create/ net::ERR_FAILED react create.js ... const options = { headers: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*", // I have tried to comment this before... } }; const handleSubmit = (e) => { e.preventDefault(); console.log("form submitted", fields.name); axios.post("https ://api.foo.com/create/", fields, options) .then(response => { console.log("Status", response.status); console.log("Data", response.data); }).catch((error => { console.log("error", error); })); }; ... django settings.py ... ALLOWED_HOSTS = ["*"] # for the sake of testing CORS_ORIGIN_WHITELIST = ( "https ://www.foo.xyz", ) CORS_ALLOWED_ORIGINS = [ "https ://www.foo.xyz", ] ... django views.py ... @api_view(["POST"]) @parser_classes([JSONParser]) def create(request): if request.method == "POST": serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The configuration seem right to me, not sure what i am getting wrong here Any help would be much appreciated -
Simple Background Image, Django unable to find image
Just wanting to make a simple multiple page website and I cant seem to get the background image to show on local host, Django just keeps saying Image not found. Can anyone help with this?? I want to drop vue in and do some fun stuff, but If I can't even get the images to show its going to be no fun at all. The HTML File. <body> <section id="hero" class="d-flex align-items-center"> <div id="bg"> <div class="bg"> <img src="{% static "media/ocean.jpg" %}" class="bg1" alt="" /> My View File from django.shortcuts import render # Create your views here. def homepage(request): return render(request, '/Users/mossboss/Dev/SimpleWS/apps/core/templates/core/base.html') My Settings STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' -
Transfer the QuerySet in Django AdminModel
I'm trying to make a reference to another model with my sorting. query = Cars.objects.filter(task_id__exact=obj.task_id, engine__isnull=False).values_list('engine', flat=True) engines_ids_list=list(query) link = reverse("admin:auto_engines_changelist") + f"?id={engines_ids_list}" ^ Not work, it's example ?engine_id=1&engine_id=2 display object with the last parameter (engine_id=2), not 2 objects.. work only Engines.objects.filter(pk__in=engines_ids_list) How can I send this filter to the engine changelist page? -
Django using multiple form with rich editor
I am creating comment area and reply to comment area for users. And I using django-ckeditor for this but there is a problem. When I add "reply form" just showing once in the page. Not showing other forms. The reply system its works just its not showing ckeditor(Rich editor). I am add some photos for better understanding: secon image: inspect: my Models: class UserMessages(models.Model): postMessages = RichTextUploadingField(null=True, verbose_name="Message") post = models.ForeignKey( serPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) username = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="Username", null=True) replies = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) my Forms: class MessageForm(forms.ModelForm): class Meta: model = UserMessages fields = ("postMessages",) widgets = { "postMessages": forms.TextInput(attrs={"class":"form-control"}), #And I tried this but not works.. class ReplyFormMessage(forms.ModelForm): class Meta: model = UserMessages fields = ("replies",) my HTML: <form method="POST" > {% csrf_token %} {{form.media}} {{ form }} <input type="hidden" name="replies_id" value="{{ message.id }}"> <input type="submit" value="Reply" class="btn btn-default"> </form> as for me, ckeditor just using one id for all form in page. So, do you have an idea? -
Handle requests that demand high RAM in Django
I have developed a geospatial app using Django. Users have the potential to draw a polygon and to get data analysis for the pixels included in the polygon. In order to get this data analysis, each request demands several GB and a couple of minutes to show the result. What if many users make a response at the same time? There will be a problem regarding the RAM. What I need is to put the requests into a queue, inform the user with a message about the waiting and execute one by one the requests. Any idea how to make this happen? Thanks in advance. Best, Thanassis -
Django - keyerror in form when running test
I have a CustomUser model, using django's auth for authentication, and a custom signup view. In the signup form I have some validation to check that the email_suffix (domain of the email) matches with the district that they select in the form. I also check that the email is unique. When running a test on this, I get an error on the form: value_district = self.cleaned_data['district'] KeyError: 'district' Model class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) SD23 = 'SD23' SD39 = 'SD39' SD67 = 'SD67' SDISTRICT = [ (SD23, 'Kelowna SD23'), (SD39, 'Vancouver SD39'), (SD67, 'Summerland SD67'), ] district = models.CharField( max_length=4, choices=SDISTRICT, blank=True, default='SD39') paper = models.BooleanField(default=False) def __str__(self): return self.username View def signup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) to_email = form.cleaned_data.get('email') # make the username the same as the email user.username = str(to_email) user.is_teacher = True user.is_staff = True user.is_active = False user.save() group = Group.objects.get(name='teacher') user.groups.add(group) current_site = get_current_site(request) print(urlsafe_base64_encode(force_bytes(user.pk))) sendgrid_client = SendGridAPIClient( api_key=os.environ.get('SENDGRID_API_KEY')) from_email = From("doug@smartmark.ca") to_email = To(to_email) subject = "Activate your SmartMark Account" active_link = render_to_string('account/acc_active_email_link.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_text … -
how to define subdomain with ip address django tenant app
im trying to deploy my django project using django-tenants i deploy it through linux ubuntu server 20.4 LTS version , my ip address 255.255.255.255(not correct) it works fine for the public schemas but when i try to creating a new tenant for example blog1 with domain name blog1.255.255.255.255 it doesnt work , and shows nothing but it create a new schemas , but i cant access it through my browser ! is there any solution if i dont use domain name ?! my ALLOWED_HOSTS = ['*'] i use dedicated server in linode thank you django version == 3.2 i use postgres DB version 12 -
Django ValueError: ModelForm has no model class specified. Where am I going wrong?
from django.db import models class Topic(models.Model): """Um assunto sobre o qual o usuário está aprendendo.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Devolve uma representação em string do modelo.""" return self.text class Entry(models.Model): """Algo específico aprendido sobre um assunto.""" topic = models.ForeignKey(Topic, on_delete=models.PROTECT) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Devolva uma representação em sring do modelo.""" return self.text[:50] + "..." This error persists. Can anyone point me where I'm wrong? -
Direct assignment to the forward side of a many-to-many set is prohibited. User exercise.set() instead
I have two models, Exercise and Workouts. I want to create a workout with a set of exercise. I have already able to send the array of exercise and workout details using POST and ajax, but I keep getting this error. I have read all other questions with this error, but my problem is two things: 1-the exercise item is already created, 2-I want to add more than one exercise item to the workout table. Any idea on how to do this? models.py: class Exercise(models.Model): BODYPART_CHOICES = ( ('Abs', 'Abs'), ('Ankle', 'Ankle'), ('Back', 'Back'), ('Biceps', 'Biceps'), ('Cervical', 'Cervical'), ('Chest', 'Chest'), ('Combo', 'Combo'), ('Forearms', 'Forearms'), ('Full Body', 'Full Body'), ('Hip', 'Hip'), ('Knee', 'Knee'), ('Legs', 'Legs'), ('Lower Back', 'Lower Back'), ('Lumbar', 'Lumbar'), ('Neck', 'Neck'), ('Shoulders', 'Shoulders'), ('Thoracic', 'Thoracic'), ('Triceps', 'Triceps'), ('Wrist', 'Wrist'), ) CATEGORY_CHOICES = ( ('Cardio', 'Cardio'), ('Stability', 'Stability'), ('Flexibility', 'Flexibility'), ('Hotel', 'Hotel'), ('Pilates', 'Pilates'), ('Power', 'Power'), ('Strength', 'Strength'), ('Yoga', 'Yoga'), ('Goals & More', 'Goals & More'), ('Activities', 'Activities'), ('Rehabilitation', 'Rehabilitation'), ) EQUIPMENT_CHOICES = ( ('Airex', 'Airex'), ('BOSU', 'BOSU'), ('Barbell', 'Barbell'), ('Battle Rope', 'Battle Rope'), ('Bodyweight', 'Bodyweight'), ('Cables', 'Cables'), ('Cones', 'Cones'), ('Dumbbells', 'Dumbbells'), ('Dyna Disk', 'Dyna Disk'), ('Foam Roller', 'Foam Roller'), ('Kettlebells', 'Kettlebells'), ('Leg Weights', 'Leg Weights'), ('Machine', 'Machine'), ('Medicine Ball', …