Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get image url attribute in django
i have a problem with getting image url in django template. In views file i am getting "product__stock_keeping_unit__image" which is related products' image as below. data = models.Product.objects.filter(category__slug=slug, product__is_default=True).values("id", "name", "product__sku", "slug", "category__name", "product__store_price", "product__sub_product__units", "product__stock_keeping_unit__image") in template file i am trying to display image {% for item in data %} <div class="col-lg-3 mb-4 text-center"> <div class="product-entry border"> <a href="#" class="prod-img"> <img src="{{ item.product__stock_keeping_unit__image.url }}"> </a> <div class="desc"> <h2><a href="{% url 'product_detail' item.slug item.product__sku %}">{{ item.name }}</a></h2> <span class="price">${{ item.product__store_price }}</span> </div> </div> </div> {% endfor %} Everything works fine except img field. In the page source i am getting empty string. But when i write <img src="{{ item.product__stock_keeping_unit__image }}"> i am getting image path in page source images/men-shoes.jpg but not add MEDIA_URL /media/images/men-shoes.jpg into path. Settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' How can i solve this problem. Thank in advance! -
Model.save() got an unexpected keyword argument 'commit' django error
im trying implement the register form and i geting this erorr: Model.save() got an unexpected keyword argument 'commit' And I wrote the save method, but I still get an error forms.py class RegisterForm(forms.ModelForm): class Meta: model = CustomUser fields = ['email', 'password', 'password2'] def save(self, commit=True, *args, **kwargs): user = super(RegisterForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.password = self.cleaned_data['password'] if commit: user.save() return user views.py class UserRegisterView(View): User = get_user_model() form_class = forms.RegisterForm template_name = 'account/register.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated == True: return redirect('home:home') return super().dispatch(request, *args, **kwargs) def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user_email = form.cleaned_data.get('email') user_password = form.cleaned_data.get('password') new_user = CustomUser(email=user_email) new_user.set_password(user_password) new_user.is_active = False new_user.save(commit=False) activateemail(request, new_user, user_email) return redirect('account:user_login') return render(request, self.template_name, {'form': form}) -
Django custom template tag that does not require a quoted string (like `load`)
The django template tag {% load mylib1 mylib2 %} does not require mylib2 and mylib1 to be quoted as a string. How does one create a template tag like this? All the examples in the documentation one has to quote argument strings. I tried to find the code for the load tag in django/template/loader_tags.py and django/template/templatetags, and grepped for @register.tag("load") but could not find it. -
i'am creating a django e-com project , i want to filter product by a price range with html range tag. I tried a lot
This is the html code .i need view functions for price filter <div class=""> <h5>Filter</h5> <input class="progress-bar bg-danger" type="range" name="range" id="" min ="5" , max = ""> </div> -
trigger a celery job via django singnals
I would like to use Django signals to trigger a celery task like so: def delete_content(sender, instance, **kwargs): task_id = uuid() task = delete_libera_contents.apply_async(kwargs={"instance": instance}, task_id=task_id) task.wait(timeout=300, interval=2) But I'm always running into kombu.exceptions.EncodeError: Object of type MusicTracks is not JSON serializable Now I'm not sure how to tread MusicTracks instance as it's a model class instance. How can I properly pass such instances to my task? At my tasks.py I have the following: @app.task(name="Delete Libera Contents", queue='high_priority_tasks') def delete_libera_contents(instance, **kwargs): libera_backend = instance.file.libera_backend ... -
How to call a view from within itself in a Django REST API?
I have this function in my Django REST API that handles the insertion of products. Sometimes a product will be a variational product (when product.type = 3), in which case I get all the permutations of these variations and want to insert a new product corresponding to each permutation into the database. @api_view(['POST']) def upsertProduct(request): productData = request.data['product'] variations = productData.pop('variations', []) variationTypes = productData.pop('variationTypes', []) product, created = Product.objects.update_or_create(pk=productData['id'], defaults=productData) if (productData['type'].id == 3): variations_by_type = [] for variationType in variationTypes: variations_by_type.append([variation for variation in variations if variation['variationType'] == variationType['id']]) combinations = list(itertools.product(*variations_by_type)) for combination in combinations: productData['name'] = product.name + ' (' + ' | '.join(' : '.join(i['name'] for i in item) for item in combination) + ')' productData['type'] = {'id': 5} productData['parent'] = product.id #Recursive call should go here #upsertProduct(request={'data': {'product': productData}}) My first attempt was to simply call the function as I did in the commented line. Django returned the following AssertionError: The request argument must be an instance of django.http.HttpRequest, not builtins.dict. I then attempted making use of this HttpRequest object from Django, but can not figure out how to use it properly for this use case. I've also tried the standard request library in … -
working on a django usermanager and am trying to set it up to where the user can be created using username or password is my code sufficient
from django.db import models from django.db.models import Q from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) # Create your models here. I need to know if I am headed in the right direction towards building a proper custom user manager.... class ProfileUserManager(BaseUserManager):`enter code here` def create_user(self, email, username, password=None): if not (Q(username)|Q(email)): raise ValueError('User must create account using username or email') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): user = self.create_user( email, username, password=password, ) user.is_admin= True user.save(using=self._db) return user Blockquote > I need any direction on if I am approaching building the custom user manager to include both the username or email when creating a user manager..... -
check if model was recently updated fails trying to use timedelta
I have the following model that saves a datetime on save: class StockInfo(models.Model): ticker = models.CharField(max_length=100) current_price = models.FloatField() name = models.CharField(max_length=255) summary = models.TextField() sector = models.CharField(max_length=100) dividends = models.ArrayField(model_container=Dividend) last_updated_time = models.DateTimeField(null=True) objects = models.DjongoManager() # https://stackoverflow.com/questions/9953427/django-custom-save-model def save(self, *args, **kwargs): self.last_updated_time = datetime.datetime.now().astimezone() super(StockInfo, self).save(*args, **kwargs) In the view I try using a timedelta to determine if the model had been updated within the last minute: the_timedelta = stock.last_updated_time.replace(tzinfo=None) - now print(the_timedelta) if the_timedelta > datetime.timedelta(minutes=1): print("stock was updated within the last minute") else: print("stock hasn't been updated recently") I was expecting it to determine these rapid updates were within a minute: found the stock the last updated time for stock good before save: 08/15/2022 07:51:09 -1 day, 23:59:31.335919 stock hasn't been updated recently the last updated time for stock good after save: 08/15/2022 07:51:38 reversing the comparison to if the_timedelta < datetime.timedelta(minutes=1): causes the opposite error: the last updated time for stock stag before save: 08/15/2022 07:51:37 -1 day, 23:50:47.073490 stock was updated within the last minute the last updated time for stock stag after save: 08/15/2022 08:00:50 I would like to be able to determine if the stock object was saved in the last 60 … -
Django http cookies: set-cookie vs. cookies
I am trying to figure out how Django is setting a cookie. Is it returning it as a set-cookie header including the cookies in the response payload object? See info here. -
Get scrapy spider response back on django Rest api GET
I'm working project it contains a GET request with a few parameters suchas (airline code and flight date), I pass those parameters to a crawler coded using scrapy . I've created Django command in management/commands to hit the scrapy crawler and as soon the scraping is done the data being saved in particular models. As I want to return that saved data to the same GET request, I have a few questions regarding it. How to return data in GET request? As I couldn't find a way to get returned data from scrapy crawler. How do I make wait that GET request for a particular time when scraping is being done. Assuming GET request is on waiting and scrapping is done now I have to validate if there is scraped data present in database accordingly to the params. Assuming the data is found in database and then how can I return it to the same GET request? If I want to use celery in this whole process what could be the best use of it? -
How to secure a spyne web service with Basic authentication in django
I have a soap service in django application and I covered this service with login required decorator. Client should send soap request with Authorization(Basic) headers and with these credentials I have to authenticate this client. I found one example for http headers in spyne: class RequestHeader(ComplexModel): __tns__ = 'spyne.examples.authentication' username = unicode() ee = unicode() class UserService(ServiceBase): __tns__ = 'spyne.examples.authentication' __in_header__ = RequestHeader @rpc(Mandatory.String, _returns=String) def get_head(ctx, user_name): print '*'*20 print ctx.in_header_doc print ctx.in_body_doc print ctx.in_header.ee retval = "Where's the header" return retval But I thought it did not match with my requirements Because client should authenticate with given credentials from me. I would appreciate any help(links, tutorials, similar answered questions) -
Django Register login
When we click on the register link register form should appear Register page Requirement o Username o Password o Confirm password o Submit button When we click on submit button then it should direct to the login page After login need to move to a new page The new page should contain a button When we click on the button a form should appear How to solve this in Django? Tags -
How to apply advance django query set filters based on two different columns?
I am new to django. I am working on a test project. Where I have a Model CollectFee with structure given below: Database table screenshot I want to apply a query set in the views which will display all the records where feetype_id is not 2, when this record is excluded then also exclude those records which have the same boarder_id as of already excluded record. For example, Exclude the second row as it has feetype_id = 2 then also exclude the third row because it has the same boarder_id as of second row. As I am new, I was able to just implement the filter below: def feedue(request): fee_type = 2 duefee= CollectFee.objects.exclude(feetype_id=2) context = {'duefee':duefee} return render(request, 'fee-due.html', context) -
Add additional field to response in pytest-django
I'm new to testing and I spent a day finding a solution for my problem but I couldn't find any. this is my serializer serilaizer.py class LeadSerializer(serializers.ModelSerializer): def create(self, validated_data): user = self.context['user'] return Lead.objects.create(organizer=user.organizeruser, **validated_data) class Meta: model = Lead fields = ['id', 'first_name', 'last_name', 'age', 'agent', 'category', 'description', 'date_added', 'phone_number', 'email', 'converted_date' ] I have two types of users, organizer, and agent. organizer can create a lead but agent can't. and as you see I don't have organizer field. authenticated user will be added to the organizer field when a Lead is created. test.py def test_if_lead_exist_return_200(self, api_client, leads_factory, user_factory): user = user_factory.create(is_organizer=True) api_client.force_authenticate(user=User(is_staff=True)) lead = leads_factory.create() serializer = LeadSerializer(context={'request': user}) print(serializer) # here I can see the user response = api_client.get(f'/api/leads/{lead.id}/', ) assert response.status_code == status.HTTP_200_OK assert response.data == { 'id': lead.id, 'first_name': lead.first_name, 'last_name': lead.last_name, 'age': lead.age, 'organizer': lead.organizer.id, 'agent': lead.agent.id, 'category': lead.category.id, 'description': lead.description, 'date_added': lead.date_added, 'phone_number': lead.phone_number, 'email': lead.email, 'converted_date': lead.converted_date, } because there is no organizer field in the serialzier test won't pass and this is the result of the test what can I do here? can I pass the organizer user to the response? -
Webhook from Django 4.1 to python-telegram-bot 20.0a2
I use the python-telegram-bot 20.0a2 library and Django 4.1 The bot runs by main.py script: if __name__ == "__main__": asyncio.run(main()) Inside of the main script I also run uvicorn in the same ascynhronous context as Application instance # Run application and webserver together async with application_tg: await application_tg.start() await server.serve() # uvicorn await application_tg.stop() What is the problem? I use webhook for my bot Django's url.py calls async view but the view can't get initalized Application instance of the bot. so the question is: How can to rearrange a scheme of interaction between python-telegram-bot 20 and Django 4.1 in a way that I can access Application instance from a Django hook? Addition: It's easy to achieve by using other frameworks such as starlette as it mentioned on the official wiki page of PTB library: https://docs.python-telegram-bot.org/en/v20.0a2/examples.customwebhookbot.html My main script: https://gist.github.com/SergSm/6843fadf505b826f83a10bf7eebc3fa0 my view: import json from django.views import View from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from telegram import Update from bot.tgbot.main import application_tg async def telegram_handle(request): if request.method == 'POST': await application_tg.update_queue.put( Update.de_json(data=json.loads(request.body), bot=application_tg.bot) ) return JsonResponse({"ok": "POST processed"}) else: return JsonResponse({"ok": "GET processed"}) -
AssertionError : List Differ in pytest django
I created a simple test to test the API endpoint. However it kept returning AssertionError: Lists differ: [] != [{'field_value': {'id': 1, 'panel_name': '[420 chars]: 2}] and Second list contains 4 additional elements. First extra element 0: {'field_value': {'id': 1, 'panel_name': 'Clinic A', 'panel_type': 1}, 'field_type': 'clinic', 'count': 3}. Does anyone know why is this happening ? Does it means the expected content is not present inside the list ? def test_api(self, query, expected): username = "jeff" password = "test" client = Client() response = client.post('/admin/login/', {'username': username, 'password': password}) self.assertEqual(response.status_code, 302) balance_type_collection = [ 'medical', 'dental' ] for balance_type in balance_type_collection: if query == '': query += '?' else: query += '&' query += 'balance_type=' + balance_type response = client.get('/api/v1/medical/clinicvisit/stats/'+ query) self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual(content, expected[balance_type]) -
local variable 'user' referenced before assignment error in django function
I have this function in django that adds a new item to the wishlist, the function is doing what it should do but when I add a new user that was not registered, when adding an item to the wish list it returns this error, but when i refresh the page the error no longer exist. I think the problem is that when a new user registers, he still does not have the database created in the wishlist model, so the try: condition fails because the user does not yet exist in the model, passing the except: condition where the user database is created, but I have to manually refresh the page so that the page no longer shows me the error. How can I fix this so that the page no longer shows me this error? def add_or_remove(request, listing_id): if request.method == "POST": if (request.POST["action"]) == "add": try: user = Wishlist.objects.get(user=request.user) listing = Listing.objects.get(pk=listing_id) user.item.add(listing) except: create = Wishlist( user=request.user, ) create.save() user.item.add(listing) messages.success(request, 'you added to Wishlist') elif (request.POST["action"]) == "remove": user = Wishlist.objects.get(user=request.user) item = user.item.get(id=listing_id) user.item.remove(item) messages.success(request, 'you removed from Wishlist') return redirect(reverse("listing", args=[listing_id])) -
Best way to incorporate a "utils" module in a django project?
I'm creating a project that will have several app named after states, such as: |-my_state_project |---my_state_project |---new_jersey |---alabama |---rhode_island I want to create a utils module that each app can import from. The utils.py file inside the utils module will have functions used to scrape data from the web using bs4. Each app will have a jobs.py script to import from utils.py. So the project will look like: |-my_state_project |---my_state_project |---new_jersey |------jobs.py |---alabama |------jobs.py |---rhode_island |---utils |------utils.py My questions are: Is this how Django projects are usually structured? I'm getting a ModuleNotFoundError: No module named 'utils.py' while trying to import inside one of the jobs.py files. I'm importing it using from utils import utils. Why is it complaining? This should be rudimentary The alternative would be to create a utils.py file inside each app which doesn't seem very pythonic (especially since the utils.py file may grow and updating each file individually would be torture :) -
NGINX throughs 404 and wont load static
Hopefully, Y'all can help me with this one and hopefully I am in the right areas to post this. Just recently began learning Django and I am trying to get it deployed to Linux. I have been using gunicorn and nginx for this deployment and for the most part I have been successful. I am able to successfully deploy and interact with my app, navigate pages and interact with some of the post requests. The only thing I have been banging my head around trying to figure out what is going on with my static files. All of my css and images do not display currently and I have tried searching everywhere for the resolution. I have tried using an alias in the nginx file and I have made sure that my static root and URL is fine, nothing i have tried has done the trick. the weird this is, when looking at the access logs from nginx it shows the Get request going to the correct file and path, but shows 404? I am at a loss here lol! What is really weird is that the static folder contains a few csv's that are processed and served by a … -
How can I get Sum for customer in current month django views
I am working on Django project where I want to get total (sum) deposit for each customer in the current month of the year in a list. I am not able to figure it out yet since there is no ID in use in the function request in order to use the .get() method to filter by the customer id. Below are my Model and views Code: class Customer(models.Model): surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=20, null=True) account_number = models.CharField(max_length=10, null=True) address = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=11, null=True) date = models.DateTimeField(auto_now_add=True, null=True) #Get the url path of the view def get_absolute_url(self): return reverse('customer_create', args=[self.id]) #Making Sure Django Display the name of our Models as it is without Pluralizing class Meta: verbose_name_plural = 'Customer' # def __str__(self): return f'{self.surname} {self.othernames} - {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Views Code: def create_account(request): current_date = datetime.now().date() customers = Customer.objects.all() act = customers.account_number deposited_this_month = Deposit.objects.filter(customer__account_number=act, date__year=current_date.year, date__month=current_date.month).aggregate(deposited_this_month=Sum('deposit_amount')).get('deposited_this_month') or 0 I am having error which says 'QuerySet' object has no attribute 'account_number'. A … -
How to display the comments for each author of the article in the profile and site manager?
I'm writing a multi-author website with Django. I have used django-comments-dab for the comments section But I don't know how to display the comment of each article for its author in the panel? -
ImportError: cannot import name 'url' from 'django.conf.urls' for Django 3.2.8
My program got "ImportError: cannot import name 'url' from 'django.conf.urls'" for Django version 3.2.8 suddenly. It can work hours before... . How to fix this? -
python dcc.Location opening new page within a page
I have several dash apps in a html files, example of html with app 'viewer': {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} <h1>Viewer</h1> <div class="{% plotly_class name='viewer' %} card" style="height: 100%; width: 100%"> {% plotly_app name='viewer' ratio=0.7 %} </div> <br> {{ plot1 | safe }} {% endblock %} I am trying to open another html from a dash app using dcc.Location (a callback provides a href back to this after a button is clicked) but it loads the html within the current html so I end up with two of all the side menu's, search bars etc.. How do I get the app to load a whole new page? Even opening the link on a new tab would suffice. Thank you for any help with this. -
Django Rest Framework invalid serializer data, can not figure out why
I am creating a simple model with a many-to-many field. The model works fine and I can create model through the admin panel, and I can make a get request to see that model (except that it only returns user IDs instead of the user models/objects). My problem is when creating a post request to create said model. I get one of the two errors depending on the changes I make, The serializer field might be named incorrectly and not match any attribute or key on the 'str' instance. or AssertionError: You cannot call '.save()' on a serializer with invalid data., either way it has something to do with my serializer. The following is my model, class Schema(models.Model): week = models.PositiveIntegerField(primary_key=True, unique=True, validators=[MinValueValidator(1), MaxValueValidator(53)], ) users = models.ManyToManyField(MyUser, related_name="users") class Meta: ordering = ('week',) My View, class SchemaView(APIView): permission_classes = (SchemaPermissions,) def get(self, request): schemas = Schema.objects.all() serializer = SchemaSerializer(schemas, many=True) return Response(serializer.data) def post(self, request): data = request.data serializer = SchemaSerializer(data=data) serializer.is_valid() serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) And my serializer, class SchemaSerializer(serializers.ModelSerializer): class Meta: model = Schema fields = ('week', 'users') def create(self, validated_data): users_data = validated_data.pop('users') users = MyUser.objects.filter(id__in=users_data) schema = Schema.objects.create(week=validated_data.week, users=users) return schema def update(self, instance, validated_data): … -
Negative impact of a Django model with multiple fields (75+ fields)
I'm in the process of building a web app that takes user input and stores it for retrieval and data manipulation. There are essentially 100-200 static fields that the user needs to input to create the Company model. I see how I could break the Company model into multiple 1-to-1 Django models that map back the a Company such as: Company General List item Company Notes Company Finacials Company Scores But why would I not create a single Company model with 200 fields? Are there noticeable performance tradeoffs when trying to load a Query Set?