Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - ImportError at /graphql
Well, I tried to start GraphQL on Django's local server. But got a mistake that: You need to pass a valid Django Model in UserType.Meta, received "auth.User". Exception value is: Exception Value: You need to pass a valid Django Model in UserType.Meta, received "auth.User". To be honest, I don't really understand where I can find 'UserType.Meta. The model about users looks like: # user - связь с пользователем один-к-одному # website - юрл, по которому можно больше узнать о пользователе # bio - о себе (Капитан Очевидность) class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, ) website = models.URLField(blank=True) bio = models.CharField(max_length=240, blank=True) # __str__ - более удобное отобажение в админке def __str__(self): return self.user.name So, what can I do to solve this problem? -
How to work pdf file at step by step slides in django template
I added a next button in my html code which will redirect me to my the same views.py function as shown above and t shall increment by 5 thus showing me my next 5 slides. However this seems not to . -
How to replicate Rails `timestamps` in Django
In Rails migrations I can call a function called timestamps in a migration when creating a table to add created_at and updated_at fields to the table. I can do this in django by creating a new abstract model class TimestampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) updated_at = models.DateTimeField(auto_now=True, null=False, blank=False) class Meta: abstract = True and then in my model just inheriting from TimestampedModel. But I'm not a massive fan of inheritance and I'd rather have some function timestamps that I can add to my model like: class UserModel(models.Model): timestamps() Is this possible in django? If it is, it seems like a useful technique in general, but unfortunately hard to google for. Thanks! -
Django DateTimeField says "You are 4.5 hours ahead of server time" even with setting the "TIME_ZONE"
When I want to set a date for a DateTimeField in django admin dashboard , there's a Note: You are 4.5 hours ahead of server time under the Time field and when I click Now for the Time field the value will be 9:40 while the actual time is 14:10 settings.py # ... LANGUAGE_CODE = "en-us" TIME_ZONE = "Asia/Tehran" USE_I18N = True USE_L10N = True USE_TZ = True # ... -
Upload video file to the Django Backend from Flutter
I have Implemented the mentioned function to upload the video file in the dart file where I ad the frontend implementation of uploading video. `Future uploadVideo(File videoFile) async { var uri = Uri.parse("http://192.168.1.6:8000/videos/"); var request = new http.MultipartRequest("POST", uri); var multipartFile = await MultipartFile.fromPath( "video", videoFile.path, ); request.files.add(multipartFile); StreamedResponse response = await request.send(); response.stream.transform(utf8.decoder).listen((value) { print('value'); print(value); }); print(videoFile.path); print(response.statusCode); if (response.statusCode == 200) { print("video uploaded"); } else { print("video upload failed"); } } ` While calling this method, Getting the status code 400 (Bad Request). How can I overcome this problem? Using Xampp Server and Using the MySQL local database in the backend. -
Async long running functions in Django REST framework
Using Django REST Framework (DRF) one API I'm implementing kicks of a function that can take a while. Callers don't have to know the result ('fire and forget') so they could have an immediate response. Django has async views now and that would solve the problem by calling the long running function asynchronously. But DRF doesn't have async support at the moment. Other suggestions I've seen is using Celery but that is a big step in both code and infrastructure. What is the easiest way to spawn the long running function in a sepate process? I must say that this long running process does need access to the ORM. I'm extending ModelViewSet: class myViewSet(viewsets.ModelViewSet): def update(self, request, *args, **kwargs): # This should be async ('fire and forget') long_running_function() -
Why images on Cloudinary don't appear?
I'm trying to implement cloudinary storage in my django project. Images are loaded successfully to cloudinary but when I create a post with image, images don't appear. Here is a URL of one image https://res.cloudinary.com/dewqgxp2a/image/upload/v1/media/images/posts/2021/07/slide02_CO2UtgA.jpeg As you see it, images are uploaded on Cloudinary but it's impossible to access the images. So when the browser tries to access that image it fails and image doesn't appear. How can solve it please? I need really your help! Here are configs in my settings.py INSTALLED_APPS: [ ... 'django.contrib.staticfiles', 'cloudinary_storage', 'cloudinary', ] # Cloudinary storage configs CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'cloud name', 'API_KEY' : 'cloud key', 'API_SECRET' : 'api secret', 'SECURE' : True, } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' For security reasons, I replaced cloudinary configs by texts. Could anyone help me please? -
How to write secure rules for firebase when using custom authentication?
I am building an app with django and firebase. I have built my custom authentication system. And I need secure rules so that only people whom I have authenticated can read/write in the database or storage. { "rules": { ".read": true, ".write": true } } These are my current rules, so is their a way to pass a token when I request(read or write on databse) which is first checked. Something like -> { "rules": { ".write": "isAuthorized == true", ".read": "isAuthorized == true" } } And when making request to database like- db.child('test').get() I pass this isAuthorized bool Any help is appreciated, or you can suggest changes. -
How to Increment a column when adding new row into HTML Table using Java script
My requirement is to add a new blank row using java script to a table and increment one column based on previous row ( other columns need to blank) . I have tried many ways but unable to figure out. Below is the code I am using. it works fine when I add a row for the first time but after that the cell value is not getting incremented , also please help on how to achieve copy functionality with same cell value incremented for each row copied. can some one please help on how to fix it ? <html> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/cesiumjs/1.78/Build/Cesium/Cesium.js"></script> <script type="text/javascript"> function addRow(row){ var i = row.parentNode.parentNode.rowIndex; var tr = document.getElementById('Table').insertRow(i+1); tr.innerHTML = row.parentNode.parentNode.innerHTML; var currentShipUnit = tr.querySelector("input[name='ShipUnitId']").value; console.log(currentShipUnit); tr.querySelector("input[name='ShipUnitId']").value = ++currentShipUnit; } </script> <body> <table id="Table" border="" class="w3-table-all"> <thead> <tr class="w3-teal"> <th>BOX</th> <th >NUMBERS</th> <th >LENGTH</th> <th >WIDTH</th> <th >HEIGHT</th> <th >WEIGHT</th> <th >LEGNTH UOM</th> <th >WEIGHT UOM</th> <th>FEATURES</th> <th></th> </tr> </thead> <tbody> <tr> <td><input size=10 type="text" readonly=True name="ShipUnitId" value='100'></td> <td> <select id="palletgid" name="palletgid" class=""> <option id="prb3" value="" selected></option> <option value="">ABC</option> <option value="">CDE</option> <option value="">FRT</option> </select> </td> <td class="inputlength2" id="length"><input size=10 id="inputlength" class="inputlength" type="text" contenteditable='true' value=''></td> <td id="width"><input size=10 id="inputwidth" … -
Django - static files are not found in root static folder, but settings point to it
I'm starting to configure my first Django project and I find this issue which is really bothering me. I have set a root static folder to put some css files for my base template there, but Django is not finding any css files there. My settings.py are like this: ... BASE_DIR = Path(__file__).resolve().parent.parent ... STATIC_URL = '/static/' SATICFILES_DIRS = [ BASE_DIR / 'static', BASE_DIR / 'sales' / 'static' ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' ... ... And in my urls.py I have: urlpatterns = [ path('admin/', admin.site.urls), path('', include('sales.urls', namespace='sales')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT, show_indexes=True) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes=True) ... If a run findstatic I get the following: $ python manage.py findstatic --verbosity 2 static No matching file found for 'static'. Looking in the following locations: /home/dancab/git/django-3-course/myenv/lib/python3.9/site-packages/django/contrib/admin/static /home/dancab/git/django-3-course/src/sales/static And also, in the browser, I can see the list of files in the MEDIA folder, but I can't see the STATIC folder, I get the following error: I don't understand why I Django finds the MEDIA folder and not the STATIC folder. Thanks in advance to anyone that gives me a hint on why this happens. -
Django cronjob is still running even after deletion
In one of my past project developed in Django python framework, I needed a cronjob to automate some process. I used this django-cron module and installed it as per their documentation. Everything was working as usual. Recently, the project was discontinued and every code and related processes were removed. But I found that the cronjob related to that project is still running. I double checked with crontab -e, the cronjob is not there. I tried by reloading and restarting the cron daemon, even I restart the whole server, but in vain. If I check in /var/log/syslog, I still can see the cron is running every minute. Here is the output from syslog. Jul 25 08:33:01 CRON[26412]: (ubuntu) CMD (cd /home/projects/pdf-generator && /home/venv/django/bin/python manage.py runcrons core.myapp.crons.PdfConversionCronJob) The server is running Ubuntu 18.04. Does anyone know what is going on and how to remove the cronjob for once and all? -
I'm unable to login in admin and login is not working in Django project after Custom User
Tysm in advance, for helping Already a superuser is made but admin login or login view is not working, Some problem in authenticate it every time returns none if correct password and email are passed Custom User Model class UserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Email Requierd!") if not username: raise ValueError("Username required!") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): userid = models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True) username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perm(self, app_label): return True Already a superuser is made but admin login or login view is not working, Some problem in authenticate it every time returns none if password and email are passed! psql view login view def login_view(request): user = request.user if user.is_authenticated: return redirect('home') if request.POST: form = LoginForm(request.POST) if form.is_valid(): … -
How to get fully randomised serialisation data from Django filter
I have the following serialization and intend to get query data fully randomized. class RecommendationList(generics.ListAPIView): model = Obj serializer_class = RecommendationFilterSerializer filter_backends = [filters.SearchFilter] search_fields = ['uuid', ] pagination_class = StandardResultsSetPagination def get_queryset(self): uuid = self.request.query_params.get('uuid') Obj.objects.filter(user=Obj_list[0].user) .filter(Q(status=Obj.Status.PUBLISHED)) .filter(Q(privacy=Obj.Privacy.PUBLIC)) .order_by('uploaded_at').reverse() return Obj.objects.filter(Q(status=Obj.Status.PUBLISHED) & Q(approved=True)) .filter(Q(privacy=Obj.Privacy.PUBLIC)) .order_by('?') There are suggestions for results returning two rows : import random last = MyModel.objects.count() - 1 index1 = random.randint(0, last) # Here's one simple way to keep even distribution for # index2 while still gauranteeing not to match index1. index2 = random.randint(0, last - 1) if index2 == index1: index2 = last # This syntax will generate "OFFSET=indexN LIMIT=1" queries # so each returns a single record with no extraneous data. MyObj1 = MyModel.objects.all()[index1] MyObj2 = MyModel.objects.all()[index2] However, the size of table rows is more than 10000, and while serializing the request might need to access all 10000 items. Fulfilling this requirement and regarding the size of the table ORDER_BY('?') becomes a very costly operation, hence I cannot use the following. Any suggestions on this? -
Redis Connection Issue with Django in VPS Server
I have installed redis in the vps (ubuntu server) and able to connect to it using redis-cli command: redis-cli -h ip_address But when I tried to access apis that uses redis in django it is throwing connection refused error. redis.exceptions.ConnectionError: Error 111 connecting to ip_address:6379. Connection refused. Enabled firewall in ubuntu using : sudo ufw enable Output of sudo ufw status: 6379 ports enabled Updated redis.conf files: bind ip_address protected-mode no But still facing the issue, Any suggestions are helpfull Thanks in advance -
Django is form not showing up
my form is not showing up. Could someone please help me media_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md-6"> <div class="card card-body"> <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="Submit"> </form> </div> </div> </div> {% endblock %} dashboard.html {% extends 'accounts/main.html' %} {% block content %} {% include 'accounts/status.html' %} <br> <a class="btn btn-primary btn-sm btn-block" href="{% url 'media_form' %}">Add Media</a> <div class="col-md-12"> <h5>CONTINUE WATCHING</h5> <hr> <div class="card card-body"> <table class="table table-sm"> <tr> <th>Title</th> <th>Language</th> <th>Rating</th> <th>Type of Media</th> <th>Genre</th> <th>Review</th> <th>Notes</th> <th>Date</th> <th>Update</th> <th>Remove</th> </tr> {% for media in media_continue_watching %} <tr> <td>{{media.title}}</td> <td>{{media.language}}</td> <td>{{media.rating}}</td> <td>{{media.type_of_media}}</td> <td>{{media.genre}}</td> <td>{{media.review}}</td> <td>{{media.notes}}</td> <td>{{media.date}}</td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} </table> </div> </div> <div class="col-md-12"> <h5>PLAN TO WATCH</h5> <hr> <div class="card card-body"> <table class="table table-sm"> <tr> <th>Title</th> <th>Language</th> <th>Rating</th> <th>Type of Media</th> <th>Genre</th> <th>Review</th> <th>Notes</th> <th>Date</th> <th>Update</th> <th>Remove</th> </tr> {% for media in media_plan_to_watch %} <tr> <td>{{media.title}}</td> <td>{{media.language}}</td> <td>{{media.rating}}</td> <td>{{media.type_of_media}}</td> <td>{{media.genre}}</td> <td>{{media.review}}</td> <td>{{media.notes}}</td> <td>{{media.date}}</td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} </table> </div> </div> <div class="col-md-12"> <h5>COMPLETED</h5> <hr> <div class="card card-body"> <table class="table table-sm"> <tr> <th>Title</th> <th>Language</th> <th>Rating</th> <th>Type of Media</th> <th>Genre</th> <th>Review</th> <th>Notes</th> <th>Date</th> <th>Update</th> <th>Remove</th> </tr> {% … -
If condition on Django html Template
jobseqno=P567890 <td> {% if jobseqno|first:"P" %}** <a href="{{ url }}{{ jobseqno }}" target="_blank">{{ jobseqno}}</a>{% endif %} </td> The above attached code doesn't work please help me out!! -
DJANGO: Product matching query does not exist
Error message I don’t understand what’s the matter. I do everything exactly according to the courses, but knocks out an error: Request URL: http://127.0.0.1:8000/products/basket-add/12/ Django Version: 3.2.4 Exception Type: DoesNotExist Exception Value: Product matching query does not exist. Add object: def basket_add(request, product_id): current_page = request.META.get('HTTP_REFERER') product = Product.objects.get(id=product_id) baskets = Basket.objects.filter(user=request.user, product=product) if not baskets.exists(): Basket.objects.create(user=request.user, product=product, quantity=1) return HttpResponsePermanentRedirect(current_page) else: basket = baskets.first() basket.quantity += 1 basket.save() return HttpResponsePermanentRedirect(current_page) Delete: def basket_delete(request, id): basket = Basket.objects.get(id=id) basket.delete() return HttpResponsePermanentRedirect(request.META.get('HTTP_REFERER')) template: <a href="{% url 'products:basket_delete' basket.id %}" style="text-decoration: none; color: gray;"> <i class="far fa-trash-alt"></i> </a> URLs: from django.urls import path from products.views import products, basket_add, basket_delete app_name = 'products' urlpatterns = [ path('', products, name="index"), path('basket-add/<int:product_id>/', basket_add, name="basket_add"), path('basket-add/<int:id>/', basket_delete, name="basket_delete"), ] Models: from django.db import models from users.models import User class ProductCategory(models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField(blank=True) class Meta: verbose_name_plural = "Product Categories" def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=256) image = models.ImageField(upload_to='products_images', blank=True) description = models.TextField(blank=True) short_description = models.CharField(max_length=64, blank=True) price = models.DecimalField(max_digits=8, decimal_places=2, default=0) quantity = models.PositiveIntegerField(default=0) category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) def __str__(self): return f"{self.name} ({self.category.name})" class Basket(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0) created_timestamp = models.DateTimeField(auto_now_add=True) … -
Bookmarking function django/python
I'm looking to create a model for users to bookmark a recipe. I have the below: models.py class RecipeBookmark(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.PROTECT, related_name="bookmarks" ) bookmarked_by = models.ForeignKey(User, on_delete=models.PROTECT) bookmarked_at = models.DateTimeField(auto_now_add=True) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ["username", "email", "date_joined"] class RecipeBookmarkSerializer(serializers.ModelSerializer): bookmarked_by = UserSerializer(read_only=True) class Meta: model = models.RecipeBookmark fields = ["recipe", "bookmarked_by", "bookmarked_at"] def create(self, validated_data): request = self.context["request"] ModelClass = self.Meta.model instance = ModelClass.objects.create( **validated_data, **{"bookmarked_by": request.user} ) return instance views.py @permission_classes([IsAuthenticated]) class RecipeBookmarkView(generics.CreateAPIView): queryset = models.RecipeBookmark.objects.all() serializer_class = RecipeBookmarkSerializer urls.py path("recipes/bookmarks/", PublishedRecipeBookmarkView.as_view()), I want to perform a lookup, given the recipe id through a POST request, to add the user to the bookmarks field, if the user already exists in the bookmarks field, to remove that user form the field (remove the bookmark). Many users can bookmark a given recipe. Also, How can a lookup be performed to return recipes that a logged in user has bookmarked via an api endpoint? -
Checkbox inside the "for" (loop), Django
my checkbox html : <form method="GET"> {% for subcategory in subcategories %} <div class="filter-items filter-items-count"> <div class="filter-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" value="{{subcategory.id}}" name="subcategory" id="{{subcategory.id}}" {% if subcategory in subcategories1 %} checked {% endif %}> <label class="custom-control-label" for="{{subcategory.id}}">{{subcategory}}</label> </div><!-- End .custom-checkbox --> <span class="item-count">{{subcategory.products.all|length}}</span> </div><!-- End .filter-item --> </div><!-- End .filter-items --> {% endfor %} <button type="submit" class="btn btn-primary w-100 mt-3">Filter!</button> </form> it work correctly to make filter. views : subcatid = request.GET.getlist('subcategory') query string: ?subcategory=5&subcategory=6 it can be one or more than one, depends on number of subcategories. but when I go next page i suppose it become like : ?page=2&subcategory=5&subcategory=6 but it remove earliest subcategory i choose and keep the last one, just one, like : ?page=2&subcategory=5 acutely when i put Manually ?page=2&subcategory=5&subcategory=6 in url field it works but not from pagination buttons. so while all checkboxes in filter has same names, name="subcategory" i made them unique by changing to name="{{subcategory}}", now each checkbox has unique name, now after tapping next page, Everything is kept, and there is no problem like before, but in views, I don't know how to get them with deafferents names subcatid = request.GET.getlist('subcategory') -
Post Multiple values as foreign key -- Django restframework
I have a model(ProfessionalMemberContacts) which has a primary key in different model(MasterProfessionalMembers). ProfessionalMemberContacts expects multiple or single set of details as per user input ie user could give multiple contact details. Problem: I cant figure out the way to loop over all the contact details(if multiple) to save in "ProfessionalMemberContacts" with reference to "MasterProfessionalMembers". Here is my models and views for it. Models.py class ProfessionalMemberContacts(models.Model): professionalmemberId = models.ForeignKey(MasterProfessionalMembers, default=None,on_delete=models.CASCADE, related_name="pro_contact") contact_person = models.CharField(max_length=100) contact_email = models.EmailField(max_length=100) contact_number = models.CharField(max_length=100) class MasterProfessionalMembers(models.Model): professionalmemberId = models.CharField(primary_key=True, max_length=100, default=1) profile_pic = models.ImageField(blank=True) organization_name = models.CharField(max_length=100) incorp_date = models.DateField(default=date.today()) organization_type = models.CharField(max_length=100) views.py def create_pro_individual_member(request): if request.method == "POST": contact_person = request.POST.get('contact_person') contact_email = request.POST.get('contact_email') contact_number = request.POST.get('contact_number') professionalmemberId =request.POST.get('professionalmemberId') member_object = MasterProfessionalMembers.objects.get(professionalmemberId=professionalmemberId) if len(contact_person) != 0: for p,ce,n in contact_person, contact_number, contact_email: reference = ProfessionalMemberContacts( contact_person = p, contact_email = ce, contact_number = n, professionalmemberId = member_object ) reference.save() return HttpResponse('professionalmember Id created as: '+professionalmemberId) Please suggest any way to save contact details provided by user. -
Failed to deploy Heroku app. ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize;
These are errors I am getting, I can't post the entire log because of the character limit sorry. Building wheel for psycopg2 (setup.py): started Building wheel for psycopg2 (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-mfz2er96 cwd: /tmp/pip-install-mxd65ubh/psycopg2/ Second Error: psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’: psycopg/psycopgmodule.c:689:18: error: dereferencing pointer to incomplete type ‘PyInterpreterState’ {aka ‘struct _is’} 689 | while (interp->next) | ^~ error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Successfully built Pillow Failed to build psycopg2 Installing collected packages: docutils, jmespath, six, python-dateutil, urllib3, botocore, s3transfer, boto3, certifi, chardet, dj-database-url, pytz, Django, django-crispy-forms, whitenoise, psycopg2, django-heroku, django-storages, gunicorn, idna, Pillow, requests Running setup.py install for psycopg2: started Running setup.py install for psycopg2: finished with status 'error' Third Error: ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-mxd65ubh/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-08ru_8_3/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/psycopg2 cwd: /tmp/pip-install-mxd65ubh/psycopg2/ psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’: psycopg/psycopgmodule.c:689:18: error: dereferencing pointer to incomplete type … -
'QuerySet' object has no attribute 'approved'
I want to fetch all items from database where city=city_name and wnat to add one condition the area is approved or not but i am getting error about django query this is my code def parkingAreas(request, city_name): city_obj = City.objects.filter(city_name = city_name).first() reg_par = Registerparking.objects.all().filter(parking_city = city_obj) if reg_par.approved: param = {'par': reg_par} print(param) else: messages.error(request, 'Parking Not Found in Your Area') return render(request, 'parkingAreas.html', param) -
Django count function is not working and numbers aren't showing up
in the code i've written the boxes for completed and so on appear however the numbers/ the count function isn't working and the amount of each media isn't showing up pls help views.py from django.shortcuts import render from django.http import HttpResponse from .models import * # Create your views here. def home(request): media_continue_watching = Media.objects.filter(status="Continue Watching") media_plan_to_watch = Media.objects.filter(status="Plan to Watch") media_completed = Media.objects.filter(status="Completed") media_dropped = Media.objects.filter(status="Dropped") total_continue_watching = Media.objects.filter(status="Continue Watching").count() total_plan_to_watch = Media.objects.filter(status="Plan to Watch").count() total_completed = Media.objects.filter(status="Completed").count() total_dropped = Media.objects.filter(status="Dropped").count() context = {'media_continue_watching': media_continue_watching, 'media_plan_to_watch' : media_plan_to_watch , 'media_completed' : media_completed, 'media_dropped': media_dropped, 'total_continue_watching' : total_continue_watching, 'total_plan_to_watch' : total_plan_to_watch, 'total_completed' : total_completed, 'total_dropped' : total_dropped} return render(request, 'accounts/dashboard.html', context) def products(request): return render(request, 'accounts/products.html') def customer(request): return render(request, 'accounts/customer.html') models.py from django.db import models class Media(models.Model): CATEGORY = ( ('Movie', 'Movie'), ('Tv Show', 'Tv Show'), ('Drama', 'Drama'), ('Other', 'Other'), ) NUMBER = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) GROUP = ( ('Action', 'Action'), ('Anime', 'Anime'), ('Comedy', 'Comedy'), ('Crime', 'Crime'), ('Fantasy', 'Fantasy'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Other', 'Other'), ) POSITION = ( ('Completed', 'Completed'), ('Continue Watching', 'Continue Watching'), ('Plan to Watch', 'Plan to Watch'), ('Dropped', 'Dropped'), ) title = models.CharField(max_length=200, null=True) language = … -
Django shows None type
My index.html file: views.py file: Terminal: -
Gunicorn returns "TypeError: expected str, bytes or os.PathLike object, not list" when testing Django site in Ubuntu server
I am following this tutorial on DigitalOcean for the setup of a Django site. After initial setup and migrations, when I test the usual python manage.py runserver 0.0.0.0:8000 it works well (showing all images and grabbing all static files) with no errors. When I test gunicorn --bind 0.0.0.0:8000 myproject.wsgi, no static files are grabbed (anyway, I understand that's Nginx's job) but this error appears for every static file requested in the page: Internal Server Error: /static/img/logo.png Traceback (most recent call last): (...) File "/usr/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not list I suspect this is related to settings.py, where STATICFILES_DIRS are declared as a list, according to Django: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This doesn't look to me related to collectstatic (but it could be). Why is it that there is no error in the Django server and when Gunicorn is used suddenly the list of paths is a problem?