Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
im using django 4.0.2 and i have thist error
i'm new in django and i cant find the error to resolve, it appears on object 'user'. Any suggestions to make this work? It looks like in the past, this would be the answer class Checkout(LoginRequiredMixin, View): def post (self, request): addres = request.POST.get('addres') comment = request.POST.get('comment') cart = request.session.get('cart') user= request.session.get('user') product = Product.get_product_by_id(cart) print(addres, comment, User, cart, product ) for product in product: print(cart.get(str(product.id))) order = Order(user=User(id=user), product=product, price=product.price, addres=addres, comment=comment, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect ('cart:cart_detail') i was watching a tutorial and doing it but i cant resolve the error that appearsenter image description here, i cant find a solution yet class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product): if str(product.id) not in self.cart.keys(): self.cart[product.id]={ "product_id": product.id, "title":product.title, "quantity": 1, "image":product.image.url, "thumbnail":product.thumbnail.url, "price": str(product.price) } else: for key, value in self.cart.items(): if key== str(product.id): value["quantity"] = value["quantity"]+ 1 break self.save() def save(self): self.session["cart"] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def decrement(self, product): for key, value in self.cart.items(): if key == str(product.id): value["quantity"] = value["quantity"]- 1 if … -
Pesquisa por id em django
Estou tentando realizar uma busca por um imóvel pelo id do imóvel, mas não está me retornando nada, o código é seguinte: def buscaPorCodigo(request): id = request.GET.get('id') imovel = get_object_or_404(Imovei, id=id) sugestoes = Imovei.objects.filter(cidade=imovel.cidade).exclude(id=id)[:2] return render(request, 'imovel.html', {'imovel': imovel, 'sugestoes': sugestoes, 'id': id}) -
django pytest / update delete view testing
I'm working on pytest testing for my 1st django app, kind of cookery book. I have problems with edit/delete view tests. For example, i have a test for testing add recipe view. Here is recipe model: class Recipe(models.Model): """Instructions how to prepare a single dish.""" title = models.CharField(max_length=50) cooking_time = models.IntegerField(help_text='in minutes', validators=[MinValueValidator(1), MaxValueValidator(5000)]) difficulty_level = models.IntegerField(choices=DIFFICULTY_LEVELS, default=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) cuisine = models.ForeignKey('Cuisine', on_delete=models.CASCADE, null=True) ingredient = models.ManyToManyField(Ingredient, through='IngredientRecipe') meal_plan = models.ManyToManyField('MealPlan', through='RecipeMealPlan') here is it's fixture: @pytest.fixture() def example_recipe(): rec = Recipe.objects.create(title='rec', cooking_time=10, difficulty_level=2, description='bla, bla, bla') return rec And tests which works fine: @pytest.mark.django_db def test_add_recipe(client, example_recipe): dct = { 'title': 'rec', 'cooking_time': 10, 'difficulty_level': 2, 'description': 'bla, bla, bla' } url = reverse('add-recipe') response = client.post(url, dct) assert response.status_code == 302 assert Recipe.objects.get(**dct) @pytest.mark.django_db def test_add_recipe2(client): url = reverse('add-recipe') response = client.get(url) assert response.status_code == 302 Now I'm trying to write test for recipe update/delete views. My recipe update test currently looks like this: @pytest.mark.django_db def test_ingredient_update_view(client, example_ingredient): url = reverse('update-ingredient', kwargs={'id': example_ingredient.id}) response = client.get(url) assert Ingredient.objects.save( name='cos', nutrient=2, glycemic_index=2 ) I know its wrong but i face problems to make it work. Same with delete view. Could someone take a look … -
What should I use to enter data to my database on Django? Django admin or SQL code?
I am a newbie in programming, but now I connected my project with PostgreSQL. I learned the way to enter by SQL code and also found out that we can actually enter /adming (by creating the superuser and add data there). So which one is widely used in webdev? -
Redis server run on heroku
I am using windows and I have deployed a Django project to heroku. This project need to run a redis server for a chatroom. I ran it perfectly on my localhost, but after I deployed it to heroku, the redis server only run in redis://127.0.0.1:6379 only. I have tried to change the redis.conf file from bind 127.0.0.1 to bind mywebsite but it doesn't work. Thanks for all help in advance -
How to send url from template to view in django
How can I send a URL from a template to a view? I have noticed that a normal string works but a URL doesn't. Here is what I have tried. path('imageviewer/<str:theimage>', mainviews.imageviewer, name="imageviewer"), def imageviewer(request, theimage): response = render(request, "imageviewer.html", {"theimage": theimage}) return response How I attempt to pass it : (value.image) is a url <a href="{% url 'imageviewer' theimage=value.image %}" class="effect-lily tm-post-link tm-pt-60"> Error I Get: Reverse for 'imageviewer' with keyword arguments '{'theimage': 'https://storage.googleapis.com/katakata-cb1db.appspot.com/images/humours/1643758561'}' not found. 1 pattern(s) tried: ['imageviewer/(?P<theimage>[^/]+)\\Z'] Thank you. -
What does the empty list passed in the assert function mean?
sorry for the weird title. I am currently learning Django, and going through their tutorial. In Part 5, it discusses test cases which I am understanding well. However, I am unclear what the last line of the snippet means. def test_future_question(self): #questions with a pub_date in the future aren't displayed on the index page. create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) Why must we pass an empty list? It doesn't make any sense to me, and I am just wanting to learn why. Thank you! -
How do i access request.user in self.client.post Testing
I have a model called Quote which has a ForeignKey pointing to User. I want to make a post request to create a Quote but i don't know what data i should give to self.client.post, this is what i got so far i am talking about the test_can_save_a_POST_request: from django.contrib.auth import get_user_model from django.test import TestCase from quotes.models import Quote from quotes.views import home_page User = get_user_model() class HomePageTest(TestCase): def test_uses_home_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'home.html') def test_display_all_quotes(self): user1 = User.objects.create(email="rafik@test.com", password="foo") Quote.objects.create(text='quote 1', user=user1) Quote.objects.create(text='quote 2', user=user1) response = self.client.get('/') self.assertIn('quote 1', response.content.decode()) self.assertIn('quote 2', response.content.decode()) def test_can_save_a_POST_request(self): user1 = User.objects.create(email="rafik@test.com", password="foo") self.client.post('/', data={ 'quote_text': 'The first ever quote' } ) -
Error while deploying django channels to amazon elastic beanstalk
I am facing an issue with websockets. When I run the program locally it works fine but when I deploy it to aws elastic beanstalk I face the following issue. I have a simple code as mentioned below. django.config ``` option_settings: aws:elasticbeanstalk:container:python: WSGIPath: playzone.wsgi:application aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static ``` Procfile ``` web: gunicorn playzone.wsgi websocket: daphne -p 5000 my_app.asgi:application ``` asgi.py ```py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( routing.websocket_urlpatterns ) }) And there are 2 more simple files `routing.py` and `consumers.py`. I've even configured the load balancers on the environment's settings (80 - HTTP ; 5000 - HTTP). So once deployed, when I try routing to the webpage which has a websocket connection, I get an error saying `WebSocket connection to 'ws://zzzzzzzzzzzz.com/ws/' failed:`. Please help me out on how I can fix it. Also am not using redis or any channel layer. Please help me out on how I can fix it. -
Webpack: Do not parse specific html tag
I'm using webpack to build html templates using Django's templating language. Django templates contain variables and tags using {{ }} and {% %} syntax. Webpack has ignored these just fine and built the html templates as expected, except when parsing srcset tags. Webpack errors when it tries to parse the following html: <source srcset="{% static 'images/my-image.png' %}"> I'd like webpack to either ignore all srcset tags completely, or have some sort of # noqa equivalent which makes webpack simply not make changes to this row of the file. Is that possible? -
Python: Run a code after return something
This is an ApiView from my django project: class Receive_Payment(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAdminUser,) def get(self, request, cc_number): if Card.objects.filter(cc_num = cc_number).exists(): client = Client.objects.get(client_id = (Card.objects.get(cc_num = cc_number).client)) if not client.is_busy: client.is_busy = True client.save() resp = "successful" else: resp = "client_is_busy" else: resp = "fail" return Response({"response": resp}) As you see, if client.is_busy is not True, I'm making it True in here. But in this situation, I need to client.is_busy = False after 30 seconds. If I do it under client.save() code, it delays to response. How can I do it? -
Django - UniqueConstraint not created
I am trying to enforce a constraint for mysql where user is prohibited from inserting twice the same name and model. E.g This should not be allowed to be inserted twice: name:Name1 model:Model1 #Model class Car(models.Model): name = models.CharField(max_length=100) model = models.CharField(max_length=100) #View class CarListCreateAPIView(generics.ListCreateAPIView): serializer_class = CarSerializer def get_queryset(self): trip_code = self.kwargs.get("pk") return Car.objects.filter(trip = trip_code) #Return cars for given trip #Seializer class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('__all__') constraints = [ models.UniqueConstraint(fields=['name', 'model'], name='car_name_model_constraint') ] The problem is that the constraint is never created and thus not enforced. What might be the issue with the code? -
Minio: InvalidRequest when change AWS_S3_FILE_OVERWRITE to False
When AWS_S3_FILE_OVERWRITE was equal to True everything worked fine. But when it was changed to False I get error (when click on link on frontend): At the same time if I copy a link to a file and paste it into browser directly there is no error. Why that's happening this way? P.S. Using django-storages -
model.objects.all() doesn't find anything when foreign key in model
when I load the website i get this error my models.py file looks like: # Create your models here. class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): id = models.AutoField(primary_key=True) found_articles = models.ForeignKey( Information, on_delete=models.CASCADE) search_details = models.ForeignKey( Search, on_delete=models.CASCADE) def __str__(self): return self.id in my view.py file: def show_articles_with_this_filter_id(request): all = Article_search.objects.all() print(all) return render(request, 'show_article.html') when I get to the print statement I get the error shown in the picture: Unknown column 'database_article_search.found_articles_id' in 'field list' why is the part _id pasted behind found_articles? -
Python simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) while in request.post data
I am trying to post a request with data as following payload={'request_payload': {'name': 'logo', 'description': 'logo file', 'det': {'download_allowed': True, 'watermark': True, 'readonly': False}, 'cat': {'0': 'Tax', '1': '2007', 'Type': '2'}, 'document_type': ['xxxxxxxxx']}} requests.post(url,headers=headersAuth,files=files, data=payload) Which causes this error: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) So i tried using postman which generates the following payload which has single quotes for the value and request.post is success. payload={'request_payload': '{'name': 'logo', 'description': 'logo file', 'det': {'download_allowed': True, 'watermark': True, 'readonly': False}, 'cat': {'0': 'Tax', '1': '2007', 'Type': '2'}, 'document_type': ['xxxxxxxxx']}'} The problem is if i post the later payload in django api through its explorer it json parse error where i placed the single quotesDjango json error image Can anyone tell how to get value formatted as the second payload. Is there anything I am missing -
how can i manipulate several images in a directory and display them conditionally with django?
I have a folder that contains several images, I would then like to display the list of images that have the same name and number (eg: myfile_page1.png, myfile_page2.png, myfile_page2.png,) and then display them in the django template show_file.html -
clearing log file using Django
I am new to Django. I am trying to log the info messages to a log file and clear it every 10 mins. I tried the below code in settings.py 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_DIR,'Logfile.log'), 'when': 'M', 'interval': 10, 'backupCount': 10, 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'main':{ 'handlers': ['file'], 'level': 'INFO', 'propagate': True, } }, I face error stating PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'D:\Folder\LogFile.log' -> 'D:\Folder\LogFile.log.2022-02-24_12-08' I understand the error that I can't rename a file that's open. I would like someone to help me in resolving this and helping me clear the log file. Thanks in advance -
How to insert data using stored procedure in django for mssql?
I get this error, ValueError at /health/ The view Healthcare.views.Sp_tbl_user_detail_views didn't return an HttpResponse object. It returned None instead. models class sp_tbl_user_detail(models.Model): userid = models.CharField(db_column='userID', primary_key=True,max_length=36,editable = False) # Field name made lowercase. username = models.CharField(unique=True, max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS') userfirstname = models.CharField(max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') userlastname = models.CharField(max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') user_contact = models.BigIntegerField(unique=True) user_dob = models.DateField() gender = models.CharField(max_length=1) height = models.FloatField(max_length=6) weight = models.FloatField(max_length=6) blood_group = models.CharField(max_length=3) user_password = models.CharField(max_length=30) # This field type is a guess. user_email=models.CharField(unique=True,max_length=100,db_collation='SQL_Latin1_General_CP1_CI_AS) addedby = models.CharField(max_length=36) addedon = models.DateTimeField(blank=True,null=True,auto_now_add=True) updatedby = models.CharField(max_length=36, blank=True, null=True) updatedon = models.DateTimeField(blank=True,null=True,auto_now=True) active = models.BooleanField() views def Sp_tbl_user_detail_views(request): if request.method=='POST': if request.POST.get('userid') and request.POST.get('username') and request.POST.get('fname') and request.POST.get('lname') and request.POST.get('pnumber') and request.POST.get('dob') and request.POST.get('gender') and request.POST.get('height') and request.POST.get('weight') and request.POST.get('bloodgroup') and request.POST.get('password') and request.POST.get('emailid'): empsave=sp_tbl_user_detail() empsave.userid=str(uuid.uuid4()) empsave.username=request.POST.get('username') empsave.fname=request.POST.get('fname') empsave.lname=request.POST.get('lname') empsave.pnumber=request.POST.get('pnumber') empsave.dob=request.POST.get('dob') empsave.gender=request.POST.get('gender') empsave.height=request.POST.get('height') empsave.weight=request.POST.get('weight') empsave.bloodgroup=request.POST.get('bloodgroup') empsave.password=request.POST.get('password') empsave.emailid=request.POST.get('emailid') empsave.addedby='55CD065E-29ED-442D-90AA-C6A443757CE5' cursor=connection.cursor() cursor.execute ("sp_tbl_user_detail '"+empsave.userid+"','"+empsave.username+"','"+empsave.fname+"','"+empsave.lname+","+empsave.pnumber+"','"+empsave.dob+"','"+empsave.gender+","+empsave.height+","+empsave.weight+",'"+empsave.bloodgroup+"','"+empsave.password+"','"+empsave.emailid+"','"+empsave.addedby) #cursor.execute ("sp_tbl_user_detail (@userID='%s',@username='%s',@userfirstname='%s',@userlastname='%s',@user_contact=%s,@user_dob='%s',@gender'%s',@height=%s,@weight=%s,@blood_group='%s',@user_password='%s',@user_email='%s')",(empsave.userid,empsave.username,empsave.fname,empsave.lname,empsave.pnumber,empsave.dob,empsave.gender,empsave.height,empsave.weight,empsave.bloodgroup,empsave.password,empsave.emailid)) messages.success(request,"Info saved successfully") print('User Created') return JsonResponse(empsave,safe=False) else: return render(request,'Index.html') Index.html <body> <center> <h2>Sign Up</h2> <form method="POST"> {% csrf_token %} <!--User ID: <input type = "text" name="userid" placeholder="Please enter your User Name" /><br/> --> USERNAME: <input type = "text" name="username" placeholder="Please enter your First Name" /><br/> First Name: <input type = "text" name="fname" placeholder="Please enter your First Name" … -
Django nestesd serializers problem for 'Subcategory' object is not iterable
I want to get the category and subcategory with my product serializer, but it is showing me this error that subcategory object is not iterable. I don't know what is the problem I tried the same nested procedure and it worked previously for another field but not with subcategory . #this is my model so you understand the relation class Category(models.Model): name = models.CharField(max_length=220) def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=220) class Product(models.Model): product_type_choices = [ ('With Cylinder', 'With Cylinder'), ('Without Cylinder', 'Without Cylinder'), ] setup_type_choices = [ ('Yes', 'Yes'), ('No', 'No'), ] user = models.ForeignKey(Vendor, on_delete=models.CASCADE) name = models.CharField(max_length=220) image = models.ImageField(null=True, blank=True) product_type = models.CharField(max_length=220, null=True, blank=True, choices=product_type_choices) setup_type = models.CharField(max_length=220, null=True, blank=True, choices=setup_type_choices) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(max_length=10000) rating = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) numReviews = models.IntegerField(null=True, blank=True, default=0) old_price = models.DecimalField(max_digits=11, decimal_places=2) discount = models.IntegerField(blank=True, null=True) price = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) countInStock = models.IntegerField(blank=True, null=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) short_description = models.CharField(max_length=2000, blank=True, null=True) isCampaign = models.BooleanField(blank=True, null=True, default=False) _id = models.AutoField(primary_key=True, editable=False) def save(self, *args, **kwargs): self.price = Decimal(self.old_price * (100 - self.discount) / 100) return super(Product, self).save(*args, **kwargs) class Meta: ordering = ['-createdAt'] … -
Getting custom Django REST user class in React using JSON Web Token
Context: My project is using Django REST together with React. I have made a User class that extends AbstractBaseUser, based on this tutorial to get a couple extra fields, and to use email, instead of username, to authenticate. To log in, I'm using djangorestframework-jwt to get an access token in React. Problem: I haven't found a way to get a user instance from Django REST based on the JSON Web token. What I have tried: Tried using the JWTAuthentication with this view: @api_view(['POST']) @authentication_classes([JWTAuthentication]) def getUser(request, format=None): content = { 'user': str(request.user), 'auth': str(request.auth) } return Response(content) It does kinda work, since it returns the users email address and token, but I want to get all user fields. I also tried copying from this SO answer, but in setting.py I don't know how to specify the path to the JWTAuthentication class. My user class: from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): … -
the administration site of django not fully presentable after copying my project on a linux server
it's the first time i see this thing , -when i go to the site of administration of django , there is no blue color everything is with white and black color and not presentable, -on my localhost everything is fine , this happened when i have copied my project django on a linux server. ps: the other templates(routes) that are linked to my project are fully presentable(there was the images and the colors..) (See the screenshoot of my administration site django please) I have tried to restart nginx and gunicorn by: sudo service nginx restart sudo service gunicorn restart but it's the same thing. Help please. Thanks in advance. -
Django runserver - Can you output the connecting IP to the console?
I am trying to capture the IP address of incoming connections to the console using the development webserver that comes with django (manage.py runserver 0.0.0.0:8000). Right now, I get the following output on requests: [24/Feb/2022 13:03:38] "GET /admin/aqww/ HTTP/1.1" 200 3223 Is there a way to get an incoming client IP address in there? For example, make it look something like the following? [24/Feb/2022 13:03:38 192.168.1.34] "GET /admin/aqww/ HTTP/1.1" 200 3223 Thanks -
Can I pass a list of objects into a session? Django/Python
I have data that does not need stored in a db. I have a list of results from an API that is made up of objects i created based off of what is returned by the api. I want to display results in an html table. When I paginate i lose all that data and want to pass the list of objects into the session to pass with each page. Is this possible? -
Why does my Django project somtimes not serve static files
Whenever I make a Django project sometimes the static files do not serve properly. I make sure that the files exist in the following format myapp/static/myapp. -
Django get the static files manifest storage URL in view when in DEV
One can get the static url in view with: from django.templatetags.static import static url = static('x.jpg') However during dev I use django.contrib.staticfiles.storage.StaticFilesStorage, and in production I use django.contrib.staticfiles.storage.ManifestStaticFilesStorage. How I have a build script that bundles some javascript modules files, the imports require the hashed urls, during DEV. Is there a way to calculate the hashed file name when the django settings.STATICFILES_STORAGE is StaticFilesStorage? The below code is what I came up with, but sometimes it gives the wrong hash (collect static modifies the files (e.g. source code map urls), so I think that changes the hash of the staic file if it references another static file): from django.contrib.staticfiles import finders from django.contrib.staticfiles.storage import staticfiles_storage from django.core.files.storage import get_storage_class from django.template import loader # Here spath = static path, and fpath = file path, mpath = manifest (hashed) path # fname = filename def spath_to_fpath(spath): return finders.find(spath) def spath_to_mpath(spath): fpath = spath_to_fpath(spath) manifest_storage = get_storage_class( 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' )() # location is the fpath that spath is relative too, get the fpath and right trim the spath manifest_storage.location = fpath.rsplit(spath)[0] app, name = spath.rsplit('/', 1) # The filename hashed_fname = manifest_storage.hashed_name(name, filename=spath) # filename arg takes a spath mpath = f"/static/{app}/{hashed_fname}" # …