Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get cryptocurrency prices and make some calculations and post it in a list with Django?
I'm newby with Django and I have to deliver some homework. So I want to create a super simple web page that a user can come and write what cryptocurrency coin and how much of it he/she has bought and submits it. On the next page, there will be some posts that show that info again, cryptocurrencies price, and the website does some calculations that I determine and posts it(eg. 10% lower than buying price)...at last there will be a list of purchases that the user has submitted. I have stocked in this problem for weeks now, can you please guide me through it or write its code so I can study it? -
Django - How to trigger views function with html button action
I have another NoReverseMatch that I don't understand.+ In my eyes, what should be happening is: 1. User presses button to submit form <button type="submit" action="{% url 'APP_NAME:image_gen' %}">Run</button> 2. The request passes through my URL pattern, which triggers the views function. path('image_gen/', views.image_gen, name='image_gen'), 3. The action sends a request to the views function, which generates an image. def image_gen(request): save_image(path) return render(request, 'APP_NAME/page.html', {'title': 'page'}) There's a lot less going on here than in my actual site, but it works in the same way. Why isn't it working? -
Django Window functions
Question How do I calculate the delta of a column between two consecutive rows in my database using the Django ORM? Background I have the following model: class Foobar(models.Model): foo = models.IntegerField() I want to calculate the delta between foo for each row in the database. I found Django's support for Window functions and the Lag() function. With those in hand, I tried something like this: Foobar.objects.annotate(delta=Window(expression=F('foo') - Lag('foo'))) which gives the following error: Traceback (most recent call last): File "/usr/lib/python3.8/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "/home/llund/.cache/pypoetry/virtualenvs/scraper-2Ye6bxs0-py3.8/lib/python3.8/site-packages/django/db/models/expressions.py", line 1275, in __init__ raise ValueError( ValueError: Expression 'CombinedExpression' isn't compatible with OVER clauses. So to simplify, I just tried to annotate each row with the value from the previous row: fs = Foobar.objects.annotate(prev=Window(expression=Lag('foo')) for f in fs: print(model_to_dict(f)) The resulting dicts in my print() statement don't have 'prev', though. What am I missing? What is the correct way to use Lag() to calculate the delta between each row? -
logging updates to fields of djagno model in a jsonfield
I have been using logging the updates to any field of a django model with a jsonfield. class User(models.Model): phone_number = models.CharField(max_length=15) email_field = models.TextField() updates_log = models.JSONField(default=list) def save_phone_update_log(self, old_phone, new_phone): self.updates_log.update({"old_phone":old_phone,"new_phone":new_phone, "updated_at":datetime.datetime.now()}) self.save(updated_fields=["updates_log"]) Now I want to do it for all the fields , what could be an optimized implementation? -
Queries related to Google cloud storage and Aws bucket for file storage
there.I am moving forward to use google cloud services to store Django media files. But one thing that stops me is about the Google and Amazon free tier. I had read the google cloud docs but I am confuse about many things. For free tiers, New customers also get $300 in free credits to run, test, and deploy workloads. What I want to know is if they are gonna automatically charge me for using the cloud-storage after 3 months of trial is over because I am gonna put my bank account. This case is same on Aws bucket which allows to store mediafiles for 1 year after then what's gonna happen. Are they auto gonna charge me? -
Download file from internet into server (django)
How to download a file from internet into server. I wanted to download a file from internet to my server and from server I would like to upload it to youtube or something else. Every thing should be done on server. -
Django return home page in get absolute url
My urls urlpatterns = [ path('', views.home, name='blog-home'), path('about/', views.about, name='blog-about'), path("post/new/", PostCreateView.as_view(), name="post-create"), ] Once I do a post my site crashes since I need to specify a get_absolute_url. I just want to return to the home page but trying redirect("") fails with error NoReverseMatch at /post/new/ Reverse for '' not found. '' is not a valid view function or pattern name. How can I return to the homepage ? -
Django one custom model field to two db columns
I would like to create a custom field that receives a datetime string and store data in two db columns. I am reading django doc but not getting how to do it with more than one db column. It is a legacy db, so I can not change db tables layout. I have this model right now. class MyModel(models.Model): mixing_datetime = models.DateTimeField() mixing_datetime_utc_offset_seconds = models.IntegerField() I would like to create a field that lets the front end (it is an API with DRF) just send a datetime string (instead of datetime and offset separately), and let the backend do the work behind the scenes. So the idea would be: class MyModel(models.Model): mixing_datetime = models.DateTimeField() mixing_datetime_utc_offset_seconds = models.IntegerField() datetime = MyCustomDatetimeField() # This also should not be sent to db How can I achieve it? -
Django return method parameter
I was watching a tutorial on django and the guy added the following line of code, however he didnt exactly explain what it does. return '%s - %s' django the full code line is: def __str__(self): return '%s - %s' % (self.post, self.author) and i do understand it, just not that return part. Anyone mind clearing it out for me. -
Django foreign key issue with django-import-export library (IntegrityError at /import/ FOREIGN KEY constraint failed)
I'm relatively new to Django and not an advanced programmer, so please pardon my ignorance. What is working: I have a Django application that uses one main model which connects to two secondary models with foreign keys. The application can correctly create companies from template and from admin, and can correctly display the "niche" drop-down field using a foreign key to the Category model and can correctly display the images using a foreign key from the CompanyImage model. What is not working: The django-import-export library can correctly import an XLS document from front end and from admin, but ONLY if I disable the Category and CompanyImage model that are relying on foreign keys. The library does import correctly with the default user=models.ForeignKey(User) in my main Company model, but the foreign keys that connect to the secondary models are causing a foreign key error: IntegrityError at /import/ FOREIGN KEY constraint failed. What I need The XLS sheet I am importing does not import the fields that use a foreign key, so I would like to disable those fields to avoid the foreign key error. It would be nice to import a niche/category field, but I can do without. What I've tried … -
Implementing 'saved books' cart in Django
I'd like to implement a cart page, where i can save all the books that i've saved before models.py class Book(models.Model): LANGUAGES = ( ('ukr', 'Ukrainian'), ('eng', 'English'), ('rus', 'Russian'), ) image = models.ImageField(upload_to='images/', default='4.jpg') title = models.CharField(max_length=128) description = models.CharField(max_length=512) language = models.CharField(choices=LANGUAGES, default='English', max_length=100) # many books has one genre, if genre is deleted then delete related books genre = models.ForeignKey('Genre', on_delete=CASCADE) price = models.DecimalField(validators=[isBiggerThanZero], max_digits=6, decimal_places=2) slug = AutoSlugField(populate_from='title', default='') def __str__(self): return self.title class Genre(models.Model): genre = models.CharField(max_length=32, default='') def __str__(self): return self.genre I think that i need to add a new model Cart with a field saved = models.ForeignKey(Book) But it should be a list of books and idk how to implement it :( P.S.1 You should be registered if you want to save a book, so users are authorized. Skip sessions :) P.S.2 If there is a way to do that without additional modules, i'll be very grateful to you :) -
Collapse Django NavBar: On Mouse Over Show and On Mouse Out Hide
I am in need to hide a django app Blockquote navbar on mouse out and show on mouse over just like in 1. The django app is using Bootstrap4. According to W3School BootStrap4 has .collapse class 2. From a BootStrap4 perspective, I am still figuring out I could use the collapse class with hover. On the other hand, by just using css, I went through the first attempt following something like in 3. HTML <div id="nav_general"> <nav id="navbar" class="navbar navbar-inverse navbar-fixed-top" role="navigation"> </nav> </div> CSS .home #navbar { display: flex; transform: translateY(-100%); } .home #nav_general:hover #navbar { transform: translateY(0); } Within the CSS configuration the navbar was hidden forever and it is not expanding on mouse over. Could anyone point me to the reason the navbar has been hidden forever and how I could make it expand on mouse over? How could I achieve the same goal by just using BootStrap4 class=collapse? -
Specify time format in model_to_dict
I have a model class Frame(models.Model): timestamp = models.DateTimeField(default=timezone.now) url_to_frame = models.CharField(max_length=100) def __str__(self): return f"{self.timestamp}_{self.url_to_frame}" I have to use from django.forms.models import model_to_dict to serialize Frame object I receive timestamp in the following format "timestamp": "2021-06-27T14:18:00Z" But I need format like this 2021-07-01 01:20:00 How can I specify format of time in my case? -
Google authentication redirects to 127.0.0.1:8080/accounts/social/signup/
I'm currently following this tutorial for google authentication in django using django-allauth: https://www.section.io/engineering-education/django-google-oauth/ When i try to login via google it shows me account choose option & when i click on it it redirects me to: /accounts/social/signup/ and it dosen't logs in the user! This is the Image -
How to optimize my query for larger queryset?
Here I am making a model to track the views of the some pages. If some user visit some page with some url then this model will created . In this case this is working fine for now. But I have a question that If the table gets to big later (since the SESSION_COOKIE_AGE will be just for 1/2 hours) then there will be a lot data. One option could be deleting objects older than x_month but I if I did so then I will not get the actual count. I think db indexing will help to optimize the query but I am not familiar with database indexing much. For example if db indexing is done in my model then for the better query optimization which model field could be desirable for db_index=True and how will I use this indexed field with my queryset ? class WebSiteVisitor(models.Model): page_url = models.CharField(max_length=30, editable=False) user_ip = models.CharField(max_length=30, null=True, editable=False) session = models.CharField(max_length=30, null=True, editable=False) date = models.DateTimeField(auto_now_add=True) # create if not WebSiteVisitor.objects.filter(page_url=url, session=request.session.session_key).exists(): # model create then # get visit count of the page return WebSiteVisitor.objects.filter(page_url=page_url).count() -
UniqueConstraint Django unique together
I have two models: class Profile(models.Model): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, ) avatar = models.ForeignKey( 'Avatar', on_delete=models.CASCADE, null=True, blank=True, ) class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' class Avatar(CreatedByModel): avatar = models.ImageField( verbose_name='Avatar', upload_to=UploadTo(prefix='avatars'), blank=True, ) default = models.BooleanField( verbose_name='Default avatar?', default=False, ) class Meta: verbose_name = 'Avatar' verbose_name_plural = 'Avatars' I need to create UniqueConstraint in Profile model based on a default in Avatar model, I tried to make this: class Profile(models.Model): ... class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'avatar'], condition=Q(avatar=False), name='unique_id_avatar_default', ), ] But got an error: Django.core.exceptions.FieldError: Joined field references are not permitted in this query Are there any other ways to do what I want? -
Heroku admin page not found
I've deployed a cookie cutter django app. It runs fine. But I can t access to admin I create a superuser and it connect fine. But I ve a 404 not found when I try to go to admin page To know urls: urlpatterns = [ # Needed for locale change path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path("", TemplateView.as_view(template_name="pages/home.html"), name="home"), path( "about/", TemplateView.as_view(template_name="pages/about.html"), name="about" ), # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management path("users/", include("gusta.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here path("employee/", include("gusta.employee.urls")), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In heroku logs:nothing In my local app I can access to it without issue. Some clues ? -
ForeignKey field problem with assign instance in form.py
Here I want to save data from a form.py on my page (everything works well from the admin panel). my model.py is, class contrat(models.Model): contrtID = models.CharField(max_length=25,unique=True) def __str__(self): return self.contrtID and the other table; class Invoices(models.Model): Invoce_Titl = models.CharField(max_length=50) Cntrat_Nbr = models.ForeignKey(contrat, on_delete=models.CASCADE) #should be Actived def __str__(self): return self.Invoce_Titl and the form I use is: query_contrat = (('', '-------'),) class Invoices_F(forms.ModelForm): Invoce_Titl = forms.CharField(label='Invoice Title',max_length=50) Cntrat_Nbr = forms.ChoiceField(label='Contract ID',choices=query_contrat) class Meta: model= Invoices fields=('Invoce_Titl','Cntrat_Nbr') def __init__(self, *args, **kwargs): super(Invoices_F, self).__init__(*args, **kwargs) self.fields['Cntrat_Nbr'].choices = query_contrat + tuple( contrat.objects.filter(Actived='Active').values_list('id','contrtID')) So when I try in the HTML page it gives me this error when I press save data. Cannot assign "'5'": "Invoices.Cntrat_Nbr" must be a "contrat" instance. So my from is taking the contrat.id as a string with another ' ', so how I do get rid of this problem? -
Django model owner field reading the log in user as None instead of the username
I am trying to learn django rest framework and have been following the django-rest-framework tutorial. I am not able to understand why my model's owner field is taking None value instead of logged in user as it is a foreign key. Please find my code below my model class Wish(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100,blank=True,default='') wishtext = models.TextField() owner = models.ForeignKey('auth.User', related_name='wishes', on_delete=models.CASCADE, null=True) class Meta: ordering = ('created',) If I don't use null=True its generating NOT NULL constraint error my views class WishList(generics.ListCreateAPIView): queryset = Wish.objects.all() serializer_class = WishSerializer permission_classes = (IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly) # print("object reached here , permissions.IsAuthenticatedOrReadOnly") class WishDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Wish.objects.all() serializer_class = WishSerializer permission_classes = (IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly) my serliazers class WishSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Wish fields = '__all__' class UserSerializer(serializers.ModelSerializer): wishes = serializers.PrimaryKeyRelatedField(queryset=Wish.objects.all(), many=True) class Meta: model = User fields = ['id', 'username', 'wishes'] my object level permission class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the wish. return obj.owner == request.user print(obj.owner) is showing None in the output and NULL in database, I couldn't understand the … -
Django - save file with user specific key in name
I've set up my models, and each profile has image components in the database assigned to them. The image I want to be used is generated in the backend, so it needs to be named corresponding to the user. How do I do that? Currently django is trying to find this image: fig_JFtHslv.png So, what built in can I use to access that key? In this case JFtHslv. I'm assuming that's what I need to do. The model component: simchart = models.ImageField(default='default.jpg', upload_to='simchart') Source in html: src="{{ user.profile.simchart.url }}" -
How to customize an import view in Django Admin (link to file)
I'm using the Import Export Django library and I need to just add a file download (a template Excel file so users can download it) but I just need to know how to customize the import view to include this link. I know the path to the original files is this Lib\site-packages\import_export\templates\admin\import_export The app is "main" so in templates there's a main folder and an admin folder. Should I need to do something in the Form class? (I have two). I tried importing the import file to templates/main/admin/class_name/import.html but the app didn't notice the change -
Django Field 'id' expected a number but got 'coding'
I am getting errors while trying to display all the posts related to one category. Error Message: Field 'id' expected a number but got 'coding' View Code: def CategoryView(request, cats): category_posts = Item.objects.filter(item_category=cats) return render(request, 'waqart/categories.html', {'cats':cats, 'category_posts':category_posts }) URL: path('category/str:cats/', CategoryView, name='category'), Template File: {%extends 'waqart/base.html' %} {% block content %} <h1>{{cats}}</h1> <div class="flex flex-wrap"> {% for item in category_posts %} <h2 class="text-gray-900 text-xl title-font font-medium"{{item.title|truncatechars:40}}</h2> {% endfor %} </div> {% endblock content %} -
Advice on how to come up with the models my app needs?
I've been thinking about making an online store web app using Django, but I've never made an app without following a tutorial. When following a tutorial, I never really came up with the models my self. How do i know what models my app needs to have so that i can pass it into the database. I already created the front end i just want to know if anyone has an idea or advice so that i can know what models to pass to my database? -
Extract details from Integrity error in Django
I'm getting integrity error from Django in below format ForeignKeyViolation('insert or update on table "foo_bar" violates foreign key constraint "foo_obj_product_id_97ae618a_fk_designman"\nDETAIL: Key (product_id)=(9bb7fd8c-2ed2-4a75-ab08-c749459a5097) is not present in table "foo_product".\n' Is there any inbuilt method to extract the "details"? -
Django: Process FileField in model clean method, NOT after save
I have a model: class MyModel(models.Model): csv = models.FileField(upload_to='csvs') rows = models.IntegerField(default=0) I'm trying to read a CSV file to see how many rows it has and save that to an attribute rows. I'm using pandas to read the csv and get the number of lines of the CSV has. I want to do this BEFORE the model saves. I thought it would work like this: import pandas as pd from django.db import models class MyModel(models.Model): csv = models.FileField(upload_to='csvs') rows = models.IntegerField(default=0) def clean(self): self.rows = len(pd.read_csv(self.csv).index) def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) However, this returns the following error (which seems to be from pandas): No columns to parse from file The weird part is it works if I put it AFTER an initial save, like this: import pandas as pd from django.db import models class MyModel(models.Model): csv = models.FileField(upload_to='csvs') rows = models.IntegerField(default=0) def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) self.rows = len(pd.read_csv(self.csv).index) return super().save(*args, **kwargs) That seems really weird and inefficient (saving twice I mean). How can I process the csv like I would after a save BEFORE a save? And what's the difference?