Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin: inline model: how to acess current record id from has_delete_permission
Django admin.py class ProductAdmin(<SomeSuperAdmin>) # blah-blah... class ProductCommentAdmin(<SomeSuperAdmin>): # blah-blah... class ProductCommentInline(admin.TabularInline): model = ProductComment # blah-blah... def has_delete_permission(self, request, obj=None): #here I have obj.id which is id of Product, but not ProductComment #here I need to get somehow current ProductComment record data product_comment_record = <get_somehow_current_record_data > return product_comment_record.<some_bool_field> How do I access a current ProductComment record data from has_delete_permission method of an inline model? -
Use multiple databases in Django with only one table "django_migrations"
For a project in Django I have to use two databases: default and remote. I have created routers.py and everything works fine. There was a requirement to create a table on the remote database and I created migration, run it and the table django_migrations was created. I want to have only one table django_migrations, in the default database. The relevant part of routers.py is here: class MyRouter(object): # ... def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'my_app': return db == 'remote' return None I run the migration like this: python manage.py migrate my_app --database=remote Now when I do: python manage.py runserver I get the following warning: You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): my_app. Run 'python manage.py migrate' to apply them. The tables for my_app are created in the remote database, and in django_migrations inside the remote database the migrations are marked as applied. How to force Django to use only one table django_migrations, but still apply the migrations into different databases? -
Mistakes in custom pagination Django Rest Framework
I am using APIView in myproject and custom pagination also it is working but it shows same elements multiple time. Here I have tried so far. views.py class ProductByBrand(APIView): pagination_class = LimitOffsetPaginationUpperBond @property def paginator(self): if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() return self._paginator def paginate_queryset(self, queryset): if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self, ctx): assert self.paginator is not None return self.paginator.get_paginated_response(ctx) def get(self, request, slug, brand, format='json'): pid = Category.objects.get(slug=slug) data = Category.objects.filter(parent_id=pid) data_categories = [] for category in data: data_categories += Category.objects.filter(parent_id=category.id) all_product = [] for data_category in data_categories: all_product += Product.objects.filter(category_id=data_category.id, brand=brand) print(all_product) ctx = [] for product in all_product: str = settings.MEDIA_URL + product.image.name ctx.append({ 'id': product.id, 'name': product.name, 'slug': product.slug, 'brand': product.brand_id, 'image': str, 'price': product.price, 'rating': product.rating, 'discount': product.discount }) queryset = Product.objects.all() page = self.paginate_queryset(queryset) if page is not None: return self.get_paginated_response(ctx) to be more precise I select brand in category section to filter the products related to that category. For example: I have two product as it can be seen from electronics category it has two products related to brand which id is 3. In this case I have … -
Django - Receiving error "too many values to unpack (expected 2)"
In my website, I have created a custom user from the AbstractUser class. When I check if a user with the same username or email exists, I get a value error returned to me. Here's my code: models.py: class Account(AbstractUser): pass def __str__(self): return self.username def __unicode__(self): return self.username views.py: try: user = Account.objects.get(username=request.POST['username']) return render(request, 'users/signup.html', {'error': 'Username has already been taken'}) except Account.DoesNotExist: try: user = Account.objects.get(request.POST['email']) return render(request, 'users/signup.html', {'error': 'Email is not available'}) except Account.DoesNotExist: user = Account.objects.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['password']) auth.login(request, user) return redirect('home') Error returned: ValueError at /accounts/signup/ too many values to unpack (expected 2) Traceback: user = Account.objects.get(username=request.POST['username']) Does anybody have a solution? Thank you. -
saving in the database after return user?
here I use essentially Django cookie cutter, to be able to save with a custom shape sign I had to proceed in this way, it works, I'm not sure it's the right way to proceed but I only found this one. I also tested with def Signup() but no results But I realized that the user is not directly saved in the database for this test I put a timer between alt_user and alt_user.name . I noticed that User.object.get gives me the user and that I can modify the rest of the user's information. But when I look at my database, the user's backup is only done after the user returns. Is the user cached before the backup? The problem it poses and that after saving Alt_user.save() I send the id of the one if in a celery task for a longer calculation, thanks you in advance User = get_user_model() class CustomSignupForm(SignupForm): name = CharField( max_length=255) forename = CharField( max_length=255) street = CharField( max_length=255) street_number = IntegerField() city = CharField(max_length=255) country = CountryField().formfield() phone_number = IntegerField() date_of_birth = DateField() affiliate_link = IntegerField(required=False) class Meta: model = get_user_model() # use this function for swapping user model def save(self, request): # Ensure … -
Selenium Chromedriver Won't Start
I'm trying to test my code using selenium with chrome driver. But I always got this error message in my terminal. ====================================================================== ERROR: test_input_status (myweb.tests.StorySixFunctionalTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/fredypasaud/Documents/PPW/story_six/myweb/tests.py", line 58, in setUp self.selenium = webdriver.Chrome('./chromedriver',chrome_options = chrome_options) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__ desired_capabilities=desired_capabilities) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /snap/bin/chromium is no longer running, so ChromeDriver is assuming that Chrome has crashed.) And i put my chromedriver in the same directory as the manage.py of my project. And here's some code about from my test.py from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options class StorySixFunctionalTest(TestCase): def setUp(self): chrome_options = Options() self.selenium = webdriver.Chrome('./chromedriver',chrome_options = chrome_options) chrome_options.add_argument('--dns-prefetch-disable') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('disable-gpu') chrome_options.addArguments("--disable-extensions"); chrome_options.addArguments("--disable-dev-shm-usage"); super(StorySixFunctionalTest, self).setUp() def tearDown(self): self.selenium.quit() super(StorySixFunctionalTest, self).tearDown() def test_input_status(self): selenium = self.selenium selenium.get('http://127.0.0.1:8000/index/') status = selenium.find_element_by_id('id_status') submit = selenium.find_element_by_id('submit') status.send_keys("Coba Coba") submit.send_keys(Keys.RETURN) -
Return wrong URL in Django
When I click link to another page from 'localhost:8000/product_all/all', it's error: "Page Not Found" (Note: 'all' is parameter) It return url 'localhost:8000/product_all/all/index'. But it should be 'localhost:8000/index'. If I change page in another page that not be 'product_all/all', it's normally. (e.g. from 'index' to 'useraccount') my context menu_list = PagesMenu.objects.all() dropdown_list = DropdownMenu.objects.select_related('head_dropdown').all() context = { 'title': 'Ratchapol Optic', 'menu_list': menu_list, 'dropdown_list': dropdown_list, } in polls/views.py if type == 'all': product_list = Product.objects.all() else: product_list = Product.objects.filter(category=type) pd = { 'product_list': product_list, } pd.update(context) return render(request, 'polls/product_all.html', pd) in polls/urls.py path('product_all/<type>/', views.product_all, name='product_all'), path('', views.index, name='index'), -
Pass image from React to Django - The submitted data was not a file. Check the encoding type on the form
I'm trying to pass image via fetch and POST request to Django. Actually it works if I pass it via Postman, it appears in database, and then I can display it on my React page via GET request. Problem is that I can't pass anything to backend using my app. I already wrapped everything into FormData() but still i keep getting error that "The submitted data was not a file. Check the encoding type on the form". Any idea how to fix it? The problem is on backend or front-end part? First I grab image via react-dropzone, then cut it a bit with react-cropper and then try to pass it to django. React: sendData() { const form_data = new FormData() form_data.append('name', this.state.name) form_data.append('preview', this.state.preview.slice(5, this.state.preview.length)) form_data.append('thumb', this.state.thumb) this.state.thumbL && form_data.append('thumbL', this.state.thumbL) this.state.thumbL && form_data.append('thumbS', this.state.thumbS) // for (var pair of form_data.entries()) { // console.log(pair[0]+ ', ' + pair[1]); // } fetch("http://localhost:8000/logo/", { method: 'POST', headers: { 'Accept': 'application/json, text/pain, */*' }, body: form_data }) .then(res => res.json()) .then(resp => console.log(resp)) } onDrop = file => { const logo = file[0].name; const ext = logo.split(".").pop(); const extensions = ["bmp", "png", "jpg", "jpeg", "gif"]; if (extensions.indexOf(ext) === -1) { console.log("wrong format of … -
ModuleNotFoundError: No module named 'tinymce' for Django
So I get the following error: ModuleNotFoundError: No module named 'tinymce' when trying to deploy my Django app to Azure. It works perfectly when I test it locally, but breaks down on Azure. I've already done a pip freeze > requirements.txt and verified that django-tinymce is on that list, I've restarted my server and re-synced my GitHub project. TinyMce has been added to INSTALLED_APPS already. Here are a few code parts along with the error: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'cpu', 'django_cron', 'tinymce', ] #... TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } Error from Azure: … -
expected token ':', got '}' in Django
I am receiving the error message mentioned in the subject of this post when trying to acccess on of my views in Django. I've tried to look at other similar questions but they seemingly frequently have to do with a .html template. In my case, this view is rendering a .docx file. Full Traceback Request Method: POST Request URL: http://127.0.0.1:8000/AESCreate Django Version: 1.11 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'bootstrap_modal_forms', 'smart_selects', 'unit'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/andrews/Desktop/WBU/web_unit/unit/views.py" in AESCreate 867. doc.render(context) File "/Library/Python/2.7/site-packages/docxtpl/__init__.py" in render 266. xml_src = self.build_xml(context, jinja_env) File "/Library/Python/2.7/site-packages/docxtpl/__init__.py" in build_xml 229. xml = self.render_xml(xml, context, jinja_env) File "/Library/Python/2.7/site-packages/docxtpl/__init__.py" in render_xml 217. raise exc Exception Type: TemplateSyntaxError at /AESCreate Exception Value: expected token ':', got '}' views.py def AESCreate(request): reference = request.POST.get('AES_Refs') manifest = Manifests.objects.all().filter(reference__reference=reference) order = Orders.objects.get(reference=reference) today = date.today() sum = Products.objects.filter( Q(manifests__reference__reference=reference)).annotate( total_quantity=Sum('manifests__cases') ) doc = DocxTemplate("AEStemplate.docx") totalFOB = 0 totalCases = 0 for item in manifest: totalFOB += item.cases * item.FOB totalCases += … -
Perform translation (internationalization) using ugettext_lazy in models.py for a dynamic variable
I have a django project where there are multiple models defined and each model have some set of fields with choice fields. These values are being displayed on template using a loop. I have multiple languages defined and using ugettext_lazy, I am able to show the translated value as per the language selected by user. Now I am trying to move these values into database, fetch them and use it in ugettext_lazy for translation. e.g. _(value_from_db) Problem is when using from database, the value doesn't translate whereas when using it as hardcoded e.g. _("translated_val") models.py from django.utils.translation import ugettext_lazy as _ from translated_fields import TranslatedField class ModelClass(models.Model): choices_values = ( (dataframe[(dataframe['name'] == 'State1')]['code'].item(), _("State1")), (dataframe[dataframe['name'] == 'State2']['code'].item(), _(dataframe[dataframe['name'] == 'State2']['value'].item())), (State3, _("State3")) ) In the above example, the translation works properly for State1, State3 but not for State2. I expect State2 to be translated on my template. P.S. All the translation activities have been done properly and are working (if I replace the dataframe fetch for state2 with hardcoded value, it gives the proper tranlation and also the dataframe fetches the same value as the one I had hardcoded) Thanks for the help. -
Weasyprint not rendering images in production
I have a django app running in a nginx server, every static file is laoded correctly, but, but when i'm using weaseyprint to create a pdf, the images are not showing. Using runserver in localhost, the images are shown. Nginx Cinfiguration: location /static/ { autoindex on; alias /var/www/app.com/static; } App settings: STATIC_URL = '/static/' STATIC_ROOT = "/var/www/ciber-seguro.com/static/" File creation: html_string = render_to_string('budget/contract.html', context) html = HTML(string=html_string, base_url=request.build_absolute_uri('/')) pdf = html.write_pdf(stylesheets=[CSS('web/static/css/contract.css')]) dirname = "./files/budgets" filename='budget_'+str(contract.id)+".pdf" response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="'+filename+'"' It's my first time with nginx and django, so its problably a simple problem, but i'm not able to find it. I have the felling it has to do with nginx, but i don't really have a clue. -
Is there a way to execute html inside of a template variable that is a table?
I am creating a website using Django and I have taken a pandas dataframe and stored it as a template variable and passed it to the render request. I would like to make some columns form elements but have been unsuccessful into how to do that. I have already tried applying the function to the pandas dataframe in order to add the proper HTML to each element in the column. However, the HTML itself shows up on the actual site. Here is my python code: def optimizer(request): df = Optimizer.get_daily_roster('E:\website\optimizer\Predictions.csv') df = df.drop(columns=['Name + ID', 'Game Info', 'Unnamed: 0', 'Unnamed: 0.1', 'name']) df = df.rename(columns={'TeamAbbrev': 'Team', 'AvgPointsPerGame': 'Predicted FP'}) df['Predicted FP'] = df['Predicted FP'].apply(lambda x: round(float(x), 2)) df['Predicted FP'] = df['Predicted FP'].apply(lambda x: "<input type='text' value=" + str(x) + ">") df['Min Exposure'] = 0 df['Max Exposure'] = 1 # cols_to_values = df.to_dict(orient='list') # cols_to_values = {x.translate({32: None}): y # for x, y in cols_to_values.items()} html_table = df.to_html(index=False, justify='left', classes=[ 'table table-bordered table-striped table-hover table-responsive table-sm, container-fluid']) return render(request, 'optimizer/optimizer.html', {'player_table': html_table}) And here is my HTML: {% extends "optimizer/base.html" %} {% block content %} <h1>Optimizer</h1> <form method="post"> <input type="submit" value="Generate Lineups"> <div class="table-responsive"> {{ player_table |safe }} </div> </form> {% … -
Getting total debt and remaining debt list with Django
I am working with django-rest-api-framework. I want to list the customers' debts and show the remaining amount. Customer A has four debt records. A customer has "totalDebt" and "totalReceived" fields. I want to calculate the total remaining debt record of each customer. But I want him to calculate on one line. And I want to print it out as json {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('50.00'), 'receivedAmount__sum': Decimal('15.00')}, {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('100.00'), 'receivedAmount__sum': Decimal('15.00')}] {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('50.00'), 'receivedAmount__sum': Decimal('9.00')}, {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('100.00'), 'receivedAmount__sum': Decimal('30.00')}] {'customer__customerKey': UUID('1db32404-272c-47da-801b-965151627afc'), 'totalDebt__sum': Decimal('250.00'), 'receivedAmount__sum': Decimal('80.00')}, {'customer__customerKey': UUID('1db32404-272c-47da-801b-965151627afc'), 'totalDebt__sum': Decimal('250.00'), 'receivedAmount__sum': Decimal('95.00')}, -
How to add different models to only one model in django?
I have some models that are used to make one order per dining table. My goal is to have different dining tables, these always have a total order and the total order has individual orders. I have difficulties when i create a second dining table, with a second total order, to avoid taking orders (relationship) from the first table. How can i make a total order that has his own orders, without any relationships from other orders? Here my models: class Order(models.Model): Beer = models.ForeignKey(Beer, on_delete=models.SET_NULL, blank=True, null=True, related_name='beer') SoftDrink = models.ForeignKey(SoftDrink, on_delete=models.SET_NULL, blank=True, null=True, related_name='soft_drink') ForeignBeer = models.ForeignKey(ForeignBeer, on_delete=models.SET_NULL, blank=True, null=True, related_name='foreign_beer') Liquor = models.ForeignKey(Liquor, on_delete=models.SET_NULL, blank=True, null=True, related_name='liquor') Wine = models.ForeignKey(Wine, on_delete=models.SET_NULL, blank=True, null=True, related_name='wine') BarDrink = models.ForeignKey(BarDrink, on_delete=models.SET_NULL, blank=True, null=True, related_name='bar_drink') Meal = models.ForeignKey(Meal, on_delete=models.SET_NULL, blank=True, null=True, related_name='meal') class TotalOrder(models.Model): Order = models.ManyToManyField(Order, related_name='order') Total_Price = models.DecimalField(default=0, max_digits=6, decimal_places=2) class Table(models.Model): Number = models.IntegerField(unique=True) Total_Order = models.ForeignKey(TotalOrder, on_delete=models.SET_NULL, related_name='total_order', blank=True, null=True) Thanks in advance :D -
Connect MariaDB Column Store to Django
I'm trying to build a dockerized app with django, mariadb for analytical purposes. Unfortunately getting the following error, which i cant connect to columnstore mariadb database from django. dmd_web | Traceback (most recent call last): dmd_web | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection dmd_web | self.connect() dmd_web | File "/usr/local/lib/python3.6/site packages/django/db/backends/base/base.py", line 194, in connect dmd_web | self.connection = self.get_new_connection(conn_params) dmd_web | File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection dmd_web | return Database.connect(**conn_params) dmd_web | File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 84, in Connect dmd_web | return Connection(*args, **kwargs) dmd_web | File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 166, in __init__ dmd_web | super(Connection, self).__init__(*args, **kwargs2) dmd_web | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") dmd_web | dmd_web | The above exception was the direct cause of the following exception: dmd_web | dmd_web | Traceback (most recent call last): dmd_web | File "manage.py", line 15, in <module> dmd_web | execute_from_command_line(sys.argv) dmd_web | File "/usr/local/lib/python3.6/site- packages/django/core/management/__init__.py", line 371, in execute_from_command_line dmd_web | utility.execute() dmd_web | File "/usr/local/lib/python3.6/site- packages/django/core/management/__init__.py", line 365, in execute dmd_web | self.fetch_command(subcommand).run_from_argv(self.argv) dmd_web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv dmd_web | self.execute(*args, **cmd_options) dmd_web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute dmd_web | self.check() dmd_web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check … -
Get users who belongs to groups
I´m trying to get queryset of users who are in group Creator and in a group Teacher, at the same time. test.py where i send array of groups i want to filter: def test_admin_create_authenticated(self): data = {"data": {"alert_type":"system", "text": "UnitTest"}, "filters":{"groups":['Teacher', 'Creator'], "together": True}} url = reverse('admin_alerts-list') response = self.client.post(url, json.dumps(data), content_type="application/json") self.assertEqual(response.status_code, status.HTTP_200_OK) views.py: Here i would like to make a q_objects which will filter groups by name: if 'groups' in filters: print(filters['groups']) try: for group in filters['groups']: q_objects.add(Q(groups__name=group), variable) except: q_objects.add(Q(groups=filters['groups']), variable) And then find all users who are in those groups: print(q_objects) users = User.objects.filter(q_objects) print(users.query) print(users) Terminal: ['Teacher', 'Creator'] (AND: ('groups__name', 'Teacher'), ('groups__name', 'Creator')) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" INNER JOIN "auth_user_groups" ON ("auth_user"."id" = "auth_user_groups"."user_id") INNER JOIN "auth_group" ON ("auth_user_groups"."group_id" = "auth_group"."id") WHERE ("auth_group"."name" = Teacher AND "auth_group"."name" = Creator) <QuerySet []> Why my q_objects doesn´t work? I have one user who is in those 2 groups. -
Set GOOGLE_APPLICATION_CREDENTIALS environment variable in VSCode debugger
I'm testing Google Cloud Pub/Sub on my Django project using VSCode on my Mac, and I'm having some problems setting GCP environment variables during debugging tests, specifically the GOOGLE_APPLICATION_CREDENTIALS environment variable. I am able to set the GOOGLE_APPLICATION_CREDENTIALS for running server and/or tests locally with export GOOGLE_APPLICATION_CREDENTIALS="path/to/json_credential_file.json" in a shell, but as the VSCode debugger runs in a separate shell the env variable is not set when debugging tests. I tried adding the same value to the env key in launch.json: "env": { "GOOGLE_APPLICATION_CREDENTIALS": "path/to/json_credential_file.json" } But it still complains about GOOGLE_APPLICATION_CREDENTIALS not being set: oauth2client.client.ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. Any ideas? -
Django multiple ModelForms from one Model
I need to implement a transaction with a step by step process wherein the user can input the details in step 1 and then process the inputted data which will do some calculations. The user can then proceed to step 2 which displays the initial result and he/she can input additional parameters to manipulate the results. I need to store all user inputs in one model so that if the user cancels the process, all data that was initially stored will be deleted. I am a newbie in django and python so if anyone know how to solve this problem I would really appreciate it. This is what I've tried so far: In my models.py I have: class Calculate(models.Model): date_created = models.DateField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) csv = models.FileField(upload_to='files/') param1 = models.CharField() param2 = models.CharField() param3 = models.CharField() In my forms.py I have: class DetailsInputForm(forms.ModelForm): class Meta: model = Analysis fields = ('date_created', 'csv',) class ParamInputForm(forms.ModelForm): class Meta: model = Analysis fields = ('param1', 'param2', 'param3',) In my views.py I have: class DetailsInputView(LoginRequiredMixin, CreateView): model = Calculate form_class = DetailsInputForm template_name = 'step1.html' login_url = 'login' success_url = reverse_lazy('step2') class ParamInputView(LoginRequiredMixin, CreateView): model = Calculate form_class = ParamsInputForm template_name = … -
File "/Users/susanalokozay/FinalProject/lib/python3.7/site-packages/django/urls/conf.py", line 39, in include
File "/Users/susanalokozay/FinalProject/lib/python3.7/site-packages/django/urls/conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. -
How to setup a Django-site where users have different permissions for different projects
Kind stacky! Hopefully you can help me out. I'm trying to workout a framework on which I can relatively easily develop django-apps and distribute them to the users. Users can use these apps within a 'project' environment, so the data they see in that app is only related to the project they are currently looking at. I'm not referring to Django-projects here, but projects as in a task on which multiple people are working together. :) Users should be able to create a project and invite other users. If a user has no permission for a certain project he cannot access the project. Questions that are spooking through my head are: How do I need to setup my model? How do I go about setting up permissions? How do I make sure they can not access project data to which they don't have permissions. I understand there is not one true solution, but I am looking for recommendations on best practices or working examples. I just don't know how to start. I already searched the internet extensively but I can't find anything that resembles what I want to do. My line of thought currently is to create a project class … -
IntegrityError at /registerdoctor.html NOT NULL constraint failed: auth_user.first_name
I created a Doctor model having a OneToOneField with the Django User model. When I hit the 'Sign Up' button I get an Integrity Error : "IntegrityError at /registerdoctor.html NOT NULL constraint failed: auth_user.first_name" Can someone tell me how do I can fix the error i.e. what changes I should make and where? models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Doctor(models.Model): doctor = models.OneToOneField(User,on_delete=models.CASCADE) #additional exp = models.PositiveIntegerField() phone_no = models.IntegerField() def __str__(self): return self.doctor.username views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from django.contrib import messages from app1.models import Doctor def HomePage(request): return render(request,'homepage.html') def RegisterUser(request): if request.method =="POST": first_name = request.POST["fname"] last_name = request.POST["lname"] email_id = request.POST["mail"] password1 = request.POST["pass1"] password2 = request.POST["pass2"] username = request.POST["username"] if password1==password2: if User.objects.filter(email=email_id).exists(): messages.info(request,"This Email ID is already Registered!") return redirect("registeruser.html") else: if User.objects.filter(username=username).exists(): messages.info(request,"Username taken!") return redirect("registeruser.html") else: user = User.objects.create_user(first_name=first_name,last_name=last_name, email=email_id,password=password1,username=username) user.save() return redirect("/") else: messages.info(request,"Passwords Not Matching!") return redirect("registeruser.html") return redirect("/") else: return render(request,'registeruser.html') def RegisterDoctor(request): if request.method == "POST": first_name = request.POST.get("finame") last_name = request.POST.get("laname") email_id = request.POST.get("emailid") username = request.POST.get('username') phone = request.POST.get("phno") exp = request.POST.get("doc_exp") password1 = request.POST.get("userpassword") password2 = request.POST.get("conpassword") if password1==password2: if User.objects.filter(email=email_id).exists(): messages.info(request,"This … -
How to upload a file outside the admin in wagtail
I want to set up a form that allows users to upload files (pdf, jpeg, docx, etc) from outside the Wagtail admin panel. But the form leaves the filefield out on my html page. Any advice would be great thanks! models.py class FormField(AbstractFormField): page = ParentalKey('FormPage', related_name='form_fields') class FormPage(AbstractEmailForm): template = "formsubmission.html" file = models.FileField(upload_to='uploads/', blank=True, null=True) submit_success = models.CharField(max_length=100, blank=False, null=True) submit_error = models.CharField(max_length=100, blank=False, null=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('submit_success'), FieldPanel('submit_error'), InlinePanel('form_fields', label='Form Fields'), FieldPanel('file') ] htmlpage.html {% extends 'base.html' %} {% load wagtailcore_tags %} {% load static %} {% block content %} <h1>page.title</h1> <div class="container"> <form action="{% pageurl page %}" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit"> </form> {% endblock %} -
How to do Filtering in Djnago?
I have a page where all transaction records are displayed. I want to narrow down the search for key points that are visible in the screenshot. How to implement a search? I tried through a filter(), but I notice that it is somehow inconvenient. Saw that can filter through Q... if request.method == 'POST': search_form = SearchForm(request.POST) if search_form.is_valid(): date1 = date(2000, 5, 2) date2 = date.today() contractor = None if search_form.cleaned_data['date1st']: date1 = search_form.cleaned_data['date1st'] if search_form.cleaned_data['date2st']: date2 = search_form.cleaned_data['date2st'] if search_form.cleaned_data['contractorName']: contractor = search_form.cleaned_data['contractorName'] print(date1) print(date2) paymentsss = Transaction.objects.select_related('currency', 'payment_source__payment_type', 'deal__service', 'deal__service__contractor').filter( payment_date__range=[date1, date2], deal__service__contractor__name=contractor).order_by('-id')[:2700] search_form = SearchForm() paginator = Paginator(paymentsss, 25) page = request.GET.get('page') try: payments = paginator.get_page(page) except(EmptyPage, InvalidPage, PageNotAnInteger): payments = paginator.page(1) data = {'payments': payments, 'form': search_form} return render(request, "payments.html", data) -
In django which is better io.StringIO or ContentFile
What is the difference between io.StringIO() and ContentFile? Which one is better performance-wise?