Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
django AJAX POST action that redirects user to login URL if not logged in
I am using django 3.2 I am trying to implement functionality that I have seen on other websites - where when you try to comment (for example), without login, it redirects you to the login page. It is trivial to do this for GET routes - however, it is not clear to me, how to implement this functionality for AJAX POST functions. Example: /path/to/myapp/views.py class FoobarMixin(LoginRequiredMixin, UserPassesTestMixin): def test_func(self): user = self.request.user if user.is_superuser: return True return some_foobar_test() class FooCreateView(FoobarMixin, CreateView): http_method_names = ['post'] context_object_name = 'foo_object' def get_object(self, queryset): content_type = self.request.POST.get('ct') object_id = self.request.POST.get('id') self.foo_object = get_object_by_content_type_and_object_id(content_type, object_id) return self.foo_object def post(self, request, *args, **kwargs): foo_object = self.foo_object retval = foo_object.just_do_it(self.request.user) new_count = foo_object.foo_count if retval else None return JsonResponse({'retval': retval, 'new_count': foo_count}) /path/to/myapp/urls.py ... path('whatever/foo/', views_foo.FooCreateView.as_view(), name='do-foo'), ... /path/to/myapp/templates/myapp/page.html {% extend 'base.html' %} {% load static %} {% block content %} <a class="foo"><i class="foo fa fa-smile-o</i></a> {%end block %} {% block body_js %} $('a.foo, a.foo > i').on('click', function(e){ $.ajax({ type: "POST", url: "{% url 'do-foo' %}", data: { ct: '{{ content_type }}', id: '{{ foo_id }}', csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: "json", success: function(resultData){ console.log(resultData); }, error: function(xhr, status, error) { console.log(status); console.log(`error from server: ${status}`); … -
How to have a field only supereditable in Django?
Note I know this question has been asked previously but i am using that suggestion only but not giving me desired result my model class QuestionModel(models.Model): question = models.TextField() mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default="", blank=True) my admin.py class QuestionAdmin(admin.ModelAdmin): def get_readonly_fields(self, request): fields = super().get_readonly_fields(request) if not request.user.is_superuser: fields.append('answer') return fields admin.site.register(QuestionModel, QuestionAdmin) i am trying to make this answer field onlyt superuser editable thats how i ma doing but a normal user is also able to update it but a simple put request, so how to prevent that user from updating -
I want to add Three js project to Django Project. Can anyone Guide me in how to update settings.py file and show the tree structure of the directory
This is my settings.py file STATICFILES_DIRS = [ "/rios/search/static/", "/rios/user/static/", "node_modules" ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django_node_assets.finders.NodeModulesFinder', 'npm.finders.NpmFinder' ] NODE_PACKAGE_JSON = 'package.json' NODE_MODULES_ROOT = 'node_modules' I used this library django-node-assets https://pypi.org/project/django-node-assets/ The image shows how my folders and files are arranged in Project Directory My Tree Structure -
how to reduce list chart to one and use select dropdown to show selection without refresh page?
I am a beginner learning to make charts with pandas converted in json format. I have a lot of graph against the data, but it takes a lot of space; so i would like to know how can i make a filter and only display what the user want to see. I read some tutorial that made with dropdowns with html, but the problem is that I have to do this dynamically and depending on the size of the data, do you have any suggestions for the process? var trend_axe = {{trend_axe | safe}}; for (i in trend_axe){ var item = JSON.parse(trend_axe[i]); var label = []; for (j in item){ label.push(item[j].date_); } var stock = []; for (k in item){ stock.push(item[k].stock); } new Chart(document.getElementById(item[i].axe),{ type :'line', data :{ labels: label, datasets: [{ label: 'Trend journalier des ventes', data: stock, fill: false, borderColor: '#0E9036', tension: 0.1 }] }, }); }; what i could do : <div class="chart"> <canvas id="MDVS1"></canvas> <canvas id="MDV03"></canvas> <canvas id="MDV01"></canvas> <canvas id="MDV04"></canvas> </div> -
Collapse Django NavBar on Hover (Mouse out)
I am in need to hide a django app 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 the reason the navbar has been hidden forever and how I could make it expand on mouse over? How I could achieve the same goal by just using BootStrap4 class=collapse? -
Django runserver is not working with ModuleNotFoundError: No module named 'test' error
Getting the below error when I am running the python app/manage.py runserver command. Not sure what is going wrong there. I tried with different version of django and getting the same error with all django version. Python: 3.6.6 Django: 3.1.5 ubuntu: 14.04 Error: root@e1dd33f6a3ef:/code# python app/manage.py runserver --noreload Traceback (most recent call last): File "app/manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'test' -
Accessing primary key in Django class based view
Accessing primary keys in Django class based view Let's start from the beginning. I have 2 models, Recipe, and Ingredient. They look like this. In models.py class Recipe(models.Model): name=models.CharField(max_length=20, help_text='Enter the name of this recipe') description=models.TextField(max_length=75, help_text='Describe your recipe') def __str__(self): return self.name def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk`}) class Ingredient(models.Model): recipe=models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient=models.CharField(max_length=100) class Meta: ordering = ['ingredient'] def __str__(self): return self.ingredient What I want to be able to do is have a detail view, where I can access the Recipe attributes, like the name and description, as well as, be able to loop through the ingredients. This is what I have working so far: In views.py def recipe_detail_view(request, pk): recipe = get_object_or_404(Recipe, pk=pk) context = { 'recipe': recipe, 'ingredients': Ingredient.objects.filter(recipe=pk) } return render(request, 'recipes/recipe_detail.html', context=context) In urls.py # ... path('recipes/<str:pk>', views.recipe_detail_view, name='recipe-detail') # ... In template <h1 class="title is-1">{{ recipe.name }}</h1> <p>{{ recipe.description }}</p> <h3 class="title">Ingredients</h3> {% for ingredient in ingredients %} <h4 class="">{{ ingredient.ingredient.title }}</h3> {% endfor %} I am wondering how I could turn this into a class based view however. More specifically, I am wondering how I can access and pass in the primary key to the filter like so: class RecipeDetailView(generic.DetailView): model = Recipe … -
i m unable to fetch profile pic
i have a default profile pixand want to show it in my html but unable to get it html code <img class="profile-pic nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="max-width: 45px; max-height:45px; border-radius: 50%;" src="{{ user.accounts.profile.profile_pic.url }}" > model class Profile_Pic(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE,) profile_pic = models.ImageField(upload_to='profile_pics', default='default.png',) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username -
while user hover on anchor tag link then a drop down should open
below is my code where where I have mention one is an anchor tag in anchor tag I have given a "class=trigger". In that anchor tag I have main categories and after that anchor tag I have given a div which is also defines with "class=sub". In this div I have complete sub categories. Know I am trying to achieve like while user hover on achor tag which is "class=trigger" then the div which is "class=sub" should display on hovering at anchor tag. So how can we achieve this using css or javascript. <a class="trigger" href="{% url 'getProductsByCategory' Categories.cat_name %}">{{Categories.cat_name}}</a> <div class="sub"> {% for subCategories in SubCategoriesBar %} {% if Categories.cat_id == subCategories.parent_id %} <div class="item">{{subCategories.cat_name}}</div> {% endif %} {% endfor %} </div> -
Deploying Django on Heroku
I am trying to dploy my django application on heroku and keep getting this error message: ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xo9jsddf/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xo9jsddf/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-xuxym03s/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/psycopg2 Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed``` I have my Procfile and requirements.txt. Any help is appreciated! -
ModuleNotFoundError: No module named 'pip' on virtual environment
Pip doesn't work in my virtual environment. As I create a virtual env, it works fine for the first time, and it doesn't seem to work the next time. Even after I upgrade pip to the latest version, it throws the same error. How may I solve this issue? pip freeze Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "D:\Fast\name\venv\Scripts\pip.exe_main.py", line 4, in ModuleNotFoundError: No module named 'pip'