Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cached_property and classmethod doesnt work together, Django
I am trying to use cached_property and classmethod decorators together in a viewset but it doesnt work regardless of their mutual position. Is it any chance to make it work together or cached_property doesnt work with classmethod? Tnanks. @cached_property @classmethod def get_child_extra_actions(cls): """ Returns only extra actions defined in this exact viewset exclude actions defined in superclasses. """ all_extra_actions = cls.get_extra_actions() parent_extra_actions = cls.__base__.get_extra_actions() child_extra_actions = set(all_extra_actions).difference(parent_extra_actions) return (act.__name__ for act in child_extra_actions) -
There is a problem distributing django using heroku
Now I enter heroku create git push heroku master heroku run python manage.py migrate heroku run python manage.py createsuperuser heroku open I had error enter image description here How can I solve this problem? My github url is https://github.com/chea-young/local_library -
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
I've just moved my project which was running perfectly in windows to centos 7. I've all the required dependencies installed in virtual environment and have mysql database running at http://localhost/phpmyadmin, using xampp. however, python manage.py runserver throws me following error : django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)") also systemctl status mysqld throws following error (myvenv) [root@CIPL-5PC226 django-project]# systemctl status mysqld ● mysqld.service - MySQL Server Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled) Active: deactivating (stop-sigterm) (Result: exit-code) Docs: man:mysqld(8) http://dev.mysql.com/doc/refman/en/using-systemd.html Process: 11595 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=1/FAILURE) Process: 11572 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS) Tasks: 23 CGroup: /system.slice/mysqld.service └─11598 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid Jun 01 14:24:17 ABCD-5PC226 systemd[1]: Starting MySQL Server... Jun 01 14:24:18 ABCD-5PC226 mysqld[11595]: Initialization of mysqld failed: 0 Jun 01 14:24:18 ABCD-5PC226 systemd[1]: mysqld.service: control process exited, code=exited status=1 because of my limited knowledge of centos, despite searching and trying out multiple solutions, I've not been able to resolve the issue yet. my understanding is that i have sql running at localhost/xampp but due to some reason the project is not able to connect despite clearly mentioned in the database section of settings.py file of django project. -
How to set DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings? Time to give up with this?? :(
I am really with Django and I am getting a little bit crazy with this issue. I created a new project and app in Django, runserver without problems, but if I ran : django-admin check Im gettin this error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LANGUAGE_CODE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to solved with differents solutions proposed but none of them worked (probably bad execution by me, idk). Really hope you can help me guys! Thanks in advance, Best. Example of similar error than mine, that i took from here ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings The answer proposed is: export DJANGO_SETTINGS_MODULE=mysite.settings I tried set DJANGO_SETTINGS_MODULE=mysite.settings with my app name instead of "mysite" in my app folder but it does not work... 22:46:15 web.1 | Traceback (most recent call last): 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker 22:46:15 web.1 | worker.init_process() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process 22:46:15 web.1 | self.wsgi = self.app.wsgi() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi 22:46:15 web.1 | self.callable = self.load() 22:46:15 web.1 | File … -
Django modelforms attrs not passed to template
In Django3 I have a modelform, and I want to add some styling to the rendered form Here is the model: class Inschrijf(models.Model): naam = models.CharField(max_length=100) This is the form: class InschrijfForm(ModelForm): class Meta: model = Inschrijf fields = ('naam',) wigets = { 'naam': TextInput(attrs={'class':'form-control','required': 'required','placeholder': 'Naam contact persoon'}), } labels = { 'naam': 'Contact persoon', } error_messages = { 'naam': { 'required': 'Vul uw naam in' } } This is rendered as: <p><label for="id_naam">Contact persoon:</label> <input type="text" name="naam" maxlength="100" required id="id_naam"></p> The custom label is passed to the template, but the widgets part not -
How get products from product table based on the category search in django restframework, How do inner join in django restframework
I am very much new in django restframework,I tried to create a search api. I have 2 models designed class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): product_name = models.CharField(max_length=255) product_Comments = models.CharField(max_length=255) size = models.CharField(max_length=10, null=True) product_Status = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) def __str__(self): return self.product_Description I want to create a rest API, in which I can search the category and based on the search i want to list the product which related to that category. How can I do it. -
Python Django Make Migrations Bug, always trying to delete
Whenever I run the makemigration command it always generate a delete script: Generated by Django 3.0.6 on 2020-06-01 23:28 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('chat', '0001_initial'), ] operations = [ migrations.DeleteModel( name='MessageModel', ), ] I am not trying to delete the model. So I try to run the migrate, then the model gets delteted from mysql. Then I try to make changes to model and ru nmakemigrations but it cannot detect any change. So I delete the makemigrations manually but everytime I run it again it delete the model from database.. i spent hours but can't figure out why -
Django with Djongo, EmbeddedFields returns Models aren't loaded yet
I have a new Django project setup. I have only one package installed Djongo. And i have a local MongoDB running. If I write a simple model with just CharFields in models.py in my app the migration works fine. But when I use EmbeddedFields it returns an error. I've copied the code from the Djongo documentation to test with code that should work. Code Source This is what I have in my models.py: from djongo import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True class Entry(models.Model): _id = models.ObjectIdField() blog = models.EmbeddedField( model_container=Blog ) headline = models.CharField(max_length=255) objects = models.DjongoManager() Error message when running py manage.py makemigrations File "C:\Users\FelixEklöf\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 178, in get_models self.check_models_ready() File "C:\Users\FelixEklöf\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Is there any way to force django run some finishing code before exit?
I am running a server program with django, I want to run some code before and after the server running. Where can I put those code? <run function a here> Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ^C <run function b here> -
Post() got an unexpected keyword argument 'user'
views.py Post() got an unexpected keyword argument 'user' so how i solve this error def post(request): if request.method=="POST": Image=request.FILES['image'] caption=request.POST.get('ta','') userr=request.user post_obj=Post(user=userr,image=Image,caption=caption) print(userr,Image,caption,end='\n') post_obj.save() models.py from django.db import models from django.contrib.auth.models import User # # Create your models here. from django.db import models # # # Create your models here. class Post(models.Model): userr = models.ForeignKey(User,on_delete=models.CASCADE) image=models.FileField(upload_to='media/',blank=True) caption = models.CharField(max_length=200,default="") timeStamp=models.DateTimeField(auto_now_add=True,blank=True,null=True) -
Django CSS changes are not applied
I am new to Django and I am using a CSS file for my styles and for now the styles are applied to my html. Now I have created a new class: .post-image { height: 500px; width: 500px; } and have applied the class to the HTML element I want to style like this: <img class="post-image" src="{{ post.image.url }}" alt=""> But the class post-image does not apply somehow. When I change it back to the old class the image gets resized. Also when I tried to edit the old class in my main.css the changes were not applied. My main.css file is in my static directory and I have added the static directory in my settings.py file like this: STATIC_URL = '/static/' and I have imported the stylesheet in my base.html like this: <link rel="stylesheet" type="text/css" href="{% static 'feed/main.css' %}"> -
Guidance on Which Framework to use for app development
I am new to web and app development. I started with Django but I am facing difficulty in understanding the different functions they have made. Actually I am not able to understand the logic behind functions already defined . But my brother suggests me to just use them. So I am a bit confused if i have done right by starting with django framework. I know python, javascript,java. So should i shift to Node.Js or continue with django. -
How to render the values in a parent child relationship in Django
I am creating a django app where the admin can add travel packages. To add the explicit details of the package I created a child that will handle those values. Here is how the code looks like. class Category(models.Model): title = models.CharField(max_length=30) slug = models.SlugField(unique=True) class Meta: ordering = ['title'] def __str__(self): return self.title class SafariPackages(models.Model): image = models.ImageField(upload_to='SafariPackages/%Y/%m/%d', null=False) title = models.CharField(max_length=200) cost = models.FloatField(null=False) days = models.FloatField(blank=False, null=False) nights = models.FloatField(blank=False, null=False) category = models.ManyToManyField(Category) exodus = models.CharField(max_length=200) destination = models.CharField(max_length=200) telegram = models.TextField(max_length=140, null=False) description = models.TextField(null=False) slug = models.SlugField(max_length=200, unique=True) objects = EntryQuerySet.as_manager() def __str__(self): return self.title class Meta: verbose_name = 'Safari Package Entry' verbose_name_plural = 'Safari Package Entries' class DayNumber(models.Model): daydetails = models.ForeignKey(SafariPackages, related_name='daydetails', default=1, on_delete=models.CASCADE) day_number = models.CharField( max_length=10, null=True, blank=True) image = models.ImageField (upload_to='SafariPackagesDetails/%Y/%m/%d', null=False, default=1) day_description = models.TextField() The views that I have so far look like this def safaripackages_view(request, *args,**kwargs): print (args, kwargs) print (request.user) all_safaripackages = SafariPackages.objects.all() #Paginator paginator = Paginator(all_safaripackages, 8) page = request.GET.get('page') try: all_safaripackages = paginator.page(page) except PageNotAnInteger: all_safaripackages = paginator.page(1) except EmptyPage: all_safaripackages = paginator.page(paginator.num_pages) context = { 'all_safaripackages': all_safaripackages, } return render (request, "safaripackages.html", context) def single_safaripackage(request, post_id): safaripackage = SafariPackages.objects.get(pk=post_id) return render (request, 'single_safaripackage.html', … -
how to get value of this variable outside if loop in django template
{% define "color:green" as bcolor %} {% define "false" as wishl %} {% for i in wishlist %} {% if i.0 == itm.5 %} {% define "color:red" as bcolor %} {% define "true" as wish %} {{bcolor}} {% else %} {% define "color:green" as bcolor %} {{bcolor}} {% define "false" as wishl %} {% endif %} {% endfor %} {{bcolor}} <a class="text-center ml-auto "><center><i class="fa fa-heart fa-lg ml-auto "wishlist="{{wish}}" style="{{bcolor}};" id="wish" onclick="wishlist(this,{{forloop.counter}})" attrbute="" ></i></center></a> i want to get the value of the variable out side if condition,If the item id = wishlit .item id then change the bg color as red else green -
autoupdate the data from excel in django
I have imported data from excel file using ImportExportModelAdmin in django for a model. ie i have imported the stockprices from nse in excel and imported data from excel in quotations class. the data in the excel gets autoupdated every 2 min, Now my problem is... How should I enable the autoupdate of the prices in the quotations objects whenever the prices in excel gets updated? -
TypeError 'item' object is not iterable
Я хотел чтобы можно было перейти через категории к предметам а через них к их описанию. Но получил такую ошибку. Вот код. views.py from django.shortcuts import render from shop.models import Category, Item, Comment from django.http import HttpResponseRedirect, Http404, HttpResponse def mainpage(request): categorys = Category.objects.all().order_by('name') return render(request, 'shop/mainpage.html', {'categs':categorys}) def items(request, categ_id): try: itemss = Item.objects.get(id = categ_id) except: raise Http404("Not found") return render(request, 'shop/items.html', {'itemss':itemss}) def info(request, item_id): try: item = Item.objects.get(id = item_id) except: raise Http404("No one item is no found") return render(request, 'shop/info.html', {"item":item}) models.py from django.db import models class Category(models.Model): name = models.CharField(max_length = 20, unique = True) def __str__(self): return self.name class Meta: verbose_name = "Категория" verbose_name_plural = "Категории" class Item(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) name = models.CharField(max_length = 20, default = "Unknown") item_desc = models.TextField(default = "Empty") publish_date = models.DateTimeField(auto_now = True) price = models.CharField(max_length = 20, default = 0) quanty = models.CharField(max_length = 10000, default = 0) def __str__(self): return self.name + " " class Meta: verbose_name = "Предмет" verbose_name_plural = "Предметы" class Comment(models.Model): item = models.ForeignKey(Item, on_delete = models.CASCADE) author_name = models.CharField(max_length = 20, unique = True) comment_text = models.TextField(default = "Empty") publish_date = models.DateTimeField(auto_now = True) def __str__(self): return self.author_name … -
Django rest framework error AssertionError `child` is a required argument
when developing my application I ran into a problem AssertionError at /api/update/ `child` is a required argument. Request Method: GET Request URL: http://45.56.80.77/api/update/?token=1234567&ifloorplan=2 Django Version: 3.0.6 Exception Type: AssertionError Exception Value: `child` is a required argument. Exception Location: /root/Env/ifloorplan/lib/python3.8/site-packages/rest_framework/serializers.py in __init__, line 591 Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.2 Python Path: ['.', '', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/root/Env/ifloorplan/lib/python3.8/site-packages'] Server time: Mon, 1 Jun 2020 07:18:31 +0000 that is, I tried to update and create in the database a record of this kind [ { "id": 2, "level": [ { "id": 2, "plan_level": { "img": null, "img_height": null, "img_width": null, "position_x": null, "position_y": null, "level": null }, "images": [ { "id": 2, "cam": [ { "id": 2, "ken_burns": { "effect": null, "start_pos_x": null, "start_pos_y": null, "finish_pos_x": null, "finish_pos_y": null, "start_width": null, "start_height": null, "finish_width": null, "finish_height": null, "cam": null }, "rotation": 0.34, "pos_x": 21.0, "pos_y": 234.0, "width": 1234.0, "height": 234.0, "img": 2 }, { "id": 3, "ken_burns": { "effect": null, "start_pos_x": null, "start_pos_y": null, "finish_pos_x": null, "finish_pos_y": null, "start_width": null, "start_height": null, "finish_width": null, "finish_height": null, "cam": null }, "rotation": 4.0, "pos_x": 354.0, "pos_y": 345.0, "width": 345.0, "height": 345.0, "img": 2 } ], "img": "/media/ifloorplans_source/test.jpg", "level": 2 } ], "tabLabel": "1 st", … -
How to get the sum of a specific column from database in django?
I have written code like this but it is not working Error Displaying : No function matches the given name and argument types. You might need to add explicit type casts. from django.db.models import Sum Coach.objects.aggregate(Sum('number')) -
Pass additional paramenters to django url
I want to pass additional arguments to django url. I am trying to do something when I am passing 'test_data' as an additional argument from testfile but how to send it through url. Urls.py: path('business/average/difference/<str:start_date>/<str:end_date>/', views_noquery.AverageChangeDifference.as_view()), views.py: def mock_funcname(func): def wrapper(request, *args, **kwargs): if kwargs.get("test", None) is not None: print('ghj') return Response({'detail': "Some stuff mocked for this user :)"}) return func(request, *args, **kwargs) return wrapper class AverageChangeDifference(APIView): '''Average change difference''' #permission_classes = [IsAuthenticated] @mock_funcname def get(self, request,*args, **kwargs): print(kwargs) if kwargs.get("start_date", None) is not None and kwargs.get("end_date", None) is not None: dataset = requests.get(config['url']['API_FETCH_URL']).json() change_difference = [] for data in dataset: data_date = datetime.datetime.strptime(data['Date'], "%d-%b-%Y").strftime("%Y-%m-%d") if data_date > kwargs["start_date"] and data_date < kwargs["end_date"] and data['Open']>data['Close'] : change_difference += [data['High']- data['Low']] #sum(change_difference)/len(change_difference) return Response({"Average change difference" : sum(change_difference)}) testfile for restapi: def AverageChangeDifference(self) : response_AverageChangeDifference = client.get('/business/average/difference/'+ self.Start_Date+'/' + self.End_Date +'/',{'test':'test_data'}) self.assertEqual(response_AverageChangeDifference.status_code, status.HTTP_200_OK) return "AverageChangeDifference passed" -
How To Unit Test Blank DateTimeField
I am trying to unit test a form which includes a date selector. It is saved in the model as DateTimeField and in the form uses a DatePickerInput widget. This is the test: def test_form_validation_for_blank_items(self): user = User.objects.create_superuser('username') self.client.force_login(user) form = PersonalInformationForm(data={ 'first_name': '', 'surname': '', 'gender': '', 'dob': ''}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'first_name': ['This field is required.'], 'surname': ['This field is required.'], 'gender': ['This field is required.'], }) And the error that's thrown: AttributeError: 'NoneType' object has no attribute 'year' My other fields are fine, but I was wondering how to unit test a blank DateTimeField model with a DatePickerInput widget. Thank you. -
Django-REST-Framework REST API within django app
I'm wondering if there is a way to access REST API within the Django app. I created a REST API using the Django rest framework. In the same project, I'm having another app in which I want to fetch data using my own rest API. -
How to only save model objects that have changed?
I want to only save the records I update via the formset. At the moment ALL my updated_by fields change to the User that is logged in, not just the ones I change in the form. Views.py @login_required() def inventory_update(request): title = 'Update Inventory' UserInventoryFormset = modelformset_factory(Inventory, form=InventoryUpdateForm, extra=0) if request.method == 'POST': formset = UserInventoryFormset(request.POST) if formset.is_valid(): for form in formset: updated = form.save(commit=False) updated.updated_by = request.user updated.save() else: formset = UserInventoryFormset() context = {'formset': formset, 'title': title } return render(request, 'main/inventory_form.html', context) Models.py class Inventory(models.Model): item = models.CharField(max_length=50, unique=True) stock = models.IntegerField() par = models.IntegerField() date_updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.item Forms.py class InventoryUpdateForm(forms.ModelForm): class Meta: model = Inventory exclude = ['updated_by'] fields = ['stock', 'par'] -
How can I get all contacts in a email using contact Api Django
I was going through this. How to use google contacts api to allow my users to invite their gmail contacts to my django website What I need to do if I ask my user to write the email.I want to get contacts of that email not of user. What steps should be taken to get contacts. -
django list_filter in html
How do i import this list_filter into my html? do you have any documentation that easy to follow and easy to understand? is it possible? class ArticleListView(ListView): model = StudentsEnrollmentRecord s=StudentsEnrollmentRecord.objects.all() paginate_by = 50 # if pagination is desired searchable_fields = ["Student_Users", "id", "Section"] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context -
How to get active users from last X mins in Django
I have a website created in Django, How can I get a list of active users from last X mins. I want all not-logged in as well as logged-in users.