Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Test custom email backend
I'm currently trying to create a custom email backend for the first time. Unfortunately, I have problems to test it. My email backend is using Huey to work asynchronous. So, I have a Huey task that is calling a normal email backend (like SMTP). Now, I want to test it and am sending a mail with my backend. I've configured that the Huey task should use django.core.mail.backends.locmem.EmailBackend as its backend. My problem is that len(mail.outobx) is always zero. Here my code: Huey task: @task() def task_send_mail(email): conn = get_connection(backend="django.core.mail.backends.locmem.EmailBackend") try: conn.open() print("Connection open") except: print("Error") conn.send_messages((email,)) My test: def test_email_sent(self): conn = mail.get_connection('django_huey_backend.backend.MyCustomBackend') email = EmailMessage( 'Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}, ) conn.send_messages([email]) time.sleep(0.5) self.assertEqual(len(mail.outbox), 1) The result of the test is AssertionError: 0 != 1. My backend: class MyCustomBackend(BaseEmailBackend): def __init__(self, fail_silently=False, **kwargs): super().__init__(fail_silently) def send_messages(self, email_messages): for email in email_messages: huey_send_mail(email) return len(email_messages) When using the console backend in my Hues task, I get the right output. So in general it's working. -
Same models appearing in conflicting models error
I shifted my project apps to a folder named 'modules' and now when I try to run the project. I get an error RuntimeError: Conflicting 'someappuser' models in application 'authentication': <class 'users.models.someAppUser'> and <class 'modules.users.models.someAppUser'>. It is basically the same model but the system is treating them as different directories, and hence different models Project Hierarchy: SomeApp - settings.py - manage.py - __init__.py - urls.py - views.py - modules +users +models.py +views.py +urls.py Settings.py- PROJECT_ROOT = os.path.dirname(__file__) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(BASE_DIR, 'modules')) -
How to set a time limit for model object delete in django?
I want to set a time limit for object delete in Django. For example, the user can delete the object they submitted within 3 days, once 3 days window is past, they can no longer delete the object. and only the superuser can delete it. How can I achieve that? I tried lots of methods but none can do this...could someone help with the solutions? thanks! -
Django: object has no attribute 'object'
I have to implement several forms, therefore I need the combination of SingleObjectMixin, TemplateView. I always receive 'AssignAttendee' object has no attribute 'object'. Do you see why I get that error? class AssignAttendee(SuccessMessageMixin, SingleObjectMixin, TemplateView): template_name = 'attendees/front/assign_attendee.html' success_message = _("Attendee has been successfully updated.") def get_object(self): return get_object_or_404( Attendee, ticket_reference=self.kwargs['ticket_reference'], ticket_code=self.kwargs['ticket_code'], ) @cached_property def attendee_form(self): return AssignAttendeeForm( prefix='attendee', data=self.request.POST or None, # instance=self.attendee_contact, ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'attendee_form': self.attendee_form, } -
django: test case for @property function of a Model
I have a Django Library application which has the following BookInstance Model: class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) STATUS_MAINTENANCE = 'm' STATUS_ON_LOAN = 'o' STATUS_AVAILABLE = 'a' STATUS_RESERVED = 'r' LOAN_STATUS = ( (STATUS_MAINTENANCE, 'Maintenance'), (STATUS_ON_LOAN, 'On loan'), (STATUS_AVAILABLE, 'Available'), (STATUS_RESERVED, 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default=STATUS_MAINTENANCE, help_text='Book availability', ) class Meta: ordering = ['due_back'] permissions = (("can_mark_returned", "Set book as returned"), ("can_create_book", "Create new book"), ("can_update_book", "Update book details"), ("can_delete_book", "Delete book"),) # how to develop test case for this function @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False In my tests.py file, I have the test_object_name_is_name function to test it, however my coverage report shows that the function is not getting tested. class BookInstanceModelTest(TestCase): """ Test case for Book Instance """ @classmethod def setUpTestData(cls): # Set up non-modified objects used by all test methods test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK', email='testuser1@test.com') test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD', email='testuser2@test.com') test_author = Author.objects.create(first_name='William', last_name='Shakespeare') test_book = Book.objects.create(title='Hamlet', author=test_author, summary='Published in 1990', isbn='123456789123') genre_objects_for_book = Genre.objects.all() test_book.genre.set(genre_objects_for_book) return_date1 = datetime.date.today() BookInstance.objects.create(book=test_book, borrower=test_user1, due_back=return_date1, … -
How to host python with django and mysql to online server especially AWS
am developing a web application on python using django framework but i have a lot of problems on hosting the app suggest me the hosting links and guide me to host my app on online and also suggest me where to i host and i need help on hosting my app to AWS python version:3 django: latest version database : mysql please any one help me thanks. -
Django dropdown dependencies admin
I started with django for a short time, and I am trying to create an application where only the admin interface will be used. I have a situation where the user after selecting the 'freguesia' will show the 'rua' that belongs to this 'freguesia'. I found some forums explaining how to do in frontoffice, but nothing relative in the admin interface. My models: //Mapeamento class freguesia(models.Model): freguesia_nome = models.CharField("Freguesia",max_length=200) class rua(models.Model): rua_id_freg = models.ForeignKey(freguesia, on_delete=models.CASCADE) rua_nome = models.CharField("Rua",max_length=200) //Noutra app class avaria(models.Model): avaria_freguesia = models.ForeignKey(freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") avaria_rua = models.ForeignKey(rua, on_delete=models.CASCADE,verbose_name="Rua") https://i.stack.imgur.com/E8MT7.png https://i.stack.imgur.com/EmVpb.png https://i.stack.imgur.com/KQn3a.png -
Django Rest Framework + Queryset Group By only one Field but show more Fields
Hello i will write this row sql query: select rating, date, count(rating) as "Count" from analyse where wkn='x' and date between 'x' and 'y' group by rating My Model Class is this class Analyse(models.Model): date = models.DateField(blank=True, null=True) week_day = models.CharField(blank=True, max_length=500) location = models.CharField(blank=True, max_length=500) old_rating = models.CharField(blank=True, max_length=500) rating = models.CharField(blank=True, max_length=500) and the Serializer and View is this class RatingSerializer(serializers.Serializer): rating = serializers.ReadOnlyField() total = serializers.ReadOnlyField() date = serializers.DateField()#format='%Y' class CompaniesChartsView(generics.ListAPIView): http_method_names = ['get'] permission_classes = (AllowAny,) serializer_class = RatingSerializer def get(self, request, wkn, format=None): self.query = self.request.GET.get('chart') end = datetime.date.today() #start = datetime.date(datetime.date.today().year-1, 1, 1) start = datetime.date(datetime.date.today().year-1, datetime.date.today().month, datetime.date.today().day) try: if self.query == "ratings": queryset = Analyse.objects.values('date', 'rating') .filter( Q(wkn=wkn) & Q(date__range=([start, end]))) .annotate(total=Count('rating')) serializer = RatingSerializer(queryset, many=True) print(serializer.data) print(connection.queries) return Response(serializer.data) else: return Response("Bad request", status=status.HTTP_400_BAD_REQUEST) except: pass Django generate but this query. This is not that was i will. 'SELECT "statistic_app_analyse"."date", "statistic_app_analyse"."rating", COUNT("statistic_app_analyse"."rating") AS "total" FROM "statistic_app_analyse" WHERE ("statistic_app_analyse"."wkn" = \'840400\' AND "statistic_app_analyse"."date" BETWEEN \'2017-12-20\' AND \'2018-12-20\') GROUP BY "statistic_app_analyse"."date", "statistic_app_analyse"."rating"' Django add the date field to group by. When i change the query to: queryset = Analyse.objects.values('rating') .filter( Q(wkn=wkn) & Q(date__range=([start, end]))) .annotate(total=Count('rating')) Then works, but the date is missing. When i … -
Openedx Django how to remove a country from Country list?
I want to disable a country from country list of my register page ,settings or anywhere country is shown on My Openedx App (OpenEdx is a django based system). But i cannot find country list for removing the country . Where locate the countries? I need to remove it . Django uses django_countries.fields class Those are my tables on mysql : +------------------------------------------------------------------+ | Tables_in_edxapp | +------------------------------------------------------------------+ | api_admin_apiaccessconfig | | api_admin_apiaccessrequest | | api_admin_historicalapiaccessrequest | | assessment_aiclassifier | | assessment_aiclassifierset | | assessment_aigradingworkflow | | assessment_aitrainingworkflow | | assessment_aitrainingworkflow_training_examples | | assessment_assessment | | assessment_assessmentfeedback | | assessment_assessmentfeedback_assessments | | assessment_assessmentfeedback_options | | assessment_assessmentfeedbackoption | | assessment_assessmentpart | | assessment_criterion | | assessment_criterionoption | | assessment_peerworkflow | | assessment_peerworkflowitem | | assessment_rubric | | assessment_staffworkflow | | assessment_studenttrainingworkflow | | assessment_studenttrainingworkflowitem | | assessment_trainingexample | | assessment_trainingexample_options_selected | | auth_group | | auth_group_permissions | | auth_permission | | auth_registration | | auth_user | | auth_user_groups | | auth_user_user_permissions | | auth_userprofile | | badges_badgeassertion | | badges_badgeclass | | badges_coursecompleteimageconfiguration | | badges_courseeventbadgesconfiguration | | block_structure | | block_structure_config | | bookmarks_bookmark | | bookmarks_xblockcache | | branding_brandingapiconfig | | branding_brandinginfoconfig | | bulk_email_bulkemailflag | | bulk_email_cohorttarget | | bulk_email_courseauthorization … -
How to match different content on a page according to which user is logged-in?
I just started using django and I have some problems understanding how to use auth on my web app. So, basically, what I cannot understand how to implement is displaying different content on my page for each user My app is an online editor that each user can use to write their code and have it stored. I have implemented the sign up/sign in and what I need to do now is to have a different filesystem for each user and display it appropriately. I don't know why I can't find this answer anywhere but I am really overwhelmed with this problem and I have done zero progress. -
Django commands not loading Atom text editor, works fine in Terminal (Mac OS)
I am trying to run django commands in Atom Text editor. It seems to work fine in Mac OS Terminal but when executing same within Atom text editor, it shows : Command not found. I am taking online tutorial for this, the instructor uses the command in Windows and seems to work fine in it. But in Mac it's working fine with python and other languages, however for django its showing Command not found. Any help will be greatly appreciated. -
Date ranges prefetch gives multiple entries instead of 1
The following returns 3 objects but this should be only 1. quarter_trading_2018q1 = InsiderTrading.objects.filter( issuer=company_issuer.pk, owners__company=company.pk, transaction_date__range=["2018-01-01", "2018-03-30"] ).prefetch_related('owners') If I however remove the owner_company filter it return 1 (correct behaviour) quarter_trading_2018q1 = InsiderTrading.objects.filter( issuer=company_issuer.pk, transaction_date__range=["2018-01-01", "2018-03-30"] ).prefetch_related('owners') But I still want to filter on owners_company, how do I get 1 returned then? -
Adding the password reset to Django Admin goes to a wrong URL?
I'm following the section on Adding a password reset feature to the Django Admin, which asks you to add these four paths: path('admin/password_reset/', auth_views.PasswordResetView.as_view(), name='admin_password_reset'), path('admin/password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), When I add them, the "Forgotten your password or username?" link appears on the Django Admin log in screen, and if I click it, it works, it even sends the email, but after the email, I end up with this error. Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/password_reset/done/ Raised by: django.contrib.auth.views.PasswordResetDoneView 404... well... yes... that's not where password_reset/done is. And the link in the email is for: http://localhost:8000/accounts/reset/Mjk/5...9, so, against, that's not where reset/<uidb64>/<token>/. Why are these URLs in the wrong place, /accounts/ instead of /admin/. My full URL patterns look like this: urlpatterns = [ path('admin/password_reset/', auth_views.PasswordResetView.as_view(), name='admin_password_reset'), path('admin/password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path("", views.index, name="homepage") ] I'm guessing then that those redirects go to /accounts/ because of this path('accounts/', include('django.contrib.auth.urls')), is that correct? is there another way of controlling them? I'm mostly trying to understand what's going on. -
Dependent ChoiceField
Im trying to develop a platform in Django and when I want to add a new material to it on the admin page, I have to define a faculty and a department for that material. They’re both choice fields. I want that the choices displayed on the second be dependent of the choice made on the previous one. For each faculty that I choose (1st choicefield), it will only display the departments of that faculty (2nd choicefield). How can I make this possible? -
Return None until query for django filters
Hello I was wondering if it's possible to return No Query until search was clicked I used django_filter it works fine, but returns all the objects from the database. I wrote this on a mobile phone access to code example isn't available. -
use opencv.js to capture video on the client side
I am working on a face detection project where when the app is opened on the client side, the webcam should start and the number of faces should be detected. I could not use opencv in python because it runs only on the server side. I tried webrtc but could not find a way to send that data to python. One way I could use webrtc is make the server act as a peer, create a RTCPeerConnection between the client system and the server and send data this way. But since the server code is written in python I could not find a way to implement webrtc in python. aiortc for python implementation does not have windows 10 support. my question is, can I use opencv.js to start the webcam on the client side and somehow send that data to python for the face detection part. If yes, how can i accomplish that? sample code is preferable. I am using django for creating the web application. opencv python, for the face detection part. I want to use python on the server side because I plan on adding more functionality later and it will be easier to code it in python. -
Django Duplicate Migrations with settings default
I have a default value for a model taken from settings. Everytime a launch makemigrations, django create a migrations equals to the previous with this statement: - Alter field status_mapping on <nodel_name> I suppose the problem is the default value taken from settings. Is the a method to resolve this issue? Obviously, I have launched a migration before makemigrations. def status_mapping(): return settings.STATUS_MAPPING # settings status_mapping = JSONField(default = status_mapping) -
django-filter: Using ChoiceFilter with choices dependent on request
I am using django-filter and need to add a ChoiceFilter with choices dependent on the request that I receive. I am reading the docs for ChoiceFilter but it says: This filter matches values in its choices argument. The choices must be explicitly passed when the filter is declared on the FilterSet. So is there any way to get request-dependent choices in the ChoiceFilter? I haven't actually written the code but the following is what I want - class F(FilterSet): status = ChoiceFilter(choices=?) #choices depend on request class Meta: model = User fields = ['status'] -
How to run a Django manage.py command (Django-background-tasks) after startup in Docker?
I have a Django project which I'm using Docker and plan to deploy to AWS Elastic Beanstalk. Based on these requirements, I need to run a manage.py command (namely 'process_tasks' from django-background-tasks) without human intervention. If my understanding is correct, 'process_tasks' must be run otherwise the tasks will not be executed at the scheduled time. I came up with the following solution to add in my docker-compose.yml. The problem is I call my background task in 'urls' on server start and somehow this solution results in adding the task to the db twice. My objective is to run a background task everyday at a certain time. Is there a simpler solution I'm missing? web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db tasks: build: . command: python3 manage.py process_tasks volumes: - .:/code depends_on: - web - db -
Python regex to get first occurance only from ecommerce data inside script tag
I'm using this regular expresion to get data from an eCommerce website which has required data inside script tag - "quantity":"(.*?)" This regular expression is giving me all the matches in the data. I have tried many ways to construct it using non-greedy method but no luck. Which expression should I use to stop the search at the first match from the data?TIA sample Script data : ({{ HOLIDAY","on_sale":false,"quantity":"214","original_price":35,"price":35,"category_path":["Mens","Tees"],"created":"2018-12-01","modified":"2018-12-20","colors":["BLACK"],"sizes":["S","M","L","XL","XXL"],"upcs":["00000000190235804075","00000000190235804082","00000000190235804099","00000000190235804105","00000000190235804112"],"variations":[{"upc":"00000000190235804075","color":"BLACK","size":"S","on_sale":false,"quantity":"31","original_price":35,"price":35},{"upc":"00000000190235804082","color":"BLACK","size":"M","on_sale":false,"quantity":"67","original_price":35,"price":35},{"upc":"00000000190235804099","color":"BLACK","size":"L","on_sale":false,"quantity":"80","original_price":35,"price":35},{"upc":"00000000190235804105","color":"BLACK","size":"XL","on_sale":false,"quantity":"33","original_price":35,"price":35},{"upc":"00000000190235804112","color":"BLACK","size":"XXL","on_sale":false,"quantity":"3","original_price":35,"price":35}]} -
Python - dynamic serializers.ModelSerializer Meta class
I would like to make a this Serializer Meta class variable values inside to dynamic. Is it possible? class Serializer(serializers.ModelSerializer): class Meta: model = Stocks # model fields = ('field1','fieled2','field3') # model fields -
Formset doesn't show field value
I've got this form: class EventAccessKeyCategoriesForm(forms.ModelForm): class Meta: model = AccessKeyEventQuota fields = ['access_key_category', 'quota'] def __init__(self, *args, **kwargs): super(EventAccessKeyCategoriesForm, self).__init__(*args, **kwargs) self.program = kwargs.pop('program', None) access_key_categories = AccessKeyCategory.objects.all() for category in access_key_categories: self.fields['access_key_category'] = ModelChoiceField(queryset=access_key_categories.filter(pk=category.id), empty_label=None, label="Zugriffscodekategorie") # only show one per "row" self.form_tag = False self.form_show_labels = False self.layout = Layout( Row( Div(Field('access_key_category'), css_class='col-sm-6'), Div(Field('quota'), css_class='col-sm-6'), ) ) EventAccessKeyCategoriesFormset = inlineformset_factory(Event, AccessKeyEventQuota, form=EventAccessKeyCategoriesForm, can_delete=False) Which makes me a Formset and shows it on my page. So far everything mostly works, just for one problem: the access_key_categories field doesn't show me the value of the field, but always AccessKeyCategory object as they value of the Choice field In my view I'm getting the formset like this: class EventAccessKeyCategories(EventAttachments): formset_class = EventAccessKeyCategoriesFormset success_redir = 'event_access_key_categories' context = { 'title': 'Access Key Categories', 'note': mark_safe(u'''<p>Test<p>''') } And my models look like this: class AccessKeyCategory(models.Model): program = models.ForeignKey('Program', verbose_name='Programm', on_delete=models.CASCADE) name = models.CharField('Name', max_length=100) events = models.ManyToManyField('Event', through='AccessKeyEventQuota') class AccessKeyEventQuota(models.Model): access_key_category = models.ForeignKey(AccessKeyCategory, on_delete=models.CASCADE, related_name='accesskey_quota') event = models.ForeignKey('Event', on_delete=models.CASCADE, related_name='accesskey_quota') quota = models.PositiveIntegerField('Quota', default=0) Anyone knows why the ModelChoiceField that I set for the access_key_category doesn't show me the actual value of name from my AccessKeyCategory Model, but always AccessKeyCategory object? Thanks … -
Django & reportlab : show a generated pdf on a div in the same page
I'm generating pdfs using reportlab, my view looks like : def statut(request,id): # Set up response infoSte=sarl.objects.get(id=id) associe=Associee.objects.all().filter(id_sarl=id) associe_gerant=0 response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="form_letter.pdf"' buff = BytesIO() menu_pdf = SimpleDocTemplate(buff, rightMargin=60, leftMargin=60, topMargin=65, bottomMargin=65) story = [] #APPENDING PDF CONTENT .. story.append(Paragraph(denomination_so,styleN)) menu_pdf.multiBuild(story, canvasmaker=FooterCanvas) response.write(buff.getvalue()) buff.close() return response This view is renderer using the url bellow url(r'^pdfstatut/(?P<id>\d+)$',views.statut, name='statutJuridique'), when exacuting this url the pdf is generated on a dedicated page. What I need is when I click on the link statut on the left of the page, the pdf shows on the section in the right side : How can I achieve such result when my view only return a response which is only a pdf. -
Best practice to work with existing MS SQL database and python?
By good way I mean any way that will work. I need to write quite simple CRM which will be able to connect to existing MS SQL. At first I wanted to do this in django,so I setup new project and tried to establish connection with database,and here are my trials and errors: django-mssql using this I tried to set up connection in django settings.py like this: DATABASES = { 'default': { 'ENGINE': 'sqlserver_ado', 'NAME': '<name>', 'HOST': '<host>', 'USER': '<user>', 'PASSWORD': '<password>', } } but it only results in error django.core.exceptions.ImproperlyConfigured: 'sqlserver_ado' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I'm working on windows so I went installing Pywin32 and other dependecies but it doesn't change much django-pyodbc-azure This time i switch my django version from 1.6 to 2.1 and tried to establish connection with this settings DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': '<host>', 'NAME':'<name>, 'USER': '<user>', 'PASSWORD': '<password>', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, }, } } Still I could make migration this time becouse of: pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) … -
unable to access context_object_name in templates
I'm trying to iterate over my context object in templates but it's not working. Here's what I have: views.py: class PortfolioStockListView(ListView): model = StockPortfolio template_name = 'home.html' context_object_name = 'stock_portfolio' models.py: class StockPortfolio(models.Model): stock_symbol = models.CharField(max_length=5) stock_qty = models.PositiveIntegerField(default=0) urls.py: urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('stocks', StocksPageView.as_view(), name='stocks'), ] In my template home.html: {% for item in stock_portfolio %} <li>{{ item.stock_symbol }}</li> <li>{{ item.stock_qty }}</li> {% endfor %} I can't seem to find what the issue is here. In my template, the items aren't displayed.