Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connect django web app to postgresql in gcloud
i have been struggling to connect my django web app to a PostgreSQL instance which I set up inside my gcloud account for testing purposes. I have done the following DB configs in settings.py in Django: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'instance connection name from gcloud', 'USER' : 'postgres', 'PASSWORD': 'passsss', 'HOST': 'ip-address', 'PORT': '5432', } } the error that I receive in Django after trying to migrate is : django.db.utils.OperationalError: FATAL: database "..instance connection name from gcloud.." does not exist I have tried creating a new database "django" and adding it to the NAME with:. This did not work as well. I have also configured in gcloud connections my own computer IP as an authorized network Normally if I use service like elephantsql it works fine. Any help would be appreciated. Thanks! -
The 'image' attribute has no file associated with it
I have been trying to update image since i added an ImageField to model.py but it always gives me this error The 'image' attribute has no file associated with it. From Admin panel given by django i can do so i can add and updat, but i need to create my own way of updating images but id doesn't work. Here are my attachments This is my model class rooms(models.Model): room_number = models.PositiveIntegerField(unique = True) room_type = models.ForeignKey(room_types, on_delete=models.CASCADE) number_of_beds = models.PositiveIntegerField() image = models.ImageField(upload_to = 'room_pics/', null = True, blank = True) price = models.PositiveIntegerField(default=0) class Meta: verbose_name_plural = 'Rooms' def __str__(self): room_number = "Room number: " + str(self.room_number) return room_number Here is a form from forms.py class addRoomForm(forms.ModelForm): class Meta: model = rooms fields = ['room_number', 'room_type', 'number_of_beds', 'price', 'image'] and here are the views from views.py to add and update def add_room(request): form = addRoomForm() if request.method == 'POST': form = addRoomForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Room added successfully!') return redirect('add_room') else: form = addRoomForm() context = { 'form' : form, } myTemplate = 'hotel/addRoom.html' return render(request, myTemplate, context) def update_room(request, id): instance = get_object_or_404(rooms, pk = id) form = addRoomForm(request.POST or None, instance = instance) if … -
Get_next_by_field with complex query
I have model Match that has fields team_first and team_second fields, also it has datetime field for the time of the match. I want to get the next match with team_first, it can be team_first or team_second, so i'm trying to do this query: self.get_next_by_datetime(Q(team_first=team) | Q(team_second=team)) It doesn't work giving me the following error: TypeError: _get_next_or_previous_by_FIELD() got multiple values for argument 'field'. Of course there are some workarounds like getting next with team_first=team and team_second=team and then comparing them and selecting the earliest and etc, but is there way to do it without? -
How to make a forum like tag system for images in Django
I am trying to make a educational website using Django where anyone can create posts. Now in those posts I want to provide links to images in a tag so that it shows up in the post. For example something similar to the html img tag will do. My Post creation view: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'display', 'category'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def cat_on_all_pages(request): return {'cat': Category.objects.all()} My html template for post creation (I use crispy forms here): {% extends "blog/base.html" %} {% block title %}Submit a Course{% endblock %} {% load crispy_forms_tags %} {% block content %} <div> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Submit or Edit a Course</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} -
get celery progress using AJAX in Django
I am new in web development.I want to upload a file and proccess it in a Celery task and show progress percent using AJAX. I used some samples and here is my code: views.py: def importnewdata(request): if request.method == 'POST': form = RawFileAddressForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] file_name = default_storage.save("sample.txt", file) task = proccess_file.delay(file_name) return HttpResponse(json.dumps({'task_id': task.id}), content_type='application/json') else: return HttpResponse("Error!") else: form = RawFileAddressForm() return render(request, 'modelmanager/importnewdata.html', {'form': form}) def get_task_info(request): task_id = request.GET.get('task_id', None) if task_id is not None: task = AsyncResult(task_id) data = { 'state': task.state, 'result': task.result, } return HttpResponse(json.dumps(data), content_type='application/json') else: return HttpResponse('No job id given.') forms.py: class RawFileAddressForm(forms.Form): file = forms.FileField() importnewdata.html: <!DOCTYPE html> <html> <head> <title>import new raw data to db</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <body style="text-align: center;"> <h1>select your file to proccess it!</h1> <progress id="progress-bar" value="0" max="100" style="display:none; margin-bottom: 1em;"></progress> <form id="proccess-raw-data" action="/modelmanager/importnewdata/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> </form> <script type="text/javascript"> var frm = $('#proccess-raw-data'); var pgrbar = $('#progress-bar'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { if (data.task_id != null) { get_task_info(data.task_id); } }, error: function (data) { frm.html("error!"); } }); return false; }); function get_task_info(task_id) { $.ajax({ type: … -
Django - Need Help Converting View To Class Based
I'm having trouble converting this to a class-based view :/ Can anyone help me out ? (and explain in the process if possibile) I went through the docs, this is the only view from my app that I still didnt convert. def apartment_view(request, apartment_id): reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) unavailable = [] for start, end in apartment.reservations.values_list('start_date', 'end_date'): while start <= end: unavailable.append(start.strftime('%-d-%m-%Y')) start += datetime.timedelta(days=1) form = ReservationForm() if request.method == 'GET': form = ReservationForm() elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): reservation = form.save(commit=False) reservation.apartment = apartment reservation.save() form.save() return HttpResponseRedirect(reverse('booking:apartment', kwargs={'apartment_id': apartment.pk})) args = {} args['form'] = form args['apartment'] = apartment args['unavailable_dates'] = json.dumps(unavailable) return render(request, 'booking/apartment.html', args) -
Django - Data source name not found and no default driver specified
I am trying to deploy my Django app and connect it to the mssql server. Django app is running on the iis and MSSQL Server 16 I am getting this error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I am running Django==2.1.11 and pyodbc==4.0.27 This is my settings,py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'my_database', 'USER': 'app_user', 'PASSWORD': 'XXXXX', 'HOST': 'XYZ.XYZ.XYZ.XYZ', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } I have no idea what to do to make it working. -
Can I transfer the site from heroku to another hosting?
The site is currently hosted on heroku. There are constant problems with opening the site. A very long time to open. At first they thought that the reason for falling asleep on a free tariff, but installed a program that wakes up the site and it still opens badly. Now suspicions that RCN is blocking the ip addresses heroku. -
Subscription django paypal integration
Anyone help me on django with website for Subscription of two plans and integrate paypal payment gateway are any basic project on github Thanks In advance -
How to test if user can display his profile?
I've got a model UserProfile. class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) city = models.CharField(max_length=100, blank=False) region = models.CharField(max_length=100, blank=False) post_code = models.CharField(max_length=100, blank=False) def create_profile(sender, **kwargs): #Funckja, ktora tworzy profile użytkownika user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) def __str__(self): return self.user.username And his view: def user_details(request, pk): user = get_object_or_404(User, pk=pk) userprofile = user.user return render(request, 'user_details.html', {'userprofile': userprofile}) The problem is I want to test if user can display his profile by clicking on: <a href="{% url 'accounts:user_details' pk=user.pk %}">Your profile</a> I can not figure out how to do it. I tried to do this way: from django.test import TestCase from accounts.models import * from django.test import Client class UserDetailsView(TestCase): @classmethod def setUpTestData(cls): cls.client = Client() cls.user = User.objects.create(username="Test") owner = cls.user cls.user.save() def test_view_url_exists_at_desired_location(self): response = self.client.get('accounts/{}').format(owner) self.assertEqual(response.status_code, 200) But it's not working. The full code is here: https://github.com/Incybro/DjangoShop -
Django/Heroku After pushing a new version certain templates do not update
I have made some changes to a Django template, saved them, committed them to git, pushed to GitHub and then deployed this new version to Heroku. The build succeeds and I can view the template but the change is not there. I checked the GitHub repo, the change is there. When I check the activity feed on Heroku I can see the change when I click the Compare diff link. When I make changes to other areas of the project, views etc there's no problem, I have updated other templates without issue but can not get the new CSS into the deployed version. Inspecting the code of the deployed version shows the old CSS not the new so it isn't just an issue with my stylesheet, inheritance or so on. I've run out of ideas, any suggestions of how I can resolve this? -
Circular reference detected with Django JsonResponse
I'm troubling with Circular reference detected when return JsonResponse from Django. The error caused by comment part of code below. It took my lot of time, but I still cann't find the reason. class GetAllGoogleAdsAccountView(LoginLimitViewMixin): def get(self, request): base_response = { "success": True, "data": None, "info": None, } try: smb_user_id = 142 account_list_smb_created = { account.account_id :{ "account_id": account.account_id, "manager_id": account.manager_account_id, "account_name": account.account_name, "timezone": account.timezone, "currency": account.currency, "status": 1, "is_smb": 1, "create_time":account.create_time } for account in SmbGoogleAccounts.objects.filter(smb_user_id=smb_user_id) } account_list_after_sync = { account.customer_id: { "account_id": account.customer_id, "manager_id": account.manager_id, "account_name": account.customer_name, "timezone": account.timezone, "currency": account.currency, "status": account.status, "is_smb": account.is_smb, } for account in GgCustomer.objects.filter(smb_user_id=smb_user_id).all() } final_dict = {**account_list_smb_created, **account_list_after_sync} #for key, value in account_list_smb_created.items(): # final_dict[key]["create_time"] = value # if removing comments , error happens final_account_list = [] for _, v in final_dict.items(): final_account_list.append(v) base_response["data"] = final_account_list except Exception as e: base_response["success"] = False base_response["info"] = "get account error:{}".format(e) return JsonResponse( base_response ) How can I avoid this error? Any commentary is very welcome. great thanks. -
How to get count from two columns in django queryset?
models.py class Friend(models.Model): creator = models.ForeignKey(Individual, related_name="friendship_creator_set", blank=True, null=True) friend = models.ForeignKey(Individual, related_name="friend_set", blank=True, null=True) active = models.BooleanField(default=False, blank=True) confirm = models.BooleanField(default=False, blank=True) created_at = models.DateTimeField(auto_now_add=True, auto_now=False) modified_at = models.DateTimeField(auto_now_add=False, auto_now=True) I am adding this two query to get the result: Friend.objects.filter(creator_id=value, confirm=True).count()+ Friend.objects.filter(friend_id=value, confirm=True).count() How can convert it to a single queryset in Django? -
How to setup django without running server
i was trying to access django website from a remote server. I allowed all PC's in settings.py ALLOWED_HOSTS = ['*', 'localhost'] And run python manage.py runserver 0.0.0.0:8085 I can access the site from connected computers. But i need to run the runserver commanad on server system before accessing site. Is there a way to access the website without running the command -
What's wrong with my Django dynamic formset?
My goal is to define an upload form for cars for users to upload a car with all relevant details, and adding images from the same page. The Admin form works perfectly, and I just want to emulate it in custom page-- a surprisingly difficult task! I'm using this tutorial, with the fields changed to match my project. I'm also using the django-dynamic-formset jQuery plugin to provide additional image fields as needed by the user. I've been stuck on this for a week, and I'm not sure exactly where the issue lays, so I'm going to share lots of code. class ImagesInline(admin.TabularInline): model = Image @admin.register(Car) class CarAdmin(admin.ModelAdmin): list_display = ('manufacturer', 'car_model', 'model_year', 'mileage', 'status', 'date_added', 'price', 'seller') list_filter = ('manufacturer', 'status', 'transmission') fieldsets = ( ('General information', { 'fields': ('manufacturer', 'car_model', 'model_year', 'price', 'vin', 'mileage', 'transmission', 'engine_displacement', 'forced_induction', 'drivetrain', 'description',) }), ('Availability', { 'fields': ('status', 'seller') }), ) inlines = [ImagesInline] This is the CarCreate view class CarCreate(generic.CreateView): model = Car # fields = '__all__' success_url = reverse_lazy('car-detail.html') slug_field = 'id' slug_url_kwarg = 'car_create' template_name = 'showroom/car_create.html' form_class = CarImageForm success_url = None def get_context_data(self, **kwargs): data = super(CarCreate, self).get_context_data(**kwargs) if self.request.POST: data['images'] = CarImageFormSet(self.request.POST) else: data['images'] = CarImageFormSet() … -
Why am I not able to import object from django models in python 3?
I am converting my python 2 project into python 3 & during conversion I am facing some strange problem like I am not able to import object from my django models. I think I have imported them properly but still I am getting error. -
How to write test case for sending email
Here is the simple view for creating user and staff model.After creating user and staff, it sends the html email to the user's email to fill up the details and the view works fine. Now I want to write test case for this view and tried like this below but i got stuck on how can i write test to check whether the email will be sent or not after saving staff model, to the users. models.py class Staff(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff') name = models.CharField(max_length=255, blank=True, null=True) organization = models.ForeignKey(Organization, on_delete=models.SET_NULL,related_name='staff') position = models.ForeignKey(Position, on_delete=models.SET_NULL,related_name='staff') ....... views.py def register_staff(request): form = RegisterStaffForm() if request.method == 'POST': form = RegisterStaffForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] organization = form.cleaned_data['organization'] position = form.cleaned_data['position'] ...... user = form.save(commit=False) user.is_staff = True user.is_active = True user.save() # creating staff model with user data Staff.objects.create(user=user, name=name, organization=organization, position=position,....) # sending html_email to the user config = EmailConfiguration.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) subject, from_email, to = "Staff Details", config.email_host_user, user.email text_content = "Staff Details " site = get_current_site(request) html_content = render_to_string('send_email.html', {'user': user, 'site_domain': site,}) msg = EmailMultiAlternatives(subject, text_content, from_email, [to],connection=backend) msg.attach_alternative(html_content, "text/html") msg.send() tests.py class StaffTestCase(TestCase): def setUp(self): self.position = Position.objects.create(title='Developer') … -
display total budget, allocated budget and available budget group by year
I am new in Django and working on budget tracking app. I want to display total_budget, total_budget_allocated_to_category and total_available_budget group by year. Please suggest if any relationship change required in models.py models.py class YearMaster(models.Model): year = models.SmallIntegerField(unique=True) class CategoryMaster(models.Model): category_name = models.CharField(max_length=255) class BudgetMaster(models.Model): year = models.ForeignKey(YearMaster, on_delete=models.SET_NULL, null=True) initial_budget = models.DecimalField(max_digits=20, decimal_places=2) class CategoryBudgetMaster(models.Model): year = models.ForeignKey(YearMaster, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(CategoryMaster, on_delete=models.SET_NULL, null=True) category_initial_budget = models.DecimalField(max_digits=20, decimal_places=2) views.py def budget_details(request): queryset = BudgetMaster.objects.values('year', 'year__year_name').annotate(total_initial_budget=Sum('initial_budget')) return render(request, "budget_list.html", {'budget_list': queryset}) Data_Table budget_master category_budget_master -
Django: Add a "configuration" list for different code sections to access
I use these different code snippets at different parts in my code. To avoid potential errors over time I would like to implement one configuration list that both these sections can access. The list gets longer over time with more entries. Do you have an idea about how to achieve that? Here the "configuration" list #1 and #2 should access in order to perform the filter and if statement: list = [TYPE_OF_PEOPLE_ATTENDING, HEARING_ABOUT_THE_EVENT, MISSING_EVENT_INFORMATION, REASON_FOR_ATTENDING] 1 entities = ( Entity.objects.values("answer__question__focus", "name") .annotate(count=Count("pk")) .annotate(total_salience=Sum("salience")) .filter( Q(answer__question__focus=QuestionFocus.TYPE_OF_PEOPLE_ATTENDING) | Q(answer__question__focus=QuestionFocus.HEARING_ABOUT_THE_EVENT) | Q(answer__question__focus=QuestionFocus.MISSING_EVENT_INFORMATION) | Q(answer__question__focus=QuestionFocus.REASON_FOR_ATTENDING) ) ) 2 if ( answer_obj.question.focus == QuestionFocus.TYPE_OF_PEOPLE_ATTENDING or answer_obj.question.focus == QuestionFocus.HEARING_ABOUT_THE_EVENT or answer_obj.question.focus == QuestionFocus.MISSING_EVENT_INFORMATION or answer_obj.question.focus == QuestionFocus.REASON_FOR_ATTENDING ): entities = analyze_entities(answer_obj.answer) bulk_create_entities(entities, response, answer_obj) -
Why can't I retrieve Date time value from my database in Django orm?
I have the following scenario: in models.py def Lab(models.Model): test_id=models.IntegerField() test_name=models.CharField(max_length=10) test_date=models.DateField() I migrated the DB to sqlite3 and filled it from an external Excel sheet, now I am trying to do the following: Lab.objects.values_list('test_date',flat=True) This call raises the following error *** ValueError: invalid literal for int() with base 10: b'09 00:00:00.000000' I can simply ask for the other values and have no problem but not for test_date value, What could be the mistake here? -
The image disappears after running the create in Django view
I have a question I created row data through the view function The image is missing I have verified that the values are stored correctly in the other fields. I can't find out why. If you have any idea or why do you know, thank you very much. When I opened the database program, there was nothing in the image field What is the cause of the problem? Thank you very much for letting me know view code is this def copy_to_me_from_user_id(request): author = request.POST['author'] # 나의 노트 모두 지우기 if( MyShortCut.objects.filter(Q(author=request.user)).count() != 0): MyShortCut.objects.filter(Q(author=request.user)).delete() CategoryNick.objects.filter(Q(author=request.user)).delete() CommentForShortCut.objects.filter(Q(author=request.user)).delete() user_id = User.objects.get(username=author).id print("user_id : " , user_id) wm_list_for_copy = MyShortCut.objects.filter(Q(author=user_id)) print("wm_list_for_copy : " , wm_list_for_copy); comment_wm_list_for_copy = CommentForShortCut.objects.filter(Q(author=user_id)) for p in wm_list_for_copy: myshortcut = MyShortCut.objects.create( author = request.user, title = p.title, content1 = p.content1, content2 = p.content2, type_id = p.type_id, category = p.category, image=p.image, ) # print("myshortcut : " , myshortcut.id) for comment in comment_wm_list_for_copy: # print("comment.id : ", comment.id) # print("myshortcut.id : ", myshortcut.id ) if comment.shortcut.id == p.id: print("댓글 생성 시도 확인") wm = MyShortCut.objects.filter(id = comment.id) wm_comment = CommentForShortCut.objects.create( author = request.user, shortcut = myshortcut, content = comment.content, created_at = comment.created_at, ) list_for_copy2 = CategoryNick.objects.filter(Q(author=user_id)) print("list_for_copy2 : " , … -
Django | 'function' object has no attribute 'get' | for request.POST.get('email')
I downloaded a HTML template form and used in my HTML page and getting the data from it. the function in the view.py associated with it is working. request.POST.get('name') is returning the text inputted but gives the error on the redirect page. Function in views.py def login(request): if request.method == "POST": email = request.POST.get('email') password = request.POST.get('pass') print(email) print(password) return redirect return render(request, 'taskManagementWebApp_templates/login.html') Terminal Output when clicked on Button abc@gmail.com 123456789 Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\Akestech\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Akestech\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "C:\Users\Akestech\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'function' object has no attribute 'get' [16/Oct/2019 12:16:55] "POST /login/ HTTP/1.1" 500 60650 Error on Webrowser Screenshot of Error during the calling of redirect -
django's filter SearchFilter isn't filtering the results, it returns me all of the objects
Im using Django and trying to filter my response data by SearchResult http://localhost:8000/autocomplete/a/?search=Something the problem that it returns me all of the data objects. like there was no filter at all http://localhost:8000/autocomplete/a/ my views.py: from autocomplete.models import Autocomplete from autocomplete.serializers import AutcompleteSerializer from rest_framework import generics from rest_framework.views import APIView from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter, SearchFilter class AutocompleteListView(generics.ListAPIView): serializer_class = AutcompleteSerializer queryset = Autocomplete.objects.all() filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ("IATA", "IATAcity") # < this is working ordering_fields = ("AirportName") # < not working search_fields = ("IATA", "IATAcity") # < not working saw possible solution here, in the last comment: Django REST - SearchFilter not filtering but dont really got where exactly should i post it. what am i doing wrong? Thanks!! -
'list' object has no attribute 'model'
I want to order all stories by average rating, when i type in url .../stories?ordering=average_rating it brings error: 'list' object has no attribute 'model' def get_queryset(self): queryset = Story.objects.all() ordering = self.request.query_params.get('ordering', None) if ordering == 'average_rating': return sorted(queryset, key=lambda s: s.average_rating) return queryset class Story(models.Model): ... @property def average_rating(self): average_rating = self.ratings.all().aggregate(Avg('rating'))['rating__avg'] if average_rating is not None: return round(float(average_rating), 2) return None -
Unable to start Django application with python manage.py runserver 0.0.0.0:8080 on CloudFoundry
I am trying to host Django application in CloudFoundry. I am able to host the application if I use external package "Gunicorn". But with Django's inbuilt runserver, the application is not getting started. The Procfile content with Gunicorn is: web: gunicorn dcms.wsgi:application The result with this Procfile: Application is started and can be seen working successfully on the URL. The Procfile content with django's inbuilt runserver is: web: python manage.py runserver 0.0.0.0:8080 The result with this Procfile: Waiting for app to start... Start unsuccessful So, Would like to know the difference between the two. And want to make it work using runserver without using external package.