Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect to created post after form
I want to redirect to the post i actually created. So i have form, that added a post to the website, and after submit form i would like to redirect to this post. This is my urls urlpatterns = [ path('', views.home, name='home'), path('detail/<int:pk>/', views.detail, name='detail'), path('form/', views.formularz, name='formularz'),] and my views : def formularz(request): form = NewJobForm(request.POST) if form.is_valid(): firma = form.save(commit=False) firma.save() return redirect('search:home') else: firma = NewJobForm() context = { 'form': form, } return render(request, 'search/home-form.html', context) I understand how redirect is working, but have no idea how to redirect to the int:pk page -
Invalid block tag on line 10: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? django (python)
I want registration and log in form in same page and in same html file. when i render form1 i have problem. i search in google but can't fix. can i render two form same html? this is code ---> {% extends 'base.html' %} <link rel="stylesheet" type="text/css" href="/static/css/style.css?{% now "U" %}" /> {% block content %} <form action = '' method="post" novalidate="novalidate" id="reg" > {% csrf_token %} <div class="continer"> {% for field in form %} {{ field.label_tag }} {{ field }} {{ field.errors }} {% endfor %} <button type="submit" name="register" id="btn" >registraton</button> <button type="button" name="log" id="lgn">login</button> </div> </form> <form action="" method="post" novalidate="novalidate" id="log"> {% csrf_token %} <div class="continer2"> {% for field in form1 %} {{ field }} </div> </form> {% endblock %} -
Getting 'foreign key mismatch' error when making migrations in Django model
I have a model Game as such (I am defining PK field because I am populating this table through API calls that come with a gameID): class Game(models.Model): gameId = models.IntegerField(primary_key=True, default=-1) season = models.PositiveIntegerField() season_type = models.CharField(max_length=50) dateTime = models.DateTimeField(auto_now_add=True) ... ... and a model GameOdd as such: class GameOdd(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) sportsbook = models.CharField(max_length=75) created_when = models.DateTimeField(auto_now_add=True) ... ... The error message says "foreign key mismatch - "bets_gameodd" referencing "bets_game" " (bets is the name of the app). I am using a sqlite db, and it is empty (aside from my admin user profile). This seems like a relatively straightforward foreign key relationship, and I am defining the parent table first. I am perplexed as to why I am getting this error. Any ideas? -
How to run "python manage.py collectstatic" in .cpanel.yml to deploy Django?
I'm trying to set up pull autodeployment for a django-wagtail project and to my best awareness, it should consist of just two commands: git pull python manage.py collectstatic The "update from remote button" seems to do first line and "deploy head commit" seems to run whatever is in .cpanel.yml file; I'm following this tutorial for automating git deployments in cpanel : https://docs.cpanel.net/knowledge-base/web-services/guide-to-git-deployment/ But these instructions in it : - export DEPLOYPATH=/home/user/public_html/ - /bin/cp index.html $DEPLOYPATH - /bin/cp style.css $DEPLOYPATH aren't the same as running python manage.py collectstatic - and neither are these: - export DEPLOYPATH_STATIC=/home/fpgsanct/public_html/static/ - export DEPLOYPATH_MEDIA=/home/fpgsanct/public_html/media/ - /bin/cp -R static $DEPLOYPATH_STATIC - /bin/cp -R media $DEPLOYPATH_MEDIA So I've tried the following (separately): - python manage.py makemigrations - /home/username/virtualenv/projectname/3.7/bin/python /home/username/projectname/manage.py makemigrations But each time it just froze at "quequed" for more than 5 minutes (it's done in a few seconds with any other commands) so I figured I must be doing something wrong -
AttributeError - response' object has no attribute 'setdefault'
I'm trying to make a post request to a third party api, and I'm getting the following error AttributeError - response' object has no attribute 'setdefault' This is my function @csrf_exempt def uploaddd(request): document = { "value": [ { "@search.action": "upload", "HotelId": "1", "HotelName": "Secret Point Motel", "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York.", "Category": "Boutique", "Tags": [ "pool", "air conditioning", "concierge" ], "ParkingIncluded": 'false', "LastRenovationDate": "1970-01-18T00:00:00Z", "Rating": 3.60, } ] } headers = {'Content-Type': 'application/json', 'api-key': 'key'} endpoint = 'https://service.search.windows.net/indexes/hotels/docs/index?api-version=2020-06-30'; res = requests.post(endpoint, headers, document) return res -
Django cross site corruption?
I've a development and production site for an application. The development site is at development.site-name.org.uk and the production site at site-name.co.uk. Please note one is .org.uk and one is .co.uk so it is not (I think a sub-domain name issue). I have some banner functionality which presents a banner to the user if they haven't seen it before. I do this in context_processors.py as follows def popup_banners(request): context = {} banners = request.session.get('banners', []) context['BANNERS'] = Banner.objects.filter(is_active=True).exclude(id__in=banners) return context I am getting the banner from the development site showing on production which means context['BANNERS'] is picking up something from the development database and showing it in production. I do not understand how this can happen and my users have been unable to give me a sequence of events they're following which results in this. What could be causing this cross site contamination -
How to convert hour into seconds?
Here For example if the object has hour as 4hr then I want to convert in seconds which should be 14400. HOURS = ( ('1', '1 hrs'), ('2', '2 hrs'), ('4', '4 hrs'), ('6', '6 hrs'), ('12', '12 hrs'), ('24', '24 hrs'), ) hour = models.CharField(max_length=5, choices=HOURS) views.py obj = MyModel.objects.get(pk=pk) hour = obj.hour # now i Want to convert into seconds. total_seconds = hour.total_seconds() ?? -
Filter a model in Django Restframework serializer
I am setting up a Django REST application where peopple can review restaurants. So far I have those serializers: class RestaurantIdSerializer(serializers.ModelSerializer): class Meta: model = RestaurantId field = fields = '__all__' class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = RestaurantReview field = fields = '__all__' class StarterPicsSerializer(serializers.ModelSerializer): class Meta: model = StarterPics fields = '__all__' def validate_restaurant_review_id(self, value): if value.review_author != self.context['request'].user: raise serializers.ValidationError("User has not reviewed the restaurant") if RestaurantReview.objects.filter(id=value.id, restaurant_id=value.restaurant_id).exists(): return value raise serializers.ValidationError('Not the right restaurant') class RestaurantId(models.Model): maps_id = models.CharField(max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) My models: class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StarterPics(models.Model): restaurant_review_id = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) pics_author = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) name_1 = models.CharField(max_length=40) picture_1 = models.ImageField() So what I need is that if the author is not the author of the review he can't POST any pictures in StarterPics. This part of my validation is working fine. But I also need to be sure that even if the User is the author of the review he can't change the restaurant_id and POST the picture with another restaurant_id. The second part of validate_restaurant_review_id doesn't work because the User can POST … -
What is the best site to find and recruit full stack developers? [closed]
Looking for a full stack developer / jack of all trades who is fluent in Objective C, Java, Python and Django for iOS and Android applications, and am just wondering what the best site to recruit such a developer might be. Thanks for any help. -
Paginator no funciona para la primera pagina (Django)
Estoy haciendo un proyecto con Django y estoy aprendiendo a usar pagination, pero tengo un problema y es que cuando limito el numero de elementos que muestra por página lo hace para todas menos la primera. Por ejemplo si tengo 500 elementos y quiero mostrar 100 en cada páagina, me crea por ejemplo 3 páginas, la segunda y la tercera con 100 elementos y en la primera me muestra el resto (mas de 100) . No se que me estará faltando para que la primera tambien se limite views.py qs_vlan = qs_vlan.filter(area=vlan_name) parametros = request.GET.copy() if parametros.__contains__('page'): del parametros['page'] page = request.GET.get('page') paginator = Paginator(qs_vlan, 100) try: vlan = paginator.get_page(page) except PageNotAnInteger: vlan = paginator.get_page(1) except EmptyPage: vlan = paginator.get_page(paginator.num_pages) return render(request, 'data.html', {'qs_vlan': vlan, 'page':page, 'parametros':parametros}) data.html {% if qs_vlan.has_other_pages %} <nav> <ul class="pagination justify-content-center" style="margin-top:20px;"> {% if qs_vlan.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ qs_vlan.previous_page_number }}&{{ parametros.urlencode }}">&laquo;</a></li> {% else %} <li class="page-item disabled"><span class="page-link">&laquo;</span></li> {% endif %} {% for i in qs_vlan.paginator.page_range %} {% if qs_vlan.number == i %} <li class="page-item active"><span class="page-link">{{ i }}<span class="sr-only">(current)</span></span></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}&{{ parametros.urlencode }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if qs_vlan.has_next … -
How to automatically create user profile for new users that register to the platform in Django
I have created a models file with custom user model and employeeProfile with details for the employee profile, a signal file to automatically create a profile for new user. Although i have set this up, new users profile is not created automatically forcing me to add them manually in the admin page. Kindly assist with a solution. models.py file looks like this (...) # imports class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField( default=datetime.now, blank=True) # To add then run migrations objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] # email is already required, no need to add def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email CustomUserManager file class CustomUserManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user def create_superuser(self, email, name, password): user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user Signal.py file (...) # other imports from django.contrib.auth import get_user_model User = get_user_model() @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: employeeProfile.objects.create(user=instance) -
Django RF. How can I have two models in a single api view or in a serializer with a foreign key
Hey guys I am completely new in django rest framework, I have this post and postimages model which has a foreign key relation with post, this is in normal django, a formset where we can upload multiple images. How can I do a similar thing with django rf? I have this serializer, how do I implement this relation? also in the detail view, only the image which is in the post model is showing and is completely ignoring the postimage model. Can someone show an example or point to a simple source where it is easy to understand? these are the codes: class PostSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') post_date = serializers.ReadOnlyField() class Meta: model = Post fields = ['id','title', 'post_date', 'updated', 'image', 'slug', 'user',] # the image in this field is of Post model class PostImageSerializer(serializers.ModelSerializer): post = serializers.ReadOnlyField() class Meta: model = PostImage fields = ['post', 'image',] # in django this is a formset def create_post_api_view(request): user = request.user post = Post(user=user) serializer = PostSerializer(post, 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) def detail_post_api_view(request, slug): try: post = Post.objects.get(slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = PostSerializer(post) return Response(serializer.data) Thanks -
How to hide Celery task id from structlog?
I used Structlog and Celery in my Django application and both work very well, but I would like to prevent task_id from appearing in the log when the worker executes tasks. How can I do that? The reason is that task_id is a key:value of 36 characters long so it makes log output hard to read. 2020-07-23 14:20:00.052156 [info ] Update started [data.tasks] task_id=b79c9b3b-ae4b-41c6-951a-72b4f19fa2ac 2020-07-23 14:20:01.659316 [info ] Update complete [data.models] exchange=aaa new=0 task_id=b79c9b3b-ae4b-41c6-951a-72b4f19fa2ac time=0.42 update=0 2020-07-23 14:20:01.936658 [info ] Update complete [data.models] exchange=bbbbbb new=0 task_id=b79c9b3b-ae4b-41c6-951a-72b4f19fa2ac time=0.03 update=0 2020-07-23 14:20:02.451733 [info ] Update complete [data.models] exchange=hhh new=0 task_id=b79c9b3b-ae4b-41c6-951a-72b4f19fa2ac time=0.28 update=0 This is how my structlog setup for Celery: structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S.%f"), structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), structlog.processors.ExceptionPrettyPrinter(), structlog.stdlib.ProcessorFormatter.wrap_for_formatter, ], context_class=structlog.threadlocal.wrap_dict(dict), logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True, ) @receiver(signals.modify_context_before_task_publish) def receiver_modify_context_before_task_publish(sender, signal, context): keys_to_keep = {"request_id", "parent_task_id"} new_dict = {key_to_keep: context[key_to_keep] for key_to_keep in keys_to_keep if key_to_keep in context} context.clear() context.update(new_dict) Thank you -
How to use different database within same app in django (3.0.4)
I want to save models in different databases but it is not working for me my settings.py file DATABASE_ROUTERS = ['path.to.DemoRouter'] DATABASE_APPS_MAPPING = {'user_data': 'users_db', 'customer_data':'customers_db'} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'users_db': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres_user', 'PASSWORD': 'password' }, 'customers_db': { 'NAME': 'customer_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_cust', 'PASSWORD': 'root' } } my routers.py file class DemoRouter: """ A router to control all database operations on models in the user application. """ def db_for_read(self, model, **hints): """ Attempts to read user models go to users_db. """ if model._meta.app_label == 'user_data': return 'users_db' elif model._meta.app_label == 'customer_data': return 'customer_db' return None def db_for_write(self, model, **hints): """ Attempts to write user models go to users_db. """ if model._meta.app_label == 'user_data': return 'users_db' elif model._meta.app_label == 'customer_data': return 'customer_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the user app is involved. """ if obj1._meta.app_label == 'user_data' or \ obj2._meta.app_label == 'user_data': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'users_db' database. """ if app_label == 'user_data': return db == 'users_db' return None my models.py file class … -
django data render to JavaScript to make a map polyline with latitude and longitude
I have a model named MapLocation and inside MapLocation model i have few attributes such as packageid, location_name, latitude and longitude. My goal is to build a map polyline using Lifletjs. for this i need fetch latitude and longitude and render them to template to use lat lng in javascript file. i have multiple lat lng for a specific tour package and i need to run a for loop for this. Here is my views code: from django.shortcuts import render from .models import MapLocation from django.core import serializers import json from django.http import HttpResponseRedirect, HttpResponse from django.core.serializers.json import DjangoJSONEncoder # Create your views here. def showthis(request): json_res = serializers.serialize('json',MapLocation.objects.filter(package_id=1),fields= ('latitude','longitude')) context= {'all_objects': json_res} return render(request, 'test.html', context) I used serializer to render data in json format, here is my javascript Template code var js_list = "{{all_objects|escapejs}}"; var myJSONList = (("{{all_objects}}").replace(/&(l|g|quo)t;/g, function(a,b){ return { l : '<', g : '>', quo : '"' }[b]; })); myData = JSON.parse( myJSONList ); console.log(myData); after writing these code i get all my data in console, like the layout given below Now i want to for loop latitude and longitude in here to create a polyline on Map. var js_list = "{{all_objects|escapejs}}"; var myJSONList = … -
Django form populating with model data no longer working
I have something which is confusing me. I have the below form, which was working until I populated the dropdown with data from a model. Now, whenever it passes through the view, it doesn't pickup the field value, rather it just passes right through and returns 'unknown' - which means I guess, it didnt think the form was valid. Any ideas??? Forms.py from django import forms from .models import * class UploadFileForm(forms.Form): title = forms.ModelChoiceField(queryset=projects.objects.values_list('project_name', flat=True)) file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) views.py def upload_file(request): title='unknown' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data.get('title') version = 1 exists = 0 while exists == 0: filepath = 'rrls/media/upload/' + str(title) + '/' + str(version) + '/' if os.path.exists(filepath) == False: exists = 1 else: version = version + 1 version = str(version) filepath = 'rrls/media/upload/' + str(title) + '/' + str(version) + '/' for file in request.FILES.getlist('file_field'): chunks = [] if not os.path.exists(filepath): os.makedirs(filepath) with open(filepath + str(file), 'wb+') as destination: for chunk in file.chunks(): chunks.append(chunk) destination.write(chunk) return render(request, 'index.html', {'title':title}) Models.py class code(models.Model): project_name = models.CharField(max_length=400, default="none") description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') #derive filename and extension uploaded_at = models.DateTimeField(auto_now_add=True) -
use database of backend pipeline for data retrieval in Django
The django project uses one default database (with users, content-types etc)..I have another database where the ETL pipeline dumps data. I want this data to be displayed on the django website. The developers dealing with the pipeline may dynamically change the pipeline database's table schema. What is the best design to solve this problem? -
Method Not Allowed (POST): /password_change_done
i am new to django/python i am trying to change user password but i am getting error Method Not Allowed (POST): /password_change_done Method Not Allowed: /password_change_done [23/Jul/2020 19:11:05] "POST /password_change_done HTTP/1.1" 405 0 this is my url patterns just for password changes : path('password_change', auth_views.PasswordChangeView.as_view(template_name='password_change.html'), name='password_change'), path('password_change_done', auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'), name='password_change_done'), both my html pages for this operation my html code: password_change {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome</title> </head> <body> <h3> Change Password</h3> <form action="{% url 'password_change_done' %}" method="POST" class="form-signin">{% csrf_token %} <input name="Old password" class="form_control" placeholder="Old password" type="password" id=old_password required="true"> <input name="new password" class="form_control" placeholder="new password" type="password" id=new_password required="true"> <input name="confirm password" class="form_control" placeholder="confirm password" type="password" id=confirm_password required="true"> <button type="submit">Update</button> </form> </body> </html> my html code for password_chang_done: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome</title> </head> <body> <h1>Welcome</h1> <h2> <img src="{% static 'images/welcome.jpg' %}"> </h2> <h5>hello,{{request.user.username}}</h5> <script> window.alert("password sucessfully changed") </script> </body> </html> -
Chart.js or Matplotlib
I am building a web application with django. I have matplotlib plots in the backend which I want to render to the front end. But my question is should I use chart.js to make things easier and easily render backend data to the front end. -
Need to implement personal and matching horoscope api [closed]
i want to create api's to get personal horoscope(weekly,today,tomorrow),and matching horoscope for girl and boy for marrige.Someone guide me how can get done,as i am not getting relevent related to this. -
Django - TypeError at /uploaddd unhashable type: 'dict'
I'm trying to return the document object as json when I hit the function upload. I'm getting the following error TypeError at /uploaddd unhashable type: 'dict' This is the function def uploaddd(request): documents = { { "@search.action": "upload", "HotelId": "1", "HotelName": "Secret Point Motel 2020", "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", "Description_fr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", "Category": "Boutique", "Tags": [ "pool", "air conditioning", "concierge" ], "ParkingIncluded": "false", "LastRenovationDate": "1970-01-18T00:00:00Z", "Rating": 3.60, "Address": { "StreetAddress": "677 5th Ave", "City": "New York", "StateProvince": "NY", "PostalCode": "10022", "Country": "USA" } }, } return JsonResponse({'doc': documents }) The issue is the latest entry the the object "Country": … -
Runserver at django some problems
PS C:\Users\Manthan Sharma\PycharmProjects\Django> python manage.py runserver enter image description here C:\Users\Manthan Sharma\AppData\Local\Programs\Python\Python38-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory PS C:\Users\Manthan Sharma\PycharmProjects\Django> -
drf model permissions in custom viewset
at the moment i have a custom view for example: class CustomViewSet(RevisionMixin, viewsets.ViewSet): def create(self, request): ... For example in the create function i create an object from the custom model. But drf dont check the model permissions for the requested user. I fix that with custom permission: class CustomPermission(permissions.BasePermission): def has_permission(self, request, view): if view.action == 'list': return request.user.has_perm('custom_app.add_custom') return False class CustomViewSet(RevisionMixin, viewsets.ViewSet): permission_classes = [IsAuthenticated, CustomPermission] def create(self, request): ... Now i must do that for all actions. Is there a better and easier way to do that? -
IntegrityError: NOT NULL constraint failed (extending default User model)
I am getting this error: django.db.utils.IntegrityError: NOT NULL constraint failed: new__auctions_user.watchlist_id I registered 1 user before extending with the Person class, could that be why? ''' class User(AbstractUser): pass class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) watchlist = models.ManyToManyField('Listing') ''' -
Required technologies for a web chat application [closed]
If you try to create an advanced real-time chat application with Django, what technologies are required to do so ? I mean very advanced chat application with 100k online users. It needs to work via API (because the main application is already created for Android)