Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way store data when callback -Python - Django - Bokeh - Webdevelopment
When doing a bokeh callback (zooming), new 500 values have to be loaded. xRangeStart and xRangeEnd define the new needed values from the total array. How to store this total array to get the best performance. Redis, direct from DataBase (MongoDB), somehow else?(backend stateless) flow: user action on frontend --> callback call --> ajax --> here I need to get the new data as described --> getting new data from total array --> ajax returns --> source.change.emit() the bold marked part is stored in REDIS atm (Coding with python). The callback takes some seconds when there are multiple graphs/lines within a chart (around 1sec for each arrays with a size of 3 million values). Is there a way to imporve this speed in general. -
Only want to call a view(not to return anything) using ajax in django
I have a button on my homepage. I want this button to call the view named "request_twitter". Just call it, nothing wants to return. I have developed the code from questions asked on this platforms but still I am not able to call that view. Here is my code view.py def request_twitter(request): global screenname if request.method == 'POST': screenname = request.POST['screenname'] user = validator(request) #this is checking if user is login or not. if he is not login then it will redirect him to login page eg twitter oauth if user: api = get_api(request) user = api.get_user(screenname) try: sn = user.screen_name except: sn = '' try: disply_name = user.name except: disply_name = '' try: descriptin = user.description except: descriptin = '' try: locatin = user.location except: locatin = '' try: urll = user.url except: urll = '' try: Date_joined = user.created_at except: Date_joined = '' try: twitter_user_id= user.id except: twitter_user_id = '' try: profile_lang = user.lang except: profile_lang = '' try: time_zzone = user.time_zone except: time_zzone = '' try: tweetzz = user.statuses_count except: tweetzz = '' try: followingg = user.favourites_count except: followingg = '' try: followerss = user.followers_count except: followerss = '' try: likess = user.favourites_count except: likess = '' … -
How to connect two registered users in Django
I have a Django 2.1.5 app in which I have created two different forms, onto which registered users can post their requirements, for example : "I need a vehicle to go from point A to B", or "I need to go from D to E tomorrow". And, other users can post their services as in "I have a truck free that can go from A to B" etc. So, I have 2 boards, one is for people who need vehicles, and other where people are posting they have free vehicles. Now, I have two different pages for both boards, and two different forms for each board. Now, if I find a requirement which I can fulfil, then there is a button which says 'Bid your price'. After which, I provide my details and a bidding price for the person asking. Then, this information is to be sent to the original author of that requirement. I need to figure out how to connect these two registered people. Should I just give every requirement and service offer a unique URL? and same for every user ? Or is there any other method ? I am really stumped here on what is the … -
ELI5: What is Django?
I realize that some people are probably rolling their eyes at the question, but believe it or not "a high-level Python Web framework" (official description) is not a really helpful sentence to a beginner. What I know: Python is a language where you write down stuff, and then it just gets executed from top to bottom. There are classes and objects, but its still pretty much from top to bottom. There are also libraries, which you can use with include time for example. Those give you a bunch of extra functions, that you don't have to write yourself. Python code is saved in .py files. And now my question - is Django just a fancy python library, or is it an actuall programming language, which for some reason also uses .py files? And how does it work with the {{some_variable_name}} commands I write in my .html files? Is it also Django? Please (if this question does not get removed) pretend that I am really really stupid and know absolutely nothing aside from what I just wrote. Thanks in advance! More context: I have to use oTree, which is a piece of software for economic experiments. And while it is fairly … -
How to force permission check on overwritten post method of UpdateModelMixin?
I'm forced to write some messy work, I need to create partial_update view, however it must use POST method, because the software in the end does not use PUT/PATCH methods. Here are some assumptions: everything needs to be routed via DefaultRouter() in urls.py - that's why I'm using GenericViewSet must use POST method for updating one field - that's why I'm overwriting post() method of UpdateModelMixin instance.visible is a Boolean, which state is set to True as soon as the body is not empty. Update works, except the permission_classess which are ignored. It totally does not check the request for valid credentials. I think it's because I totally overwrote the post(), right? How do I force authentication check within the post method? urls.py: from django.urls import include, path from rest_framework import routers from browse.views import * router = routers.DefaultRouter() [...] router.register(r'update-article', UpdateArticleBodyViewSet) urlpatterns = [ path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework'),) ] views.py: class UpdateArticleBodyViewSet(mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer permission_classes = (permissions.IsAuthenticated, ) def post(self, request, pk): instance = get_object_or_404(Article, pk=pk) instance.body = request.data.get("body") if instance.body: instance.visible = True instance.save() serializer = self.get_serializer(instance=instance, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django - Nested loops and template rendering with Forms
Is there a way to set a variable after a return statement? I am trying to execute a for loop with a if clause. At first the if clause is False and after the for loop is executed completely it should render a template with a form and then set the variable to True afterwards. Then the for loop gets executed again but this time it should execute the if statement and submit the Form which is something like ("Are you sure?" and then Continue or Cancel). I tried it with using nested loops (for loop inside a while loop) but the return render statement to render the template with the request is not working with setting the variable afterwards. This is my views.py def file_upload(request): if request.method == "POST": # Wenn CSV Datei valide ist --> Datei hochladen csv_file = request.FILES['file'] csv_file.seek(0) decoded_file = csv_file.read().decode('utf-8').splitlines() reader = csv.reader(decoded_file) updated_list = list() created_list = list() s = False while (True): for row in reader: count += 1 try: datet = datetime.now().date() datum = datet.strftime("%d.%m.%Y") row[7] = datum row[8] = str(request.user) #d = [row[0], row[1], row[2], row[3], row[4]] dataset1 = CSV5.objects.filter(gebaeudebereich=row[0], gebaeudenummer=row[1], ebene=row[2], raum=row[3], dose=row[4])#.values_list("gebaeudebereich", "gebaeudenummer", # "ebene", "raum", "dose") dataset2 … -
django safe template filter customization
i'm using a rich text editor for users comments reply. but i need to limit html tags which users type in text editor for avoiding xss attacks. i know that safe template filter is best choice. but as a example i'd just accept some tags like <p>,<a>,<h3> not img,script,... . the problem is that safe filter accepts all of html tags. i'm looking for some thing like this: {{user.reply|safe:'<p>,<h3>,<a>'}} which reply is client's richtext html tags. and safe flter just accepts p,a,h3 tags. i,m using froala rich text editor and also i know to limit text editor options. but if user try to insert some <script> tag it can't undrestand. how can i customize safe filter? or which filter is more appropriate for this job? -
Match two profiles in Django framework
I made a web app which consists of two categories(let's say A and B) of users and there is a common board upon which they can both post something. Now if a person(John) from category A is suggested that his best match is person(wick) from category B by a django card, how can I make something that notifies both of them. Suppose JOHN like what WICK is offering and there is a book button he sees on WICK's card(mini profile). Now I want to notify Wick that JOHN is interested in you when JOHN clicks on the Book button. example data Manufacturer M_ID From To M_Type T_Type T_Length T_Weight #Trucks JOHN A B Boxes Open 12-Tyre 22 3 BLAKE C D Cylinders Trailer HIGH 23 2 GREG G H Scrap Open 14-Tyre 25 5 Transporter T_ID From To T_Type T_Length T_Weight #Trucks Price WICK A B Open 12-Tyre 22 5 1500 PATEL G H Open 14-Tyre 25 10 1200 NICK A B Open 12-Tyre 22 7 1900 The algo returns data in this format Manufacturer Best Match Second Best JOHN WICK NICK GREG PATEL - I can show JOHN that his best matches are WICK and NICK( and when he … -
Disabling options in django-autocomplete-light
Just started using django-autocomplete-light (autocomplete.ModelSelect2) and while I have managed to get it working, I wondered if it is possible to pass disabled options? I have a list of customers to choose from but some, for various reasons, shouldn't be selected they shouldn't be able to use them. I know I could filter these non-selectable customers out, but this wouldn't be very usable as the user might think that the customer isn't in the database. If so, could someone point me in the right direction as I'm not sure where to start. It says in the Select2 documentation that disabling options should be possible. Presumably if I could also send a 'disabled':true within the returned json response that might do it. -
How can i display different profile pictures in friends_list/followers_list, i am practicing django
My template {% for follow in my_followers %} <div class="col s12 m8 offset-m2 l6 offset-l3"> <div class="card-panel grey lighten-5 z-depth-1"> <div class="row valign-wrapper"> <div class="col s2"> <img src="{{user.appUser_set.all.0.avatar.url}}" alt="" class="circle responsive-img"> <!-- notice the "circle" class --> </div> <div class="col s10"> <span class="black-text"> {{follow }} <br> </span> </div> </div> </div> </div> {% endfor %} my views def followers(request): a = appUsers.objects.get(users=request.user) my_followers = a.follow_people.all() my_obj = appUsers.objects.all() return render(request, 'parsifal_users/followers.html', {'my_followers': my_followers, 'my_obj': my_obj}) My models: class appUsers(models.Model): users = models.OneToOneField(User, on_delete=models.CASCADE) profile_url = models.URLField() location = models.CharField(max_length=100) institution = models.CharField(max_length=100) avatar = models.ImageField( default='default.jpg', upload_to='profile_pics') follow_people = models.ManyToManyField( User, related_name='followed_by', blank=True) def __str__(self): return self.users.username Now how could i get display pictures of all the followers in this template any ideas or suggestions for the query?Thanks in advance!! PS:I am a begineer ,please also suggest some good reference and some good projects so that i could practice django successfully. -
Returning a dictionary from prepare_field
I'm setting up ElasticSearch, and would like to index multiple fields from a related object by name. How would you do this in a proper way? My index looks like this: class ArticleIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') updatedAt = indexes.DateTimeField(model_attr='updatedAt') date = indexes.DateTimeField(model_attr='date', null=True) description = indexes.CharField(model_attr='description') annotations = indexes.CharField(faceted=True) companies = indexes.MultiValueField(faceted=True) Now i would like to acces companies as a dictionary, so in my templates i could do something like: {% for comp in companies %} {{ comp.dnbNumber }} {{ comp.primaryName }} {% endfor %} So far i tried: def prepare_companies(self, obj): return [{company['dnbNumber'], company['primaryName'], company['cleanName']} for company in obj.companies.all() .values('dnbNumber', 'primaryName', 'cleanName')] def prepare_companies(self, obj): companies = [(company['dnbNumber'], company['primaryName'], company['cleanName']) for company in obj.companies.all() .values('dnbNumber', 'primaryName', 'cleanName')] return [{'dnbNumber': comp[0], 'primaryName': comp[1], 'cleanName':comp[2]} for comp in companies] If been searching google for answers but failed to find any. Any help is appreciated. Thank you in advance. P.S. I'm verry new to Elasticsearch -
why getting null values while posting the foreign keys(when i used slugrelatedfield in seializers to get foreign keys as string instead of integer)
This is my models.py class Product(models.Model): product = models.CharField(max_length=200) def __str__(self): return self.product class CustOrder(models.Model): CustomerName = models.CharField(max_length=200) email = models.EmailField(max_length=70,blank=True, null= True, unique= True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES) phone = PhoneField(null=False, blank=True, unique=True) landmark = models.PointField() #landmark = models.TextField(max_length=400, help_text="Enter the landmark", default='Enter landmark') houseno = models.IntegerField(default=0) #product_name = models.CharField(max_length=200, choices=PRODUCT_CHOICES,default='Boneless chicken') product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True,related_name='production') quantity = models.IntegerField(default=0) price = models.ForeignKey(Price, on_delete=models.SET_NULL, null=True,related_name='pricetag') #price = models.DecimalField(max_digits=50, decimal_places=5, default=48.9) pay_method = models.CharField(max_length=200,choices=PAYMENT_CHOICES, default='RAZOR PAY') city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) def __str__(self): return self.CustomerName This is my serializers.py class CustOrderSerializer(serializers.ModelSerializer): class Meta: model = CustOrder fields = '__all__' price = serializers.SlugRelatedField(read_only=True, slug_field='price') product = serializers.SlugRelatedField(read_only=True, slug_field='product') area = serializers.SlugRelatedField(read_only=True, slug_field='address') city = serializers.SlugRelatedField(read_only=True, slug_field='city')``` Actual result after posting: { "id": 7, "price": null, "product": null, "area": null, "city": null, "CustomerName": "tift", "email": "rkkk@gmail.com", "gender": "male", "phone": "(821) 699-7920, press 91", "landmark": "SRID=4326;POINT (0.04222869873046874 0.00102996826166618)", "houseno": 5, "quantity": 8, "pay_method": "cod" } Expected result after posting: { "id": 7, "price": 10, "product": chicken, "area": indiranagar, "city": banaglore, "CustomerName": "tift", "email": "rkkk@gmail.com", "gender": "male", "phone": "(821) 699-7920, press 91", "landmark": "SRID=4326;POINT (0.04222869873046874 0.00102996826166618)", "houseno": 5, "quantity": 8, "pay_method": "cod" } -
Mixin not working without any error - Django
I am trying to create a mixin for checking access token and some conditions. But it seem to be not working. Even i am using that accesstoken variable in TimesheetListApiV2 which is inside AccessTokenMixin. How can i access that variable inside my view. class AccessTokenMixin: def dispatch(self, request, *args, **kwargs): try: accesstoken=AccessToken.objects.get( token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '') ) if not accesstoken.application.company.company_tab_opts: return Response ( { "status" : False, "error" : "Tab Opts Error", "error_message":"You are not allowed to access it.", } ) return super().dispatch(request, *args, **kwargs) except ObjectDoesNotExist: return Response ( { "status" : False, "error" : "Wrong Access Token", "error_message":"You have provided wrong access token.", } ) class TimesheetListApiV2(AccessTokenMixin, APIView): def get(self, request): qs = User.objects.exclude( Q(userprofile__user_is_deleted = True) | Q(userprofile__user_company__company_is_deleted=True) ).filter( Q(userprofile__user_company =accesstoken.application.company) ) serializer = TimesheetListSerializer(qs, many=True) return Response ( { "status" : True, "message":"Timesheet Retrieved Successfully.", "result_count": qs.count(), "api_name" : "TimesheetListApiV2", "result": serializer.data, } ) -
when i click a post on my blog application, it should display date and time in url,but it doesnt get redirected to details.html
i have created a app on django, following the documentaries. I created base html, and then 2 more, list and detail respectively. list.html works fine, but when i click a post, it gets redirected to same page i have tried ordering the urls, but it doesnt work. models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self)\ .get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) urls.py for the app urlpatterns = [ url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), url(r'^$', views.post_list, name='post_list'), ] views.py def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) urls.py for main(mysite) app_name = 'blog' urlpatterns = [ url(r'^blog/', include('blog.urls')), url(r'^admin/', admin.site.urls), ] -
Target WSGI script '/var/www/backend/backend/wsgi.py' cannot be loaded as Python module
I'm deploying a Django web app on ubuntu server. Configuration are set. But, somehow, it show an 500 Internal Server Error. I checked the apache error log and found the following error entry : [Tue Mar 26 08:50:56.540300 2019] [wsgi:error] [pid 18832] [remote 27.61.32.236:42365] mod_wsgi (pid=18832): Target WSGI script '/var/www/backend/backend/wsgi.py' cannot be loaded as Python module. [Tue Mar 26 08:50:56.540376 2019] [wsgi:error] [pid 18832] [remote 27.61.32.236:42365] mod_wsgi (pid=18832): Exception occurred processing WSGI script '/var/www/backend/backend/wsgi.py'. [Tue Mar 26 08:50:56.540498 2019] [wsgi:error] [pid 18832] [remote 27.61.32.236:42365] Traceback (most recent call last): [Tue Mar 26 08:50:56.540542 2019] [wsgi:error] [pid 18832] [remote 27.61.32.236:42365] File "/var/www/backend/backend/wsgi.py", line 12, in <module> [Tue Mar 26 08:50:56.540553 2019] [wsgi:error] [pid 18832] [remote 27.61.32.236:42365] from django.core.wsgi import get_wsgi_application [Tue Mar 26 08:50:56.540584 2019] [wsgi:error] [pid 18832] [remote 27.61.32.236:42365] ImportError: No module named 'django' I have tried the solutions for the same error found on stackoverflow. Is there anything I'm still missing on these configurations ? Apache Configuration Listen 8000 <VirtualHost *:8000> WSGIDaemonProcess backendapp python-home=/var/www/backend/venv python-path=/var/www/backend WSGIProcessGroup backendapp WSGIPassAuthorization On WSGIScriptAlias / /var/www/backend/backend/wsgi.py ErrorLog /var/www/backend/error.log CustomLog /var/www/backend/access.log combined </VirtualHost> wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings") application = get_wsgi_application() using python 3.6 and mod_wsgi is enabled on server. -
Getting an assertion error while views testing using invalid data in django
I am testing my webapp by developing testcases using invalid data. Everything runs fine except for an assertion error that is bugging me a lot. I am trying to prevent a suer from registering if a same email id like his exists. In such a case, the same form will be rendered with the context as errors.(Check the code written below). But it keeps on showing an assertion error. Here is my code: Here is my views.py: def register(request): if request.method == 'POST': user_form = CustomUserCreationForm(data=request.POST) if user_form.is_valid(): ob = CustomUserCreationForm.register(user_form) if ob.is_active is False and ob.is_staff is False: return render(request, 'todoapp/waiting.html') else: return render(request, 'todoapp/admin_success.html') else: return render(request, 'todoapp/register.html', {'errors': user_form.errors}) return render(request, 'todoapp/register.html', {'form': CustomUserCreationForm()}) Here is my urls.py: url(r'^register/', views.register, name='register'), Here is my tests.py: sent_data = { 'first_name': 'john', 'last_name': 'doe', 'email': 'johndoe@gmail.com', 'password': 'johndoe' } response = self.client.post(url, sent_data) self.assertEqual(response.status_code, 200) expected_data = { 'email': 'User with this Email already exists.' } self.assertEqual(response.context['errors'], expected_data) Here is the error: self.assertEqual(response.context['errors'], expected_data) AssertionError: {'email': [u'User with this Email already exists.']} != {u'errors': {u'email': u'User with this Email already exists.'}} -
Designing a multi-type user webapp in django
Im building a webapp in django and really beating myself over the design im going to use. This is a big project and it needs to be scalable and so the design is critical. My app will have two main types of users, each of them have to see some similar elements, but their 'Flow' through the website and the interaction with it should be different depending on the user type. I read the answer here and considered using this skeleton project. But non of them address the fact that I have 2 different types of users. And so my question is: is it best practice to have a user/profile app, then app for each one of the entities. or on the other hand have a user app that contains all user related and have user groups deciding which kind of user it is, then the main app will decide which flow to show the user depending on its group. Any other design best practices will be great. -
How to pass more than one parameter from views.py to forms and get them in forms.py in django 2.1.7?
I am new to Django and I am trying to add comments for a post in a blog in Django 2.1. When I want to add comments to a post, I need to save the user who adds the comments and post_id with that comment. I defined my comment model with relations to post and user models. I used init() method for CommentForm and get the post_id, but I can't get user_id similarly in forms.py. Is it possible to pass more than one parameter from views.py and pass it to form and get them in that form to save to that table? Here is the code which I wrote for doing above functionality: veiws.py My method for creating comments: def details(request, id): instance = get_object_or_404(Post, id=id) post_data = request.POST.dict() if request.method == 'GET': form = CommentForm(request.POST or None, request.FILES or None) if request.method == 'POST': form = CommentForm(request.POST or None, request.FILES or None, post=instance.id) if request.method == 'POST': print(request.user.id) if request.user: user = request.user.id form = CommentForm(request.POST or None, request.FILES or None, create=user) forms.py In my CommentForm I have following method: def __init__(self, args, *kwargs): post = kwargs.pop('post', '') super(CommentForm, self).__init__(*args, **kwargs) if post: self.fields['post_name'] = forms.ModelChoiceField(queryset=Post.objects.filter(pk=post)) def __init__(self, args, … -
Pip install multiple packages fails when each other have dependencies
I'm using Heroku as a development server. When I try to push my Django application to Heroku it first tries to install my packages from the requirements.txt file. requests==2.18.3 ssh-import-id==5.5 The problem is I have a dependency on one of my packages with others. In the above packages, ssh-import-id needs requests package already installed. So when I push the app, pip fails to install and stops the deployment. Collecting requests==2.18.3 (from -r re.txt (line 1)) Using cached https://files.pythonhosted.org/packages/ba/92/c35ed010e8f96781f08dfa6d9a6a19445a175a9304aceedece77cd48b68f/requests-2.18.3-py2.py3-none-any.whl Collecting ssh-import-id==5.5 (from -r re.txt (line 2)) Using cached https://files.pythonhosted.org/packages/66/cc/0a8662a2d2a781db546944f3820b9a3a1a664a47c000577b7fb4db2dfbf8/ssh-import-id-5.5.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-go0a5mxf/ssh-import-id/setup.py", line 20, in <module> from ssh_import_id import __version__ File "/tmp/pip-install-go0a5mxf/ssh-import-id/ssh_import_id/__init__.py", line 25, in <module> import requests ModuleNotFoundError: No module named 'requests' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-go0a5mxf/ssh-import-id/ I need to install all the listed packages using pip in single attempt. Because by default Heroku runs, pip install -r requirements.txt. -
Django forms dynamic getting author as a logged in user in model forms
I'm trying to make some forms that will allow users to add some objects, delete them or edit but I've stucked with thing like author of model. Let's say we got model Shot which got field author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and then we creating modelForm, creating views etc. and finally got form. When we will try to submit this form, it won't add this object submited in form to db because form has no filled field author author which means this field == Null and that's why it won't add this to db. So my question is how to get it dynamic, for example when user with nick "thebestuser" will try to add this modelForm it will work and mark author as "thebestuser"? Ofc I could add to form field author, but it's the worst way in my opinion and every user would be allowed then to add object for example as a another user, let's say user with nick "anothernick" could add form as a user with "thebestuser" which is In my opinion not acceptable. models.py from django.db import models from django.contrib.auth.models import User from streamers.models import Streamer from django.conf import settings from django.utils import timezone class Shot(models.Model): author … -
when i type my domain name it will give only public html files
i have tried to change my old domain to a new domain on the same website's file , but now i get only public html files (index of) , and when i try to put my old domain it will show the same error , is it possible to change a domain name for a website i want to change a domain to another note : i used django web framework my application worked fine before i decide to change its domain name and i changed $ALLOWED_HOST = ['new domain'] [enter image description here][1] -
serializer.is_valid() works with integer fields but serializer.save() asks for model instance
I have a many-to-many relationship in ma database (PK are integers). I auto-generated django models from the db and implemented the simplest serializer. When I give a dictionary with integers to the serializer, serializer.is_valid() returns True, but serializer.save() says fields should be models instances. But when I give a dictionary with models instances, serializer.is_valid() returns False. data = {'tag_id': 9, 'spending_id': 17} serializer = TagspendingSerializer(data= data) serializer.is_valid() True serializer.save() => ValueError: Cannot assign "9": "Tagspending.tag_id" must be a "Tag" instance. data = {'tag_id': Tag.objects.get(tag_id= 9), 'spending_id': Spending.objects.get(spending_id= 17)} serializer = TagspendingSerializer(data= data) serializer.is_valid() => False Here's my model : class Tagspending(models.Model): tag_id = models.ForeignKey(Tag, models.DO_NOTHING, db_column='tag_ID', primary_key=True) spending_id = models.ForeignKey(Spending, models.DO_NOTHING, db_column='spending_ID') class Meta: managed = True db_table = 'TagSpending' unique_together = (('tag_id', 'spending_id'),) Here's my serializer : class TagspendingSerializer(serializers.ModelSerializer): class Meta: model = Tagspending fields = ('tag_id', 'spending_id') -
Explain the hitcount library
I Set up hitcount but could not understand or use it and could not understand the explanation on its site All I want is a detailed explanation of how to use, for example After installation What do I do if I want to calculate specific pageviews? What 's Added in model. What' s Added in views I did not understand all this possible detailed explanation -
Django. How to make search?
I need to do a search by region. In the model, the region has a foreignkey field. Can you please tell me how to do a search? views.py: def search(request): context = { } return render(request, 'listings/search.html', context) It's main model: class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риелтор') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область') city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город') district = models.ForeignKey(District, on_delete=models.CASCADE, verbose_name='Район') Template: <div class="form-row"> <div class="col-md-4 mb-3"> <label class="sr-only">Region</label> <select name="region" class="form-control"> <option selected="true" disabled="disabled">Region</option> <option value=""></option> </select> </div> <div class="col-md-4 mb-3"> <label class="sr-only">City</label> <select name="city" class="form-control"> <option selected="true" disabled="disabled">City</option> <option value=""></option> </select> </div> <div class="col-md-4 mb-3"> <label class="sr-only">District</label> <select name="district" class="form-control"> <option selected="true" disabled="disabled">District</option> <option value=""></option> </select> </div> </div> -
Django form not saving at all
I have registered the form in the admin page put the form data doesn't save only the name of the class shows in the admin page. this is my views.py def details_investor_business(request): Invest_form=Investor_form(request.POST) business_form=Business_owner_form(request.POST) if Invest_form.is_valid(): iform=Invest_form.save() if business_form.is_valid(): bform=business_form.save() context={} context['Iform']=Invest_form context['Bform']=business_form return render(request,'detail.html',context) forms.py class Investor_form(forms.ModelForm): class Meta: model=Investor_Registration fields=("__all__") models.py class Investor_Registration(models.Model): investor_fullname=models.CharField(default="Jon Samuel",max_length=50,null="True") Address=models.TextField(default='Resendential Address') Age=models.IntegerField() Gender=models.CharField(choices=gender,max_length=50) Figi_Username=models.CharField(default='Figi Username',blank=True,max_length=50) Next_of_Kin=models.CharField(default='Next of kin Name',max_length=50) Next_of_Kin_Address=models.TextField(default='Address of Next of kin',max_length=100) Bank_Name=models.CharField(default='GTB',max_length=50) Bank_Type=models.CharField(choices=typeBank,max_length=50) def __str__(self): return(self.investor_fullname, self.Address,self.Age,self.Gender,self.Figi_Username,self.Next_of_Kin,self.Next_of_Kin_Address,self.Bank_Name,self.Bank_Type)