Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How do I fix a ProgrammingError at /admin/login/ (1146, "Table 'torquedb.showroom_customuser' doesn't exist")
I created a CustomUser using the Django allAuth package. Allowing users to sign-up and log in via email rather than usernames was the primary reason why. When I try logging into the admin with my superuser account, it throws this error: ProgrammingError at /admin/login/ (1146, "Table 'torquedb.showroom_customuser' doesn't exist") **Admin.py for the customuser ** @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'phone_number', 'website'] ** The CustomUser models.py ** from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): phone_number = models.IntegerField(default='07') website = models.CharField(max_length=50) def __str__(self): return f'{self.name}' I've tried running new migrations with py manage.py makemigrations py manage.py migrate py manage.py migrate showroom (the app name) I've already dropped and recreated the MariaDB database (called torquedb) a few times, and this is a new one with all migrations up to date. Again, they all state that they are up to date. -
Django not recognizing user form email verification link:
Sorry I've asked this so many times, but I've spent the last week on this like 20 hours and cannot figure it out. Yes, I'm a Django newbie. This is my very first application. I have tested the 'urlsafe_base64_encode(force_bytes(user.pk))' in shell and it works to pass the user's 'uid', however it does not work in the application itself. I get that the 'activation link is invalid' for all links even though the link passed the correct primary key, I'm not sure what is going wrong. Please help. views.py/registration page from_email, subject = 'domain <info@domain>', 'Email verification' htmly = get_template('activation_email_template.html') username = user.username message = render_to_string('activation_email.html', { 'user':user, 'token':account_activation_token.make_token(user), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), }) d = {'username': username, 'url':reverse('activate', kwargs={ 'token':account_activation_token.make_token(user), 'uidb64':urlsafe_base64_encode(force_bytes(user.uid)) })} html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, message, from_email,[user.email]) msg.attach_alternative(html_content, "text/html") msg.send() here is my activate/views.py: try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): ... else: return HttpResponse('Activation link is invalid!') For some reason I'm getting user is none. here is my activation_email.html: {% autoescape off %} Hi {{ user.username }}, Thanks for creating an account. Please click on the link to confirm your registration, http://domain{% url 'activate' … -
Sentry.io ignore logger dynamically
I am hoping to dynamically add loggers to a file whenever I decide to ignore a certain logger from sending to sentry, I've read the docs and this answer How to ignore a logger in the Sentry Python SDK and I believe I got it working when I has put the literal string into the ignore_logger function. When I try the below code, it doesn't ignore the logger, is there a better way to achieve this? with suppress(FileNotFoundError): with open(os.path.join(SITE_ROOT, '..', 'sentry_ignore_logger.txt')) as f: for log_line in f: ignore_logger(log_line) I had a print statement inside the loop to check it was reading the file and it printed as desired, so the issue isn't an incorrect file. The contents of the file are: django.security.DisallowedHost I'm using Djano and I've put this in my settings.py after the sentry_sdk.init (I had it before it, however that also didn't work) Thanks -
How to Run Sympy_gama in windows 10 on localhost
I am new to python and django. I want to run sympy_gama on my localhost server. i follow the documentation given by sympy_gama [ https://github.com/sympy/sympy_gamma]. but in some steps the error can be occurs. after a python deploy.py --generate-only --generate-test 1000 the ../google_appengine/dev_appserver.py . not working this command. Error is : ../google_appengine/dev_appserver.py '..' is not recognized as an internal or external command, operable program or batch file. anyone can help me? -
Is there another way to generate api key in django?
I'm building a testing application in Django that generates api key using the module Django RestFramework API Key. (Refer here: https://florimondmanca.github.io/djangorestframework-api-key/) I want to include some symbols or hyphen in the middle of the generated key. I have tried the default key generator in the module but I want to make it more secure. #models.py from rest_framework_api_key.models import BaseAPIKeyManager from rest_framework_api_key.crypto import KeyGenerator from rest_framework_api_key.models import AbstractAPIKey class UserCompanyAPIKeyManager(BaseAPIKeyManager): key_generator = KeyGenerator(prefix_length=32, secret_key_length=32) class UserCompanyAPIKey(AbstractAPIKey): objects = UserCompanyAPIKeyManager() Output: Prefix = jlxGg6bnRdjtrW3Xr6Q6yUMKWAuc0D2u -
How can I access Outlook contacts using Graph and Python?
I'm trying to access personal contacts using the graph API and Python. I can get this working for calendars and events but cannot find a way to get it working with contacts. The website doesn't provide any Python solutions to this apart from some massively out of date Django tutorials. I've read the documentation on the graph site and have attempted to edit the calendar events tutorial to fit my need but I can't get it to do what I want. Here's what I've got: My code to get the contacts: def get_contacts_personal(token): graph_client = OAuth2Session(token=token) contacts = graph_client.get('{0}/me/contacts'.format(graph_url)) return contacts.json() And my Django view code: def contacts(request): context = initialize_context(request) token = get_token(request) contacts = get_contacts_personal(token) if contacts: context['contacts'] = contacts['value'] return render(request, 'tutorial/contacts.html', context) I was hoping to get the json data but instead I get a keyword error for value. If I remove this I just get no data. I'm sure I'm missing something obvious, hopefully someone can help! -
Run DAG inside airflow container works fine but gets the AirflowException("Bash command failed") when triggered from Web
If I run the DAG inside the docker container with airflow run dag_A task_1 ... command, it works fine. But if I trigger the same DAG via the web-UI, it will fail with the following error: AirflowException: Bash command failed. Sifting through the error logs, revealed this error ImportError: No module named some-lib where some-lib is a local module inside the dag folder. I think the error is related to this question posted in SO - Apache Airflow DAG cannot import local module -
python django use mysql cursor
Cursor declared inside mysql (E.g. DECLARE cur1 CURSOR FOR SELECT id, name FROM mytable) Get returned as a variable in Python Django (e.g. a variable named abc) abc.fetch () Is it possible to use it this way? For now, receiving and printing abc only prints the contents of line x of mytable. fetch () throws an error that it is not defined. -
<option {% if 'condition.' == 'condition....'%}selected{%endif%}> </option> not working in Django custom select
I am passing two objects 'editsub_obj' and 'cat' both key-value pairs to the template. The main aim is to keep option tag selected when name from both object list matches but the code is not working. <select class="form-control" id="" name="cat_name" required> {% if not editsub_obj %} {% for data in cat %} <option value="{{data.id}}">{{data.category_name}}</option> {% endfor %} {% else %} {% for data in cat %} {% if editsub_obj.category_name == data.category_name %} <option value="{{data.id}}" selected>{{data.category_name}}</option> {% else %} <option value="{{data.id}}">{{data.category_name}}</option> {% endif %} {% endfor %} {% endif %} </select> Expected : selected should be selected with the category_name matches in both objects list. Actual : none of the options are showing as selected. -
Subtract dates in django
I'm trying to subtract two dates. I read that it could be done as simples as subtracting two class attributes but I get this error when I execute manage.py runserver expected string or bytes-like object code: class example(models.Model): date1 = models.DateField() date2 = models.DateField() diff = models.IntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.diff = date1 - date2 super(example, self).save(*args, **kwargs) When I put my mouse cursor over the - symbol, PyCharm shows: "Class 'DateField' does not define 'sub', so the '-' operator cannot be used on its intances" What can I do to solve this problem/fix the operation? -
Access a methods variable
I want to access the gallery_path variable from my create_directory method as a parameter in my gallery model field. Is this possible? class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) gallery = models.ImageField(upload_to=gallery_path) def create_directory(self): global gallery_path gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, self.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) def save(self, *args, **kwargs): if not self.pk: self.create_directory() super().save(*args, **kwargs) def delete(self, *args, **kwargs): shutil.rmtree(os.path.join(settings.MEDIA_ROOT, self.slug)) # os.rmdir(os.path.join(settings.MEDIA_ROOT, self.slug)) super().delete(*args, **kwargs) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title