Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rendering a number as 5-stars rating
I'm building a rating system for my website. It's currently working well but I would like to improve the esthetical aspect of the system. I would like to be able to take the rating from the database and display it as a 5-stars rating. Also, if it's not overly complicated, I would like to be able to click on stars to record the rating in the database, rather than writing a number. I'm quite new to web development. In particular, I have no experience with javascript (I only did tutorials found on internet), which I think is required to implement the functionality I'm searching for, so please gives me a little example with your response in order to make me able to understand. For rendering the rating as stars, I have no idea how to do it. For recording the rating as stars, I thought about two solutions : 1) Using django star-ratings but I don't think I have the capabilities required to understand how it works. I already made a post to ask for help and examples about this app but I received no help so I guess I should forget this. 2) Using a form with some appropriate … -
Display messages on LogoutView
I'm using the messages framework for basic things like success messages on user login. This is working fine. I can't get it to work when a user logs out, however. I'm not a web-developer so not particularly strong with django so not sure what i'm doing wrong - there are similar issues: django message when logout Django How to add a logout successful message using the django.contrib.auth? with solutions in using signals - before trying that I'd like to understand why my code below isn't working. I'm clearly missing something! Note in my template i've added a conditional to print some text if there are no messages - this text does print out so my messages.html is definitely being included. views.py class LogoutFormView(SuccessMessageMixin,LogoutView): template_name = 'users/logout.html' success_message = "Successfully logged out." class login_view(SuccessMessageMixin,LoginView): template_name = 'users/login.html' success_message = "Successfully logged in." def get_success_url(self): return reverse('recordings:projects') messages.html {% if messages %} {% for message in messages %} <div class="alert {{ message.tags }} alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span> </button> {{ message }} </div> {% endfor %} {% endif %} in the template both my login redirect and logout.html extends: <div class="container-fluid mt-3 pl-5 pr-5"> {% block messages %} {% … -
Django Subquery Expression contains mixed types. You must set output_field
I am trying to add sum for credits that are taxable my models.py. If I calculate the balance without the taxable_credits it works. The minute I add the taxable_credits into the mix I get the error. class Account(models.Model): name = models.CharField(max_length=32) class Debit(models.Model): account = models.ForeignKey(Account, related_name='debits', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=12, decimal_places=2) class Credit(models.Model): account = models.ForeignKey(Account, related_name='credits', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=12, decimal_places=2) taxable = models.BooleanField(default=False) My test is as follows: lass TestAccount(TestCase): # https://mixedquantum.blogspot.com/2017/08/django-tips-3-subquery-expressions.html def setUp(self) -> None: self.accounts = dict() self.accounts['fox'] = Account.objects.create(name='FOX') self.accounts['dog'] = Account.objects.create(name='DOG') self.accounts['snake'] = Account.objects.create(name='SNAKE') """ # Credits +----------------+-----------------+-----------------+ | account_name | credit_amount | taxable | |----------------+-----------------|-----------------+ | FOX | 100.0 | False | | SNAKE | 50.0 | False | | SNAKE | 20.0 | False | | DOG | 300.0 | False | | DOG | 100.0 | True | +----------------+-----------------+-----------------+ """ Credit.objects.create(account=self.accounts['fox'], amount=Decimal('100.0')) Credit.objects.create(account=self.accounts['snake'], amount=Decimal('50.0')) Credit.objects.create(account=self.accounts['snake'], amount=Decimal('20.0')) Credit.objects.create(account=self.accounts['dog'], amount=Decimal('300.0')) Credit.objects.create(account=self.accounts['dog'], amount=Decimal('100.0'), taxable=True) """ # Debits +----------------+----------------+ | account_name | dedit_amount | |----------------+----------------| | FOX | 40.0 | | SNAKE | 30.0 | | DOG | 12.0 | | DOG | 23.0 | +----------------+----------------+ """ Debit.objects.create(account=self.accounts['fox'], amount=Decimal('40.0')) Debit.objects.create(account=self.accounts['snake'], amount=Decimal('30.0')) Debit.objects.create(account=self.accounts['dog'], amount=Decimal('12.0')) Debit.objects.create(account=self.accounts['dog'], amount=Decimal('23.0')) def test_sum(self): credits = Credit.objects.filter( account=OuterRef('pk')).values('account_id').annotate(sum_credits=Sum('amount')) taxable_credits = Credit.objects.filter( … -
How to group by values based on common elements of the queryset in Django view?
I'm new to Django and I need this data to render some chart please help I must get my queryset as a dictionary in a specific structure This is my view: def pr1(request): fdate = unidecode(str(request.GET.get('fdate'))) tdate = unidecode(str(request.GET.get('tdate'))) dataSource = OrderedDict() dataSource["dataset"] = [] for key in Production.objects.filter(date__range=(fdate, tdate)).values('date', 'comName').annotate(total_qty=Sum('qty')): seriesname = {} data = {} data["seriesname"] = key['comName'] data["value"] = key['total_qty'] dataSource["dataset"].append(data) This is output of my query: [ {'date': '1398/08/01', 'comName': 'a', 'total_qty': 253.0}, {'date': '1398/08/02', 'comName': 'a', 'total_qty': 263.0}, {'date': '1398/08/01', 'comName': 'b', 'total_qty': 3.938}, {'date': '1398/08/02', 'comName': 'b', 'total_qty': 31.625} ] datasource after appending: "dataset": [ { "seriesname": "a", "value": 253 }, { "seriesname": "a", "value": 263 }, { "seriesname": "b", "value": 3.938 }, { "seriesname": "b", "value": 31.625 } but I have to get it as following: "dataset": [ { "seriesname": "a", "data": [ { "value": "253" }, { "value": "263" }]}, { "seriesname": "b", "data": [ { "value": "3.938" }, { "value": "31.625" }]} ] -
Django Effecient way to Perform Query on M2M
class A(models.Model) results = models.TextField() class B(models.Model) name = models.CharField(max_length=20) res = models.ManyToManyField(A) Let's suppose we have above 2 models. A model has thousands of objects. I would like to know what about be the best efficient/fastest way to get all the results objects of particular B object. Let's suppose we have to retrieve all results for object number 5 of B A.objects.filter(b__id=5) (OR) B.objects.get(id=5).res.all() -
Create custom domain CNAME for AWS S3 static and media files using Django
Let's say site is example.com Bucket Name S3: example URL to static / media files: example.s3.amazonaws.com What steps needs to be done to server static files over CNAME likes this: media.example.com Now the images are served like: https://example.s3.amazonaws.com/static/image.jpg Would like to have it like this: https://media.example.com/static/image.jpg Also the reason is that I can verify the CNAME in the webmaster tools. production.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(ROOT_DIR('staticfiles')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( str(APPS_DIR.path('static')), ) # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) # MEDIA CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR('media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' # DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' DEFAULT_FILE_STORAGE = 'config.custom_storages.MediaStorage' THUMBNAIL_DEFAULT_STORAGE = 'config.custom_storages.MediaStorage' AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = env('REGION_NAME') # e.g. us-east-2 AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME) AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() AWS_DEFAULT_ACL = "public-read" # AWS cache settings, don't change unless you know what you're doing: AWS_EXPIRY = 60 * 60 * 24 * 7 # TODO See: https://github.com/jschneier/django-storages/issues/47 # Revert the following and use str after the above-mentioned bug is fixed … -
How to fill a form field based on the value of an autocomplete field in Django template using Ajax+jQuery
In my application, I am using Ajax+jQuery to populate the unit of measure field based on a product selected by the user using a dropdown. In my products model, each product has been assigned a unit of measure and is picked up to autofill the unit field during order creation. I am using jQuery to pick up the product from select field and capturing the event using .on('change') event. Following are the objects: models.py Model : Product class Product(models.Model): product_id = models.IntegerField(primary_key=True, default=300000000000000000) description = models.CharField(max_length=100, help_text='Prod.Short text') default_uom = models.ForeignKey(Unit_of_Measure, null=True, on_delete=models.CASCADE, verbose_name='UoM') def __str__(self): return '{0} : {1}'.format(self.product_id, self.description) Model : Unit_of_Measure class Unit_of_Measure(models.Model): uom = models.CharField(max_length=4, unique=True, help_text='Units of measure') uom_desc = models.CharField(max_length=50, null=True, help_text='Base UoM description') def __str__(self): return '{0} ({1})'.format(self.uom, self.uom_desc) views.py Function View def fill_UoM(request): product_id = request.GET.get('product_id', None) data = {'default_uom': Product.objects.get(product_id=int(product_id)).default_uom.id} return JsonResponse(data) Ajax Function function fillUoM() { $.ajax({ url: '{% url 'fill_unit_of_meas' %}', data: {"product_id": matl_sel}, dataType: 'json', success: function(data) {console.log('The value captured is: ' + data.default_uom)}, error: function(data) {console.log('Data could not be retrieved')} }); }; urls.py (Root): for ajax urlpatterns = [ # ... path('ajax/uom/', fill_UoM, name='fill_unit_of_meas'), # ... With the above arrangement, I am able to fill the unit … -
Bandit issue B108:hardcoded_tmp_directory and B102:exec_used
I ran bandit on my project and got the following issue for security, I don't understand why this is an issue and what are the solutions for the issues. -------------------------------------------------- >> Issue: [B108:hardcoded_tmp_directory] Probable insecure usage of temp file/directory. Severity: Medium Confidence: Medium Location: abc/xyz/xxx.py:176 More Info: https://bandit.readthedocs.io/en/latest/plugins/b108_hardcoded_tmp_directory.html 175 def get_pickle_file_path(self): 176 return os.path.join("/tmp/aaa", "folder_" + self.name) 177 -------------------------------------------------- >> Issue: [B102:exec_used] Use of exec detected. Severity: Medium Confidence: High Location: abc/models.py:1405 More Info: https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html 1404 loc = {'result': []} 1405 exec(self.code, globals(), loc) 1406 return loc['result'] After searching for the solution of B108 issue. I found this where /tmp is replaced by tempfile.gettempdir() function, but the value of the both is same. Is tempfile.gettempdir() the solution for /tmp? -
GeoDjango save ModelForm that contains PolygonField
I am trying to implement a simple ModelForm in Django, but it looks like I am missing something. What I have right now is the following: models.py class DogParks(models.Model): park_name_en = models.CharField(max_length=256) description = models.TextField() 'picture = models.ImageField()' geom = PolygonField() def __unicode__(self): return self.title forms.py class DogParkForm(forms.ModelForm): geom = PolygonField() class Meta: model = DogParks fields = ('park_name_en', 'description', 'geom') and in views.py def dog_park_insert(request): if request.method == 'POST': form = DogParkForm(request.POST) if form.is_valid(): form_instance = form.save(commit=False) form_instance.as_json() form_instance.save() return HttpResponse('save!') else: return HttpResponse(form.errors) else: form = DogParkForm() return render(request, 'adddogpark.html', {'form': form}) the problem is that when I try t save the form I get the following error: TypeError TypeError: <Polygon object at 0x7fc11e4a4780> is not JSON serializable should I use a Serializer and if yes how or where should I serialize? any ideas would be helpful -
What is best practice when using ValidationError and Constraint (new in Django 2.2)?
Edit: I am using PostgreSQL I have a model that has 4 phone number fields, and I run a ValidationError at the Model level using clean: class Person(models.Model): personal_phone_mobile = PhoneNumberField() personal_phone_direct = PhoneNumberField() company_phone_mobile = PhoneNumberField() company_phone_direct = PhoneNumberField() def clean(self): """Ensure that at least one phone number for personal and company contact phone is provided (either mobile or direct).""" error_dict = {} if self.personal_id_type == 0 and self.personal_id: error_dict['personal_id_type'] = ValidationError( "ID type can not be 'None' if you have set a value." ) if self.personal_phone_mobile is None and self.personal_phone_direct is None: error_dict['personal_phone_direct'] = ValidationError( 'Please enter at least one personal phone number' ) error_dict['personal_phone_mobile'] = ValidationError( 'Please enter at least one personal phone number' ) if self.company_phone_mobile is None and self.company_phone_direct is None: error_dict['company_phone_direct'] = ValidationError( 'Please enter at least one company phone number' ) error_dict['company_phone_mobile'] = ValidationError( 'Please enter at least one company phone number' ) if error_dict: raise ValidationError(error_dict) This works fine as expected. In Django 2.2, model Contraints were introduced which create constraints at the database level. Is it best practice to: Replace model ValidationError with Constraint Use only ValidationErrors (I am not sure the above logic is possible with a Constraint?) Keep both? … -
Remotely running python script from Django
On my Pi3 running Raspian, Apache server I have a Django App. I'm trying to run a python file from Django. If I SSH into my Pi and type "python test_data.py", it runs fine. I SSH in as user "pi" test_data.py is just this. output = "success!" print(output) urls.py url(r'^mygame/$', views.my_game), views.py file I have the following from subprocess import PIPE, run def my_game(request): command = ['sudo', 'python test_data.py'] result = run(command, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True) return render(request, 'rungame.html',{'data1':result}) When /mygame is called via the web browser, here is the result I get printed in rungame.html, so I know it calls test_data.py. It appears to be a permissions issue? I don't understand what the following means. Can someone advise if this is a permissions issue and how do I fix it? CompletedProcess(args=['sudo', 'python mygame.py'], returncode=1, stdout='', stderr='usage: sudo -h | -K | -k | -V\ nusage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]\ nusage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user]\n [command]\ nusage: sudo [-AbEHknPS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p\n prompt] [-u user] [VAR=value] [-i|-s] [<command>]\ nusage: sudo -e [-AknS] [-r role] [-t type] … -
ModuleNotFound error Django and Heroku deployment
I am new to Django and to programming overall, and I am trying to deploy my personal website developed with Django to heroku. I feel like I am at the last step but one error keeps bugging me and I cannot solve it on my own or with documentation. My project folders are like this: enter image description here My Procfile: enter image description here My wsgi file: enter image description here And in the heroku logs I get the following: 2020-01-04T15:45:47.211072+00:00 app[web.1]: ModuleNotFoundError: No module named 'blog' There are many blue lines but I believe this is the one that is problematic (i.e. not being able to find the settings file from this) Is there anything else I can provide if this is not clear? Thanks for any help I welcome any questions -
'scp' is not recognized as an internal or external command
I'm trying to deploy my django website to a linux server using linode. I just created my enviroment. Now im in the process to copy my project onto the server using this command: scp -r excelsite *****@*****:~/ I'm using windows 10 but following a youtube video (which is on mac). I got through half of the video, some problems, but easily fixable using puTTY. But, instead of copying the file it gives out this error: 'scp' is not recognized as an internal or external command Thanks in advance!! -
How to route the URL to separate views based on the value of a certain query parameter in urls.py Django?
I've recently started with Django and I'm unable to understand how to route the URL based on the value of a 'action' parameter which'll be passed along with some other parameters in the URL. So the goal is to filer out the value of the 'action' parameter and routing the url to seperate views accordingly. For example.. If the URL is:- /api/?param1=value&param2=value&action=status it should be routed to the status view if it's /api/?param1=value&action=add&param2=value be routed to the add view and so on no matter the value and position of the other parameters. -
Python manage.py runserver doesn't work on a project (Django)
So I made my own project it worked with python manage.py runserver but when I tried with a new project, it's a challenge project and the challenge is to improve the django app. I use Python 3.8.1 (64-bit) and when I write python manage.py runserver on Admin Powershell it gives me this error: Traceback (most recent call last): File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\thatp\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\djangoProjects\django-challenge-master\app\mailer\models.py", line 6, in <module> from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name … -
Serializer field validation and how to check if value exist?
I have 2 models, User and UserProfile. UserProfile model has OneToOneField with User model. Here I am trying to update both the models in a single request. Request Payload: {'email': ['xxx@gmail.com'], 'first_name': ['Nalin'], 'last_name': ['Dobhal'],} I have created serializer for both models. serializers.py class UserAccountSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False, read_only=True) mobile = serializers.IntegerField(read_only=True) email = serializers.EmailField(required=False, read_only=False) username = serializers.CharField(read_only=True) class Meta: model = User fields = ("id", "mobile", 'email', "username",) class UserProfileSerializer(serializers.ModelSerializer): user = UserAccountSerializer(required=False, read_only=False) # other fields class Meta: model = UserProfile fields = ("user", # other fields) def update(self, instance, validated_data): # validated data doesn't have email here, that's why getting value from self.initial_data if self.initial_data.get("email"): instance.user.email = self.initial_data.get("email") instance.user.save() instance.save() return instance views.py class UserAccountSettingsAPI(generics.RetrieveUpdateAPIView): http_method_names = ["options", "get", "put", "patch"] permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) serializer_class = UserProfileSerializer def get(self, request, *args, **kwargs): # some processing def update(self, request, *args, **kwargs): profile = UserProfile.objects.select_related("user").get(user_id=request.user.id) serializer = self.get_serializer(profile, data=request.data) if serializer.is_valid(raise_exception=False): serializer.save() # some other processing only to set key value for context. return Response(context) I would like to perform some validation before updating user's email. So my question is where to perform that validation? And is there any better way of doing this? I … -
Get image.url as atributte in a related model in django template
I have a ListView where a I want to list products. The problem is that I can't get the related image of these products as they are in a different model. The model for products is: class Product(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='marca') name = models.CharField('nombre', max_length=40) description = models.TextField('descripción', blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) slug = models.SlugField(max_length=50) active = models.BooleanField('activo',default=True) in_stock = models.BooleanField('en stock', default=True) tags = models.ManyToManyField(ProductTag, blank=True) date_updated = models.DateTimeField('última actualización', auto_now=True) The model of images is: class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='producto') image = models.ImageField('imagen', upload_to="product-images") thumbnail = models.ImageField('miniatura', upload_to="product-thumbnails", null=True) To get both models in the template I used context.update in the view. class ProductListView(ListView): template_name = 'product_list.html' context_object_name = 'products_list' model = models.Product paginate_by = 4 def get_context_data(self, **kwargs): context = super(ProductListView, self).get_context_data(**kwargs) context.update({'product_images_list': models.ProductImage.objects.all()}) return context def get_queryset(self): tag = self.kwargs['tag'] self.tag = None if tag != 'all': self.tag = get_object_or_404(models.ProductTag, slug=tag) if self.tag: products = models.Product.objects.active().filter(tags=self.tag) else: products = models.Product.objects.active() return products.order_by('name') Additionally, I created a filter to iterate both models in a forloop but I think is useless as I don't want to iterate both models, I just want to get the first image that matches the product's FK to … -
How to check if a wagtail block contains given text
I have a wagtail/django template that contains {% for block in page.content %} {% include_block block %} {% if "Email address:" in block %} This is an email address {% endif %} {% endfor %} The block does contain the text, but the if clause does not return True What is wrong? -
Getting BlobNotFound while configuring django static and media files
I have an Vuejs application running with Django framework, currently application running in production mode with static files are in local server, instead of serving files from location server want to keep in Azure storage Followed below URL and made the changes to keep media and static files to azure https://medium.com/@DawlysD/django-using-azure-blob-storage-to-handle-static-media-assets-from-scratch-90cbbc7d56be Here is my setting.py in djando STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist', 'static'), ] # Added for Azure storage STATICFILES_STORAGE ='storages.backends.azure_storage.AzureStorage' DEFAULT_FILE_STORAGE = 'backend.custom_azure.AzureMediaStorage' AZURE_ACCOUNT_NAME = os.environ['AZURE_ACCOUNT_NAME'] AZURE_ACCOUNT_KEY = os.environ['AZURE_ACCOUNT_KEY'] AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_LOCATION = 'static' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' AZURE_LOCATION = 'containertest04' AZURE_CONTAINER = 'containertest04' MEDIA_LOCATION = "media" MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' Facing 2 issues 1) Getting below error in django log while running "python3.7 manage.py collectstatic" also uploading files from my application 2020-01-04 14:50:59,888 azure.storage.common.storageclient INFO Client-Request-ID=9e944449-2f01-11ea-9a8b-000d3a3be0ea Operation failed: checking if the operation should be retried. Current retry count=0, Server-Timestamp=Sat, 04 Jan 2020 14:50:59 GMT, Server-Request-ID=a1e7153a-401e-00df-690e-c38686000000, HTTP status code=404, Exception=The specified blob does not exist. ErrorCode: BlobNotFound. 2020-01-04 14:50:59,888 azure.storage.common.storageclient ERROR Client-Request-ID=9e944449-2f01-11ea-9a8b-000d3a3be0ea Retry policy did not allow for a retry: Server-Timestamp=Sat, 04 Jan 2020 14:50:59 GMT, Server-Request-ID=a1e7153a-401e-00df-690e-c38686000000, HTTP status code=404, Exception=The specified blob does not exist. ErrorCode: BlobNotFound. 2) Both static and media files are going to the container containertest04, … -
Testing Django GraphQL API with database
I am using from graphene_django.utils.testing import GraphQLTestCase to implement my tests. However, the result from response = self.query(...) is always empty. I read in Django Test Database looks empty while test is runnin that this is a result from GraphQLTestCase inheriting from TestCase. This post is very old (2012) but I can not seem to find any documentation on how to use a propper test database. Sorry if I have mist something, and the answer was obvious. Thanks -
i would like to integrate a template for my django project?
i'm working in a django project and i want to integrate a template to make front end develeopment more easier ?? any one can dvice me . i'm using django 3.0.1 i tried to integrate Jinja but it doesn't work . -
How can I make the UUIDField shorter in Django?
So for my webapp, I have this code for my Post model import uuid id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) So that's all fine and well, but I get this error when I go to create a Post object. But I get this error Python int too large to convert to SQLite INTEGER So I need to somehow shorten the length of it down to something like 12 so I don't get this error, but I haven't been able to find anything anywhere on how to do this in Django. -
Object has no attribute 'get_absolute_url' in UpdateView when it is defined in the model
I have a Company model: class Company(models.Model): company_name = models.CharField(max_length=255) def get_absolute_url(self): return reverse('company_detail', kwargs={'pk': self.pk}) Which I use in an UpdateView CBV: class CompanyUpdate(UpdateView): model = Company template_name = 'companies/company_update.html' fields = '__all__' This view renders fine. However when I submit the form I get the error: AttributeError at /company/update/1/ 'CompanyUpdate' object has no attribute 'get_absolute_url' I am able to see that the get_absolute_url is there in the admin console and shows the correct path values by including it in list_display = ('get_absolute_url') in the AdminModel settings. What am I missing here? -
What is the purpose of third-party, reusable django app tests for the app consumer?
I've been using Django for under a year and would like clarification on the role of tests within a reusable django app. Popular apps, for example, like django-allauth - https://github.com/pennersr/django-allauth - come with tests. From the point of view of the app consumer what is the purpose of these tests? I can see when I run - python manage.py test That only MY tests are executed and not the app tests. Furthermore when I did run the tests - python manage.py test allauth.account Pretty much everything failed. For example the first test failed because allauth tried to create a user object with a keyword 'username' which isn't how my project user model is configured (I just have an email field). So these tests which all-auth provides are supposed to run within which project exactly? I'd have thought app designers should create tests which accommodate any proper app consumer project config. That way running the tests informs you whether or not your project is correctly integrated from the consumed apps point of view. I noticed a similar question but it doesn't really help with my more general question - How to test single application (not project) in Django? By the way … -
how i save post with the current user without viewing all user list in the endpoint in django rest framework
i was be able to create posting blog with django rest api and its almost ok, put i found that when i post request throw DRF endpoint dashbored,it views all the user list in dropdown menu,i dont wannt that,i want it to plug the current user without let it being edited in the endpoint this is the code class Tarh(models.Model): title = models.CharField(max_length=255) context = models.TextField(default="nothing") user = models.ForeignKey(User,on_delete=models.CASCADE) publishedDate = models.DateTimeField(auto_now_add=True) rating = models.IntegerField(default=0) img = models.TextField(null=True) Serializer class TarhSerializer(serializers.ModelSerializer): class Meta: model = Tarh fields = ( 'title',"user" ,'context','rating','publishedDate','img','pk') ViewSet class TarhViewSet(viewsets.ModelViewSet): """ API endpoint that allows Tarh to be viewed or edited. """ queryset = Tarh.objects.all() serializer_class = TarhSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) i wanna hide this dropdown menu of users list and just post the post with the current user