Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django seo optimization
How to do django seo optimization.The rollyourownseo is not supported in the latest version. -
How to pass variable of checked table rows in template to view and create multiple data in django db?
Basically I have three tables in my models: 1) Delegates - storing all delegates 2) Events - storing all events 3) EventDelegate - relation between delegate and event (which delegate is registered for which event) The delegates table is displayed in a template of each event that also contains the event and i hav put a checkbox beside each row to save the checked row and send the ids of all checked rows to the view function so that i can insert the ids of delegates with loop into the EventDelegate table along with the same eventid (it will remain same for each row because i am sending data from each event page). So finally i should be able to check the delegates from the list of all for each event page and clicking on submit will add their IDs along with the event id to the EventDelegate Table. I have did something but is not working the way it should, sharing my work till now:- models.py ... class EventDelegate(models.Model): event = models.ForeignKey(Event, on_delete=models.DO_NOTHING) delegate = models.ForeignKey(Delegate, on_delete=models.DO_NOTHING) template.html <form action="/register-delegates" method="POST"> {% csrf_token %} <table id="myTable2" class="table table-striped table-bordered" style="width:100%"> <thead class="thead-light"> <tr> <th scope="col"></th> <th scope="col">#</th> <th scope="col">Name</th> … -
django.db.utils.IntegrityError: - error persists
this question has been discussed and answered here, however the error is persisting for me. As I don't have enough reputation I cant comment in that discussion yet. I have followed the responses to remove on_delete=models.SET_DEFAULT and default=1 to run the initial migrate, however I receive the following error: tutorial_category = models.ForeignKey(TutorialCategory,verbose_name="Category", null=True) TypeError: init() missing 1 required positional argument: 'on_delete' I'm assuming it needs the 'on_delete' field, and have tried on_delete.PROTECT and CASCADE, however this brings the original error: "django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value 'tutorial_series_id' that does not have a corresponding value in main_tutorialseries.id." I am using Django 2.2.9, any help on how to set up Foreignkeys would be appreciated. thanks! -
django "only()" method seems not to work properly
Models.py class Post(models.Model): id = models.IntegerField(default=0) name = models.CharField(max_length=200, default='', blank=True) click = models.IntegerField(default=0) content = models.CharField(max_length=200, default='', blank=True) Below, what I coded post = Post.objects.filter(id=3).only('name') print(post.values()) Result what I expected <QuerySet [{'name': 'Micheal'}]> But the actual result was <QuerySet [{'id': 3, 'name': 'Micheal', 'click': 2, 'content': 'asdf'}]> How can I fix the problem? -
Django Swagger 2.2 + Django REST API + Uploading file so to get browse option
I am attaching code... models.py: class File(models.Model): file = models.FileField(blank=False, null=False) print("wat is the name",file) def __str__(self): return self.file.name serializers.py: class FileSerializer(serializers.ModelSerializer): #file = serializers.FileField(use_url=False) class Meta: model = File fields = "__all__" views.py: `class MyModelView(generics.ListAPIView): parser_classes = (MultiPartParser,FormParser) serializer_class = FileSerializer @action(detail=False, methods=['post'], name='Uploader View', parser_classes=[multipartparser],) @api_view(['POST']) def post(self, request, *args, **kwargs): """ Create a MyModel --- summary: Uploads a file. requestBody: content: multipart/form-data: consumes: - multipart/form-data parameters: - in: formData name: file "paramType": "formData", "dataType": "file", type: File responseMessages: - code: 201 message: Created """ file_serializer = FileSerializer(data=request.data) return Response(file_serializer.data, status=status.HTTP_201_CREATED) ` Please tell me what changes are required in my code!!! Thank you. -
Django profile form not hitting the database
I am running a Django Application. views.py: @user_passes_test(lambda u: u.is_anonymous) def signup(request): if request.method=='POST': user_form = UserForm(data=request.POST) profile_form = ProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user=user response = {'status':'success','message':'Registered Successfully'} return JsonResponse(response,safe=False) elif user_form.errors: ress = {'status':'Failed','message':'Username already Exists'} return JsonResponse(ress,safe=False) elif profile_form.errors: resss = {'status':'Failed','message':'mobile number already Exists'} return JsonResponse(resss,safe=False) forms.py : class UserForm(forms.ModelForm): username=forms.CharField(widget=forms.PasswordInput) password=forms.CharField(widget=forms.PasswordInput) class Meta(): model=User fields=('username','password') class ProfileForm(forms.ModelForm): class Meta: model=Profile widgets = { 'address_line_1': forms.TextInput(attrs={'placeholder': 'Door No,Building'}), 'address_line_2': forms.TextInput(attrs={'placeholder': 'Area,Locality'}), } fields=('first_name','last_name','mobile_no','email','address_line_1','address_line_2','postal_code','city','country') user_form is hitting the database, but profile_form is not hitting the database.If i register with the same mobile_no 2 times, it is showing "Registered successfully" message. -
NoModuleFoundError- Django
My default python is Anaconda in the path : C:\users\programdata\anaconda. I checked marked yes to make it default python during installation. So the path for this anaconda is set to my environment variable path too. Later I installed normal python (python.org) in the path : C:users\Megha\Python38 My django is installed in Site-packages inside the lib folder of Anaconda (C:\users\programdata\anaconda\lib\site-packages\django) I opened the python interpretor inside normal python path (C:users\Megha\Python38) When I try to import django there, it was throwing NoModuleErrorFound Error. How I tried to fix it. Open the python interpretor (path - C:users\Megha\python38) Tried to append the path where django is installed to my current sys.path import sys sys.path.append("C:\users\programdata\anaconda\lib\site-packages\django") Still the same error showed. So I made virtual environment and then did pip install django. It worked. But what if I don't want virtual environment. I want to import django from anaconda path?? -
ValueError: Filename must be a string while uploading file to s3 bucket
I am sending an excel file as a request in postman and need to upload this to s3 . I access the file from request and send it to s3. @api_view(['POST']) def excel_upload(request): print("request", request) excel_file = request.FILES['file'] print("excel_file", excel_file) upload_to_aws(excel_file,'X1excelsheets','s3_file_name') and here is the function to upload file to s3. def upload_to_aws(local_file, bucket, s3_file): s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) try: s3.upload_file(local_file, bucket, s3_file) print("Upload Successful") return True except FileNotFoundError: print("The file was not found") return False except NoCredentialsError: print("Credentials not available") return False uploaded = upload_to_aws('local_file', 'bucket_name', 's3_file_name') I am trying to use this particular post https://medium.com/bilesanmiahmad/how-to-upload-a-file-to-amazon-s3-in-python-68757a1867c6 to get things done . Error:ValueError: Filename must be a string -
How to get specific keyword from db and show it in dropdown format in django template?
I want to filter data for that i had given search field and another is dropdown button. In search whatever i type it will show according to subject name but now i want to filter data according to durations available also. def servicesview(request): services = ServicesData.objects.all() key = request.GET.get("search_key", "") if key: services = ServicesData.objects.filter(subject_name__icontains=key) page = request.GET.get('page', 1) paginator = Paginator(services, 2) try: services = paginator.page(page) except PageNotAnInteger: services = paginator.page(1) except EmptyPage: services = paginator.page(paginator.num_pages) return render(request, 'services.html', {'services': services, 'key': key}) services.html <div class="topnav"> <form> <input type="text" name="search_key" value="{{key}}" placeholder="Search..">` <select> <option value="{{}}">Select your option</option> </select> <input type="submit" value="Submit"> </form> </div> The data is not showing as i did not imported any fields. I want to show in my template. Please help -
cookie is not set while redirecting in python django
I am trying to redirect to a different domain, so the below code is redirecting properly but when i check the cookie the cookie is not set in the redirected url. What can be the issue any help is appreciated. I am using Django 1.8.17 @permission_required('users.page_live', login_url='/admin/') def users_view(request): try: user_list = UsersConfig.objects.get(meta_key="ALLOWED_USERS") user_list = [int(x) for x in user_list.meta_value.split(",")] sessionId = 0 if request.user.id not in user_list: redirect_url = "http://mes.meta.in/admin" try: if settings.ENV == 'PROD': redirect_url = "https://data-frontend.production.us.mes.cloud/" else: redirect_url = 'https://data-frontend.staging.us.me.s/' response = HttpResponseRedirect(redirect_url) except Exception as e: print e response = HttpResponseRedirect("/admin") else: redirect_url = "http://mes.meta.in/admin" try: if settings.ENV == 'PROD': redirect_url = "https://data-frontend.production.us.mes.cloud/" else: redirect_url = 'https://data-frontend.staging.us.me.s/' response = HttpResponseRedirect(redirect_url) except Exception as e: print e response = HttpResponseRedirect("/admin") max_age = 172800 expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT") if settings.ENV == 'PROD': response['Set-Cookie'] = 'mes_wr_session_id=' + sessionId + '; domain=mes.in; port=80; path=/' else: response.set_cookie(key="mes_wr_session_id", value=sessionId, max_age=max_age, expires=expires) except Exception as e: print e return response -
Group_by and filter Django
I'm trying to make and query in Django,But I can't get the output I want. I want to use group by and filter in Django Query, I tried using annotate by looking at some answers on stackoverflow and some other sites but couldn't make it work . Here's my response on after using filter. [ { "id": 11667, "rate_id": "FIT-PIT2", "name": "FIT-PIT111", "pms_room": null, "description": null, "checkin": "", "checkout": "", "connected_room": null }, { "id": 11698, "rate_id": "343", "name": "dfggffd", "pms_room": "5BZ", "description": null, "checkin": null, "checkout": null, "connected_room": null }, { "id": 11699, "rate_id": "343", "name": "dfggffd", "pms_room": "6BZ", "description": null, "checkin": null, "checkout": null, "connected_room": null }] What I want to do is group all those pms_rooms which have same rate_id, roughly something like this {'343':['5BZ','6BZ'],'FIT-PIT2':[null]} I can do it using dictionary or list . But I want to do it directly from query like table.objects.filter(condition).group_by('rate_id') , something SQL equivalent of SELECT *,GROUP_CONCAT('name') FROM TABLE NAME WHERE PMS = hotel.pms GROUP BY rate_id . Can somebody please help me out . Thanks. -
I tried to run a Django site downloaded form a git repo but I'm stuck at resolving the dependencies(upm and pypraoch)
This is the error message I'm getting this is an up and running site so no possibility of the dependency being wrong I guess -
invalid syntax tried almost everything
I'm running into issues with this code. return render(request, 'count.html',{'fulltext':fulltext,'count':len(wordlist),'sortedwords':}) CMD is telling me line 22 invalid syntax but, I cant find anything wrong with it. -
old media files visble but new image files uploaded on django development admin console failing with 404 not found
I am running python 3.7/Django==2.2.6 . My issue is all old files uploaded through django admin console were accessible from media folder when i go with domain.com/media/. But when i upload a new file, it says successfully saved and i can see the file in media folder but when access it it says 404 not found. All old files in media folder still accessbile. My settings.py DEBUG = 'True' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path(......), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django admin site: how to get a student id to link a specific html?
I hope my title is enough to understand my question this is my admin.py @admin.register(studentDiscount) class studentDiscount(admin.ModelAdmin): list_display = ('Students_Enrollment_Records', 'Discount_Type','my_url_field') ordering = ('pk',) def my_url_field(self, obj): obj_id = obj.Students_Enrollment_Records.Student_Users.id url = reverse('record', args=[obj_id]) return format_html( '<a href="{url}" target="_blank">{obj_id}</a>', url=url, obj_id=obj_id ) this is my model.py class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) this the result what I want if I click on the Download link it will go to specific html by Student ID this is the result if i click the Download link this is the error I get with my current admin.py, please help me guys this is my views.py def record(request): return render(request, 'accounts/adminstudentrecord.html') my url.py path('record/', accounts.views.record, name='record'), -
Annotate fields from intermediate model from Django RelatedManager
Given a Django intermediate model for a ManyToManyField e.g. class Player(models.Model): name = models.CharField(max_length=128) class Team(models.Model): name = models.CharField(max_length=128) players = models.ManyToManyField(Player, through='Membership', related_name='teams') class Membership(models.Model): player = models.ForeignKey(Player, related_name='membership') team = models.ForeignKey(Team, related_name='membership') is_manager = models.BooleanField() I want to annotate fields from Membership onto a related manager query, e.g. team = get_team() team.players\ .annotate(is_manager=F('membership__is_manager'))\ .all() But this results in an outer join of memberships back to players. I know I can turn the query around and query directly on Membership, but what I need is Player objects to feed into the serializer. It feels obvious how I would express this in SQL, but I can't work out how to express it in ORM. -
How to do asynchornous post requests from django to external server?
Currently I am using requests for sending get or post request. But I need to send a asynchronous post request. Lets say I have three block in a task : def funct(): ########### # Section 1 ########### print("First Sectiojn") ########### # Section 2 ########### requests.post(url,data) ########### # Section 3 ########### print("Third Section") I just want to send the post requests in section 2 after that without waiting for the response I want to execute section 3. Please suggest me a good library or way. Thanks in advance. -
How to get two value just using one serializerMethodField
When 'content' field is excluded, I want to add "NOT content contained" at 'sth' field, else "content contatined" serializers.py class PostSerializer(serializers.ModelSerializer): sth = serializers.SerializerMethodField() class Meta: model = Post fields = ('id', 'sth', 'content', 'created',) def get_sth(self, obj): return Response what I want to get [ { "id": "1", "sth": "content contained", "content": "a", "created": "2020-01-23" }, { "id": "3", "sth": "NOT content contained", "created": "2020-01-22" }, ] How can I get the reponse like above. -
Way to distinguish different AJAX functions in POST?
I need to distinguish among multiple AJAX functions in a django view's POST method, to handle multiple forms. The background: I'd previously written this view without AJAX and got it working just fine. Before Ajax, I was able to distinguish the POST method for each form by adding name="some_button_name", like so: if request.method == 'POST' and 'some_button_name' in request.POST: #check which form button submitted This was great, but AJAX can make it better if I get it working. Now I'm not sure how to distinguish the ajax functions on the view side. Here's how I think it should work (theoretical view): if request.method == 'POST' and request.POST['some identifier_A from ajax function here']: # do stuff # save form_A if request.method == 'POST' and request.POST['some identifier_B from ajax function here']: # do stuff # save form_B if request.method == 'POST' and request.POST['some identifier_C from ajax function here']: # do stuff # save form_C ... but I'm stumped. Below is my (simplified but structurally accurate) code. It will of course want to call every model's save method regardless of which form/ajax function was called, so saving form C will screw up form B since the B's ajax handler didn't do anything or … -
Website using Django runs on machine that doesn't have Django. How is this possible?
I inherited maintenance of a large website, and no one knows what the tech stack is. I'm trying to piece it together bit by bit. All signs point to it being some combination of Django and Nginx. However, Django is literally not installed on the machine. I can't get the version, and I can't import anything Django-related using python from command line. Similarly, none of my changes to the .py files is compiled when I restart Nginx. I can delete all the .py and .pyc files and leave only .html files and somehow it still works. Changes to the html files work though. How is this possible, and how do I get my changes to the .py files to be reflected on the website? -
ModuleNotFoundError in wsgi + apache despite installed and python path configured
So I installed all the requirements into a virtual env, however this error still shows [Fri Jan 24 10:14:11.568489 2020] [wsgi:error] [pid 7677:tid 139735752533760] [remote 168.70.107.79:35002] mod_wsgi (pid=7677): Target WSGI script '/root/pw_x_web/PW_X_Web/wsgi.py' cannot be loaded as Python module. [Fri Jan 24 10:14:11.568566 2020] [wsgi:error] [pid 7677:tid 139735752533760] [remote 168.70.107.79:35002] mod_wsgi (pid=7677): Exception occurred processing WSGI script '/root/pw_x_web/PW_X_Web/wsgi.py'. [Fri Jan 24 10:14:11.568773 2020] [wsgi:error] [pid 7677:tid 139735752533760] [remote 168.70.107.79:35002] Traceback (most recent call last): [Fri Jan 24 10:14:11.568797 2020] [wsgi:error] [pid 7677:tid 139735752533760] [remote 168.70.107.79:35002] File "/root/pw_x_web/PW_X_Web/wsgi.py", line 12, in <module> [Fri Jan 24 10:14:11.568801 2020] [wsgi:error] [pid 7677:tid 139735752533760] [remote 168.70.107.79:35002] from django.core.wsgi import get_wsgi_application [Fri Jan 24 10:14:11.568819 2020] [wsgi:error] [pid 7677:tid 139735752533760] [remote 168.70.107.79:35002] ModuleNotFoundError: No module named 'django' My pip3 list looks like this (running from django.core.wsgi import get_wsgi_application is fine on python console) amqp (2.5.2) argh (0.26.2) asgiref (3.2.3) bcrypt (3.1.7) billiard (3.6.1.0) celery (4.4.0) certifi (2019.11.28) cffi (1.13.2) chardet (3.0.4) Django (3.0.2) django-dbbackup (3.2.0, /root/pw_x_web/venv/src/django-dbbackup) django-livesync (0.5) django-recaptcha2 (1.4.1) docopt (0.6.2) idna (2.8) importlib-metadata (1.4.0) kombu (4.6.7) more-itertools (8.1.0) mysqlclient (1.4.6) pathtools (0.1.2) Pillow (7.0.0) pip (9.0.1) pkg-resources (0.0.0) pycparser (2.19) python-dateutil (2.8.1) pythonanywhere (0.8.3) pytz (2019.3) PyYAML (5.3) requests (2.22.0) schedule (0.6.0) setuptools (39.0.1) … -
TypeError: __init__() got an unexpected keyword argument 'attrs'
I Know this question had been asked many times but I still cant figure it out yet. from django.contrib.auth.forms import UserCreationForm from django.forms import ModelForm from django import forms from . models import Profile from django.contrib.auth.models import User ACCOUNT_TYPE = [ ('SPO', 'SPO'), ('Call Agent', 'Call Agent'), ('Accountant', 'Accountant'), ] class CreateUserForm(UserCreationForm): name = forms.CharField(max_length=255, required=False) account_type = forms.ChoiceField(choices = ACCOUNT_TYPE) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'name': forms.CharField(attrs={'class': 'form-control','required':'required'}), 'account_type': forms.ChoiceField(attrs={'class': 'form-control','required':'required'}) } What am I doing wrong. I have made every possible changes but nothing had changed. Thank you in advance -
Email activation in Django failing in different browsers
My app has email activation. However, the activation link fails when the user creates an account in one browser and tries to verify the link from another browser. How do I fix this problem? I create the uidb64 when creating the account. It all works when the user tries to use activation link in the same browser. try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if request.user.is_authenticated and account_activation_token.check_token(user, token): .... do something else: return HttpResponse('Activation link is invalid!') Please help how do I fix this bug? -
Channels endpoint not found - Deploying Django channels app to Heroku
I'm able to run an app with channels and redis in my local server, but my websocket consumer endpoint is not found after deploying to heroku. Here are my relevant settings: settings.py: if 'REDIS_URL' in os.environ: print('database url found') CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:8869')], }, }, } else: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } CACHES = { "default": { "BACKEND": "redis_cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), } } routing.py from django.conf.urls import url from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import myapp.routing from .consumers import MyConsumer application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ url('editor/', MyConsumer), ]) ), }) Procfile release: python manage.py migrate web: gunicorn myapp.wsgi wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() When I try to connect to the endpoint /editor, I see in my Heroku logs: app web.1 - - Not Found: /editor/ This is using the command: new WebSocket(`ws://${window.location.hostname}:${window.location.port}/editor`) Any suggestions about why my channels setup isn't working? -
how to browse django psql backend from command line
Im developing a website with Django 3 (in a docker container) using postgres sql as the backend; i.e. in the project settings file I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } Ive populated the backend database and can browse the data using the admin. However, Id like to connect to the database via the command line so I can more easily test queries. I have tried connecting to the database the normal way from the command line: sudo -u postgres psql postgres=# \c postgres The problem is that there is no data found: postgres=# \dt Did not find any relations. since Im new to docker I thought to try connecting other ways as well; specifically, based on another post I tried: sudo docker run -d -p 5432 -t postgres/postgresql /bin/su postgres -c '/usr/lib/postgresql/10/bin/postgres -D /var/lib/postgresql/10/main -c config_file=/etc/postgresql/10/main/postgresql.conf' This throws an error: pull access denied for psql/postgresql, repository does not exist or may require 'docker login' Again, Id like to connect to the database via the command line so I can more easily test queries. Perhaps Im on the right track but assistance would be appreciated.