Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mypy error: BaseCache has no attribute "keys"
I am trying to run a test case involving django cache. Here is my (incomplete) snippet: from django.core.cache import caches class NCRTest(TestCase): def setUp(self) -> None: self.cache = caches['log'] def test_ncr_view(self, mock: Mock) -> None: # code below throws error keys = self.cache.keys(f"ncr:60:*") self.cache.delete_many(keys) When running Mypy test, an error occurred: test_ncr.py: error: "BaseCache" has no attribute "keys" I am trying to delete keys in keys. -
Django template : cant access to the static files outside of Django project
I am trying to access the static files from my django app to the static files that are outside of my django app. I want to access the files in UIUX/static to DjangoRepo/myapp/static. it looks like below UIUX/ - static - staticfile... - templates - index.html DjangoRepo/ - myapp - static - templates my view.py class IndexViewTemplateView(View): # trying to acess the inedx.html file that is outside of Django file template_name = '../../../UIUX/templates/index.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): return render(request, self.template_name) I did not edit my template at all for this. is there any other template setting I need to do to archive this ? TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PROJECT_ROOT, 'templates')], # 'DIRS':[], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], # 'debug': DEBUG, }, }, ] -
NameError 'unicode' not defined, this error occurs when I use save function in django model
NameError at /admin/todo/todomodel/add/ name 'unicode' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/admin/todo/todomodel/add/ Django Version: 2.2 Exception Type: NameError Exception Value: name 'unicode' is not defined Exception Location: C:\Users\PEE TEE\Desktop\ToDoApp\lib\site-packages\slugify.py in slugify, line 24 Python Executable: C:\Users\PEE TEE\Desktop\ToDoApp\Scripts\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\PEE TEE\Desktop\ToDoApp\src', 'C:\Users\PEE TEE\Desktop\ToDoApp\Scripts\python37.zip', 'C:\Users\PEE TEE\Desktop\ToDoApp\DLLs', 'C:\Users\PEE TEE\Desktop\ToDoApp\lib', 'C:\Users\PEE TEE\Desktop\ToDoApp\Scripts', 'c:\users\pee tee\appdata\local\programs\python\python37\Lib', 'c:\users\pee tee\appdata\local\programs\python\python37\DLLs', 'C:\Users\PEE TEE\Desktop\ToDoApp', 'C:\Users\PEE TEE\Desktop\ToDoApp\lib\site-packages'] Server time: Tue, 4 Feb 2020 03:03:37 +0000 And this is my model: from django.db import models from django.db.models.signals import post_save from slugify import slugify Create your models here. class ToDoModel(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) what_todo = models.CharField(max_length=255, default="Event to be done") date_todo = models.DateField(auto_now=False,auto_now_add=False) slug = models.SlugField(null=True, blank=True) def save(self, *args, **kwargs): if self.what_todo and not self.slug: self.slug = slugify(self.what_todo) return super(ToDoModel, self).save(*args, **kwargs) def str(self): return str(self.what_todo) -
How to solve the 404 Not found error of background images?
I tried both ways but the background image is not loading. How to solve this problem? One way style="background-image: url('myapp/Project/home/static/home/images/W2.png');" Second way style="background-image: url('../../home/static/home/images/W2.png');" -
How can I define custom output types for mutations with graphene-django?
Create/remove/update/delete (CRUD) mutations usually return the corresponding database model instance as output type of the mutation. However for non-CRUD mutations I'd like to define business logic specific mutation output types (e.g. returning a list of IDs). How can I achieve this with graphene-django? -
how to create crud template api in django
how to Create CRUD operation API's i.e get, post, update and delete into each table and Create a functional API to insert across table different columns in one. will have two API performing POST API for insertion but need to execute together in functional API. -
Can it be done using Python or HTML5 on Django
Task : I have to get the audio from the user which should be less than one minute and then save it in the backend and send it to Google's Speech Recognition API to get the text. -
Path error in django rest framework : Specifying a namespace in include() without providing an app_name is not supported
In my django rest framework app I have Urls.py as follows: from django.urls import include, path from .shipper import* from .views import * urlpatterns = [path('shipper/', include(path('shipperitems/', MasterItemsList.as_view()), path('shippercreateapi/', shipperCreateAPIView.as_view()),)), ] When I try to run the app it gives me the following error: 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 t he list of patterns and app_name instead. what should I do to resolve this ? -
Django CMS Single Page Application (SPA)
I want to create a website to load only a single HTML page and dynamically update the content of that page as the user interacts with the app. I use Django CMS and Vue js at frontend for this purpose. I tried out this project https://github.com/nirazul/djangocms-test/tree/feature/setup and I went trough the initial setup but it does not work as a Single Page application yet. What is the next step after I go trough the 8 steps? -
Why is background image not working in html?
I want to make the links working but it is not responding. How to make it work? I have other links also which are working signup.html working link <img src="{% static 'users_assets/img/favicon.png' %}"> signup.html not working link <div class="image-container set-full-height" style="background-image: url('static/users_assets/img/wizard-book.jpg')"> Folder structure -
Render images from media directory Django
I have a model to store images of all users. Each user will have an uploaded image as well a thumbnail image. All the images will be stored in the path '/media/users//user_image.jpg' Say the user is ABC: directory structure will be : /media/users/ABC/ABC_image.jpg and /media/users/ABC/thumbnail/ABC_image.img I could get the path of the image from the ImageField of this particular User model. I have a template where I want to display this image. How can I achieve this? -
How do i return Django queryset only if value exists in another table?
Maybe the late hour has my brain fried because I am sure this is incredibly easy. My view is being passed the id of the calllist and I want to return a queryset of candidates that are in the list for user? I have read many posts on values and value lists, but I am struggling. Any help would be appreciated. Candidate.objects.filter(user=self.request.user, ????????) class Candidate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) class CallList(models.Model): prospecting = models.ForeignKey(Prospecting, on_delete=models.CASCADE, null=True) candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) -
whois package cannot be imported
I'm attempting to get this simple package working with my django project, but it's not working: https://github.com/DannyCork/python-whois Steps I took: pip install whois Within my views.py import whois Error that I got: Error: ModuleNotFoundError: No module named 'whois' Any thoughts on why I can't import this? Apparently this package only runs on linux, so I'm not running this on my local machine. This is the error I got when running on my linux webserver. Thanks! -
"message": "add_category matching query does not exist.",
this is my view set class add_category(models.Model): addcategory=models.CharField(max_length=20,null=True,blank=True) def __str__(self): return self.addcategory class sub_category(models.Model): category=models.ForeignKey('add_category', on_delete=models.CASCADE,related_name='xyz') subcategory=models.CharField(max_length=20,null=True,blank=True) def __str__(self): return self.subcategory this is my viewset def create(self,request): try: data=request.data category=data.get('category') subcategory=data.get('subcategory') new=sub_category() new.category=add_category.objects.get(addcategory=category) new.subcategory=subcategory new.save() return Response({'submitted succesfully':True}) except Exception as error: return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
How to pass a list to the SQL query in django
Am using the code below: def internal(request): try: year='' month=[] class=[] results=[] conn = connections["connection1"] cursor = conn.cursor() year = request.GET.get('year') print(year) month = request.GET.getlist('month[]') for i in month: print("Months::"+i) class = request.GET.getlist('class[]') response_list = [] cursor.execute(" select Year,month,student_name,admission_date,class from admission_table\ where MONTH(admission_date) in ('"+(month)+"') AND YEAR(admission_date) in ('"+year+"') AND class in ('"+class+"') ") rows = cursor.fetchall() print(rows) if rows: for row in rows: response_list.append({'year':row[0],'month':row[1],'student_name':row[2],'admission_date':str(row[3]),'class':row[4]}) except Exception as e: print(str(e)) return HttpResponse(json.dumps(response_list)) How to pass a month and class values which are lists to SQL query. Thanks for your help in advance! -
Django - count numbers of same field in a model
I'm new to Django and I'm building an e-commerce website (db: sqlite3). Each item on sale has 1-5 images uploaded. So I've got the model here: class Item(models.Model): '''Item model with maximum 5 images uploaded''' <--snip--> image_1 = models.ImageField(upload_to='items/') image_2 = models.ImageField(upload_to='items/', blank=True) image_3 = models.ImageField(upload_to='items/', blank=True) image_4 = models.ImageField(upload_to='items/', blank=True) image_5 = models.ImageField(upload_to='items/', blank=True) In order to create a carousel (bootstrap4) for each item, I need to know how many images uploaded. My thinking is to create a function in the class to find out how many ImageField there are in this model and how many are not blank. So my question is: 1. is there a better way to create ImageField, a more dynamic way? 2. is it possible to find out the number of the same field in a model that are not blank? -
Issues with csfr token and ajax call
I tried to implement a button on a Website, wich upon pressing it automatically runs a python function on the server and copies some value into the clipboard of the user. The clipboard copying runs fine, but I can not run the python function. Whenever I try to I get an error 403 and I think it is due to an issue with the csfr token. Can anyone help me to solve this issue? Here is my HTML {% if categories %} <div class="card shadow mb-4"> <div class="card-body card-interface"> <table id="predictionTable" class="table table-bordered"> <thead> <tr> <th>Vorhersage</th> <th>Wahrscheinlichkeit</th> <th>Kopieren</th> </tr> </thead> <tbody> {% for category in categories %} <tr> <td>{{ category.0}}</td> <td>{{ category.1}}%</td> <td><img src="{% static "documents/img/copy.png" %}" class="interface-copy" value="{{ category.0 }}" input_text = "{{ input_text }}" style="cursor: pointer"></td> </tr> {% endfor %} </tbody> </table> </div> </div> And here the .js that is run $(".interface-copy").on('click', function(e) { var csrftoken = $("django-data").data().CSRF; console.log(csrftoken); console.log("test") var $temp = $("<input>"); $("body").append($temp); $temp.val($(this).attr('value')).select(); document.execCommand("copy"); $temp.remove(); console.log("test") $.ajax({ url: "/ajax/postSingleSourceEntry/", type : 'POST', beforeSend: function(request){ request.setRequestHeader("X-CSRFToken", csrftoken); }, data: { csfrmiddlewaretoken: csrftoken }, dataType: "json", success: function (data){ console.log("call created") }, error : function(response){ console.log(response) } }) }); Best regards! -
How to pre-fill Django dynamically added formset fields on HTML page
I am using Django inline formset with option to add additional forms at runtime. Some of the fields display the default values as already defined in the related models. However, when new rows of formsets are added, most of the fields are "blank" (i.e. the default values do not show up in those fields), except the date field which show the date widget. As in the image above, a new row containing the blank (red rectangle) field fails to show the default value (as otherwise available in the rows available at page load). I am currently using jQuery to fill the blank fields capturing the "rowadded" function but find it quite a mess, as managing the code is cumbersome. Is there a ready to use function/plugin available in Django which can be used to fill the fields on addition of new row/s (at runtime)? -
Paginator is not showing appropriate result
I want to show only 5 results and next 5 in other page. my view.py class QuestionList(APIView): def get(self, request, *args, **kwargs): res = Question.objects.all() paginator = Paginator(res, 5) serializer = QuestionSerializers(res, many=True) return Response({"Section": serializer.data}) how will my paginator work here ? -
Display custom format name on django admin page
I want to display first name and last name. To achieve that, I have used __str__() method. But it is not working. class OnlineUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user.first_name} {self.user.last_name}" Instead it display, user ID. In admin.py, class OnlineUsersAdmin(admin.ModelAdmin): # a list of displayed columns name. list_display=['user'] admin.site.register(OnlineUsers, OnlineUsersAdmin) Where I'm doing wrong? How to get the format I want? Version: Django==2.0.1 -
iam new in django , static files are not loading on browser only images are loading css, and js are not loading
but the same project is perfectly working on my laptop this is my setting(debug is true) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static', os.path.join(BASE_DIR, 'demo/static')), ) STATIC_ROOT = os.path.join(BASE_DIR, '/static') This is my url from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('demo/', include('demo.urls')), ] -
Unable to access backend using Postman and Authorization toekn
Angular 8 and Django 3. I am getting a user_id and token from django using a custom view class CustomAuthToken. I get a response that has a token and user_id. I am following a tutorial and want to test out the sending a custom header to django to see if the authorization works. I am using Postman and setting the headers to Authorization: Bearer 1a683...9e428. When I send a GET request to http://127.0.0.1:8000/users/dashboard/23 I get a response "detail": "Authentication credentials were not provided." My understanding is providing these headers should work? Or is there something on the client side that decodes the header and sends it back or something? views.py class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, }) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } urls.py urlpatterns = [ path('dashboard/<int:pk>', UserDashboard.as_view(), name='dashboard'), path(r'api-token-auth/', CustomAuthToken.as_view()), ] -
Django collectstatic : is it possible to access static files that are outside of Django Project?
I am trying to access the static file from my django app to static files that are outiside of my django app. I want to copy all the files in UIUX/static to DjangoRepo/myapp/static. it looks like below UIUX/ - static - staticfile... - templates - index.html DjangoRepo/ - myapp - static - templates my setting file STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' # trying to access the static file outside of django file STATICFILES_DIRS = ( #os.path.join(PROJECT_ROOT, 'static/'), "C:/Users/kevin/workspace/UIUX/static" ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' when I run python manage.py collectstatic I get this Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 188, in handle collected = self.collect() File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\contrib\staticfiles\finders.py", line 131, in list for path in utils.get_files(storage, ignore_patterns): File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\contrib\staticfiles\utils.py", line 23, in get_files directories, files = storage.listdir(location) File "C:\Users\iact80h\.virtualenvs\lynx-ocr-python-services-6157-7DFxjqs2\lib\site-packages\django\core\files\storage.py", line 315, in listdir … -
Filter list of object not followed by other object using django orm
I've to model called class InstagramBot(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.CharField(verbose_name='Email', max_length=55) ............ and another model is class Following(models.Model): target = models.ForeignKey(InstagramBot, on_delete=models.CASCADE, related_name='followers_set') follower = models.ForeignKey(InstagramBot, on_delete=models.CASCADE, related_name='targets_set') Now I want to filter list of instagram_bot which is not followed by specific bot, I mean suppose there are 10 bots in Instagram Model, and first bot followed other 5 bots. Now i want to filter all the bots which is not followed by first bot. -
Test database is empty while querying inside a view
I have a scenario where I'm conditionally checking a visitor's registration form data (via subclass of UserCreationForm). If there are no existing Users with the username that the visitor provides, a new User is created. Otherwise, the conditionals are checked and the visitor receives a flash message (ie. f"Username {username} exists. Choose another username." Upon creating a TestCase, I have created an existing User with the usage of User.objects.create_user(). When testing the view, the QuerySet is empty when performing the query User.objects.get(). As a result User.DoesNotExist is raised, which is not the desired outcome. Rather the desired outcome is to branch into the else clause instead. Why would the test database be empty of User instances while testing the view when it was populated in setUpTestData? How can the the test database populated for the event test_views.py class TestCreateNewChef_Case2(TestCase): def setUpTestData(cls): User.objects.create_user( username='masterchef', password='password', ) cls.user_signup_data = { 'username': 'masterchef', 'password1': 'secret', 'password2': 'secret' } print(User.objects.all()) # <QuerySet [<User: masterchef>]> def test_new_chef_sign_up_username_taken(self): response = self.client.post( reverse("chef:register"), self.user_signup_data, follow=True ) self.assertRedirects(response, reverse("chef:register")) self.assertTemplateUsed('chef/register_chef.html') self.assertContains( response, "<p>Username masterchef exists. Choose another username.</p>", html=True ) views.py def register_chef(request): if request.method == 'POST': new_user_form = ChefRegisterationForm(request.POST) if new_user_form.is_valid(): try: user = User.objects.get( username=new_user_form.cleaned_data['username'] ) …