Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin add field from parsing text
I have a question. First, I have a Django model such as below: class MyModel(models.Model): text = models.CharField() In Admin page, I want to a parsing text and add fields dynamically. class MyModelAdmin(ModelAdmin): model = MyModel fields = (parsing1, parsing2, parsing3 ... ) # like this... That time, for efficiency, I want to use just only one parsing function. def _parsing_text(self, obj): return { idx: text for idx, text in enumerate(obj.text) } # def parsing1( blah... blah...): self._parsing_text()[0] ... What should I do? -
How can I add a comma to separate each group of three digits with jinja?
for this, which filter should i use? Project Total weight = 1000000 {{project.total_weight}} >> 1.000.000 -
What kind of Django Model inheritance should i use for multiple classes sorting different information of a single person?
I am new to coding and Django, I need to have 5 model classes to store different info about a person (basic info, medical history,diet,exercise). The fields need not be related to each other across the tables but i want to have the cascade delete option(ie basic info fields like age etc are not related to medical conditions or exercise, but they all are information for a single person). I tried the making the basic info a parent class and used Multitable inheritance, but it gave me duplicate entries of all the parent class fields in the database. I tried making an abstract class and rest all classes as child classes, but in this case i dint have the cascade delete option(i.e if i delete a persons basic info, his medical history still remains in db). How do i approach this? -
Django rest_framework: Get only last entry from SlugRelatedField
Let's say I have two models: class MediaFiles(models.Model): filename = models.CharField(max_length=300) class Program(models.Model): media = models.ForeignKey(MediaFiles, related_name='program_set', db_column='fileID', null=True, on_delete=models.SET_NULL) start = models.DateTimeField() With this serializer: class MediaFilesSerializer(serializers.ModelSerializer): program_start = serializers.SlugRelatedField( source='program_set', slug_field='start', many=True, read_only=True ) class Meta: model = MediaFiles fields = ('filename', 'program_start') class ProgramSerializer(serializers.ModelSerializer): media = MediaFilesSerializer() class Meta: model = Program fields = ('start', 'media') In my MedeFilesViewSet I would like to have the possibility to filter and order against program_set__start. Something like: class MediaFilesFilter(filters.FilterSet): program_set__start = filters.DateFromToRangeFilter() class Meta: model = MediaFiles fields = ['program_set__start'] class MediaFilesViewSet(viewsets.ModelViewSet): queryset = MediaFiles.objects.all() serializer_class = MediaFilesSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filterset_class = MediaFilesFilter ordering_fields = ['program_set__start'] The problem here is now, that program_start from serializer will have a list with many entries. Like: { "filename": "/path/to/file/test.mp4", "program_start": [ "2020-04-02T10:55:02.920000Z", "2020-04-27T11:40:20Z", "2020-05-21T11:35:44.160000Z" ] } So the filtering and ordering are not correct. I need a way to have only the last program item in program_start list. I tried to add a queryset in my SlugRelatedField with arguments like .last() etc. but it looks like that this is not possible. Can you give me an example of how can I limit program_start list to its last entry. And be able … -
sudo systemctl start uwsgi giving a 203 error
I tried to host my website on a linux server and now I was configuring the uwsgi for it. I made my project.ini file in /etc/uwsgi/sites Here's it [uwsgi] project = salesproject base = /home/ubaid chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 2 socket = %(base)/%(project)/%(project).sock chmod-socket = 666 vacuum = true Then I made a uwsgi.service in /etc/systemd/system/ [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target Now when I run sudo systemctl start uwsgi It gives me an error like this ● uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-05-18 17:08:45 IST; 3s ago Process: 33974 ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites (code=exited, status=203/EXEC) Main PID: 33974 (code=exited, status=203/EXEC) When I cd into usr/local/bin there is no uwsgi, there is only virtual env. How can I resolve this issue please help! -
Need help Django and react Login
Hi im super new to this , and i would like some help on how to implement login in react and django. Basically i made a sign up form that sends the data to the data base through some api. How would i implement the checking of the username and password in order to login? getReq(event){ // Make a request for a user with a given ID axios.get('/api/todos/') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); event.preventDefault(); } this gives me all the users -
The real difference between MEDIA_ROOT and STATIC_ROOT in python django and how to use them correctly
The real difference between MEDIA_ROOT and STATIC_ROOT in python django and how to use them correctly? I just was looking for the answer and i'm still confused about it, in the end of the day i got two different answers: - First is that the MEDIA_ROOT is for storing images and mp3 files maybe and the STATIC_ROOT for the css, js... and so on. -Second answer is that they were only using MEDIA_ROOT in the past for static files, and it caused some errors so eventually we are only using STATIC_ROOT. is one of them right if not be direct and simple please so everybody can understand and by how to use them correctly i mean what kind of files to put in them exactly -
Running tests with model_mommy and django-modeltranslation fails with Unknown population mode 'Default'
I wrote a unittest using model_mommy that looks like this: from django.test import TestCase from model_mommy import mommy class AttributeValueAssociationTest(TestCase): def test_sanity_check_configurable_attributevalueass(self): attribute = mommy.make('Attribute', use_for_configrations=True) value_1 = mommy.make('AttributeValue', attribute=attribute) value_2 = mommy.make('AttributeValue', attribute=attribute) product_1 = mommy.make('products.Product', type='SIMPLE') ass_1 = mommy.make('AttributeValueAssociation', product=product_1, attributevalue=value_1) with self.assertRaises(ValueError): ass_2 = mommy.make('AttributeValueAssociation', product=product_1, attributevalue=value_2) On the models Attribute, AttributeValue and Products I have fields that use django-modeltranslation for our languages. They look something like this: from modeltranslation.translator import register, TranslationOptions from .models import Attribute, AttributeValue @register(Attribute) class AttributeTranslationOptions(TranslationOptions): fields = ('name',) required_languages = ('en-gb',) @register(AttributeValue) class AttributeValueTranslationOptions(TranslationOptions): fields = ('value',) required_languages = ('en-gb',) Now when I'm running ./manage.py test attributes, django returns: ERROR: test_sanity_check_configurable_attributevalueass (attributes.tests.AttributeValueAssociationTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/sascha/Sites/Sila2/attributes/tests.py", line 8, in test_sanity_check_configurable_attributevalueass attribute = mommy.make('Attribute', use_for_configrations=True) File "/Users/sascha/Sites/Sila2/venv/lib/python3.7/site-packages/model_mommy/mommy.py", line 60, in make **attrs File "/Users/sascha/Sites/Sila2/venv/lib/python3.7/site-packages/model_mommy/mommy.py", line 254, in make return self._make(**params) File "/Users/sascha/Sites/Sila2/venv/lib/python3.7/site-packages/model_mommy/mommy.py", line 304, in _make _from_manager=_from_manager, File "/Users/sascha/Sites/Sila2/venv/lib/python3.7/site-packages/model_mommy/mommy.py", line 329, in instance instance = self.model(**attrs) File "/Users/sascha/Sites/Sila2/venv/lib/python3.7/site-packages/modeltranslation/translator.py", line 259, in new_init populate_translation_fields(self.__class__, kwargs) File "/Users/sascha/Sites/Sila2/venv/lib/python3.7/site-packages/modeltranslation/translator.py", line 392, in populate_translation_fields raise AttributeError("Unknown population mode '%s'." % populate) AttributeError: Unknown population mode 'Default'. It would seem that django-modeltranlation and model_mommy aren't playing nice together. Could you help me avoid … -
Saving a data into a .txt file in django
I am working on a project in Django where I simply count the number of words when I input a sentence. I also try to save the number of words in a .txt file evry time I use the website. The views.py is: from django.http import HttpResponse from django.shortcuts import render def homepage(request): return render(request,'home.html') def count(request): fulltext = request.GET['fulltext'] wordlist = fulltext.split() f=open('abc.txt','a+') f.write('\n') f.write(wordlist) f.close() return render(request,'count.html', {'fulltext':fulltext, 'count':len(wordlist)}) The homepage where I give the input sentence is: <h1> Word Count </h1> <form action = "{% url 'count' %}"> <textarea col='40' rows = '5' name = "fulltext"></textarea> <br/> <input type = 'submit' value= 'count!' /> </form> The page where I show the output along with the number of words is: <h1> hey, there are {{count}} words</h1> <h1> your text </h1> {{fulltext}} The program runs well in the UI portion. As I give the input sentence in the homepage and submit it, I get the results in the output page. It also generates a abc.txt file in the working directory. However, there is a repetation of the part of the code there as in the .txt file I get the same output twice. That is, if the input sentence … -
Django model add uuid
Django 2.2 postgres I added uuid to my existing django model , generated and applied a migration for the table that already had records in it: migrations.AddField( model_name='<mymodel>', name='uuid', field=models.UUIDField(default=uuid.uuid4, editable=False), ), The field got added fine, however all the existing records got the same value inserted in the uuid field. How do I make default=uuid.uuid4 to generate a new value for each existing records? Thanks -
“detail”: “Method \”GET\“ not allowed.” Error
I am trying to create an article by pulling out data from serializer but i get an error that says “detail”: “Method \”GET\“ not allowed.” Error Why? Views.py class ArticleView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def post(self, request, format=None): try: serializer = self.serializer_class(data=serializer_data, context=serializer_context,) serializer_context = {'request': request } serializer_data = request.data.get('article',{}) if serializer.is_valid(): serializer.save() return Response({'success': True}) else: return JsonResponse({'fail':'True'}) except Exception as e: return JsonResponse({'exception':'True'}) Urls.py from django.conf.urls import url,include from accounts.views import ArticleView urlpatterns = [ url('createarticle/', ArticleView.as_view(), name='articlecreate'), ] -
Page not found error when adding Facebook authentication
I'm following Django-3-by-Example. I followed all instructions but reached a dead spot with a page not found error. I checked FB dev Error page settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ #my apps 'account.apps.AccountConfig', 'social_django', 'django_extensions', #pre intalled apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bookmarks.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bookmarks.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = … -
How to run third party python file in Django
I'm trying to run the 'hello_analytics_api_v3.py' file in Django. But how ! I don't know. -
DRF - django_filters -Using custom methods
I have a model like this: class Agreement(models.Model): file_no = models.IntegerField(primary_key=True) contract_date = models.DateField() contract_time = models.IntegerField() @property def calculate_expiry_date(self): return self.contract_date + relativedelta(years=self.contract_time) @property def is_expired(self): return (self.contract_date + relativedelta(years=self.contract_time)) < timezone.now().date() is_expired function returns true or false for each agreement and I have a simple filter like this: class AgreementFilter(filters.FilterSet): file_no = filters.NumberFilter(lookup_expr='icontains') class Meta: model = Agreement fields = ['file_no',] I think that I cannot filter on the property field because Django filters operate at the database level. So how can I make it work to filter agreement if it is valid or invalid or either true or false -
breaking the django json response
I have the following response with the code: { "id": 716, "name": "XYZ", "start_date": "2019-12-24", "end_date": "2020-01-31", "ads": [ { "id": 20228, "no_of_times_per_hr": 1, }, { "id": 20227, "no_of_times_per_hr": 2 }, { "id": 20229, "no_of_times_per_hr": 7 } ] }, I have written this using the serializer with the following code: class AdsDetailOnScheduler(serializers.ModelSerializer): ads = serializers.SerializerMethodField() class Meta: model = AdCampaign fields = ('id','name','start_date','end_date', 'ads') def get_ads(self, obj): adlabels = AdDayLabelMap.objects.filter(ad_campaign__id = obj['id']).values_list('ad_label', flat = True).distinct() ad_id = AdSlot.objects.filter(ad_label__id__in = adlabels).values_list('ads', flat = True) if Ads.objects.filter(id__in = ad_id).exists(): a = [] for ad in Ads.objects.filter(id__in = ad_id): a.append(AdsDetailSongScheduler(ad).data) return a else: return None class AdsDetailSongScheduler(serializers.ModelSerializer): no_of_times_per_hr = serializers.SerializerMethodField() after_n_songs = serializers.SerializerMethodField() specific_time = serializers.SerializerMethodField() class Meta: model = Ads fields = ('id','no_of_times_per_hr') def get_no_of_times_per_hr(self, obj): if obj.no_of_times_per_hr: return obj.no_of_times_per_hr else: return None However, I would want the response below: { "id": 716, "name": "XYZ", "start_date": "2019-12-24", "end_date": "2020-01-31", "ads": [ { "id": 20228, "no_of_times_per_hr": 1, }, ] }, { "id": 716, "name": "XYZ", "start_date": "2019-12-24", "end_date": "2020-01-31", "ads": [ { "id": 20227, "no_of_times_per_hr": 2 }, ] }, { "id": 716, "name": "XYZ", "start_date": "2019-12-24", "end_date": "2020-01-31", "ads": [ { "id": 20229, "no_of_times_per_hr": 7 } ] }, I would like to explain … -
How to optimize database queries when the create method is invoked?
I send a request to the database to read / write data saved from an exel file. The data are from 4 to 10 thousand lines of json format. I have encountered that the query lasts a very long time . It takes up to 20 seconds on the local compute (quite powerful), and on the server it takes more than a minute and eventually falls off with an error. It seems to me that there is not much data to make the request last so long. the serializer create method looks like def create(self, validated_data): # Get data from url context rfiid = self.context.get('rfiid') vendor_id = self.context.get('vendor') analyst_id = self.context.get('analyst') vendor = Vendors.objects.get(vendorid=vendor_id) round = Rfis.objects.get(rfiid=rfiid) current_scoring_round = self.context.get('current_scoring_round') # for update rfipartisipatiostatus analyst/vendor response (1 or 0) status_info = self.context.get('status_info') # save CI company_information = self.context.get('Company_info') for ci in company_information: ciq, _ = CompanyGeneralInfoQuestion.objects.get_or_create(question=ci.get('question'), rfi=round) cia, _ = CompanyGeneralInfoAnswers.objects.update_or_create(vendor=vendor, question=ciq, defaults={'answer': ci.get('answer')}) # Get data from validated data sc = validated_data.pop('s') cat = validated_data.pop('category') pc = validated_data.pop('pc') self_score = validated_data.pop('self_score') self_description = validated_data.pop('self_description') sm_score = validated_data.pop('sm_score') analyst_notes = validated_data.pop('analyst_notes') attachment = validated_data.pop('attachment') parent_category = ParentCategories.objects.filter(parent_category_name=pc) if parent_category: category, _ = Categories.objects.get_or_create(category_name=cat, pc=parent_category.first()) else: raise serializers.ValidationError({"general_errors": ["Parent categories are … -
All models reset when creating a new one in django
My goal is to generate a random joinkey for every new model based on a function that takes the models own primary key as an argument. The problem is that every time I create a new object the joinkey field resets for every single object in my database, which I do not want, I would only like the joinkey to be added to the new object being created. This is my model: class Project(MainAbstractModel): users = models.ManyToManyField(User) title = models.CharField(max_length=25, default="") @property def joinkey(self): return random_int(self.pk) @joinkey.setter def joinkey(self, value): joinkey = models.IntegerField(null=True, unique=True) def other_user(self): return self.users.exclude(username=user.username) and here is the random_int function just in case: def random_int(primarykey): return int(randint(10000, 99999) + 1000000 + primarykey) -
Display just 3 records instead of all in django
I want to display three records and randomly three record from model. But if I do this, {% for service in services.all %} {{service.title}}<br/> {{service.summary}}<br/> {% endfor %} it display all records. what I need to do display three 3 records from the database Django model? -
Maintain historical data of a model without using trigger in django
I have created HistoryModel replica of a Model. Then I am trying to keep the historical data of that model without using database trigger or any django api. For that, in the edit section of my views.py I have written as below: Basically trying to enter the same data before saving the new value to the actual model. def computer_edit(request, id=None): instance = get_object_or_404(Computer, id=id) form = ComputerForm(request.POST or None, instance=instance) if form.is_valid(): hist = HistoryComputer(instance) #**<< getting error here** hist.save() instance = form.save(commit=False) instance.save() return redirect('djform-home') context = { "title": 'Edit ' + str(instance.computer_name), "instance": instance, "form": form, } return render(request, "djform/computer_entry.html", context) Can we do like that way? -
Cannot import django_countries yet is installed
(operation-fix) bash-3.2$ ls Pipfile Pipfile.lock README.md src (operation-fix) bash-3.2$ pip freeze Django==2.0.7 django-countries==6.1.2 pytz==2020.1 (operation-fix) bash-3.2$ above shows django_countries in the root of project. Should it not be in the root? from django_countries.fields import CountryField above has error unable to import. Yet have added to INSTALLED APPS in settings.py in src. Don't understand what I am missing (am new to python) yet this seems very obvious if you know what to look for. Thanks! -
Razor pay integration with Django
I want to integrate Razorpay payments with Django. I searched, but there are no proper resources. I even checked the Razorpay official website. But there are no proper documentation. Can anyone please help me how to integrate Razorpay with Django -
Is there a way to catch user is not authenticated exception?
I am calling a stored procedure via AJAX request, which requires user id. If the user is not logged in i need to raise an exception. How is this possible? Note that I am using @login_required decorator. @login_required() @require_POST def mail_forward_action(request): try: ...cal procedure except UserIsNotAuthenticated -
What do I put in the Procfile for Gunicorn with Django?
I have uploaded by git repo to Heroku, but I am having a hard time finding out the gunicorn command to put in the Procfile. This is my repo path to the wsgi.py So what should I put in my Procfile. web: gunicorn image_editor.wsgi --log-file - is my current Procfile but there is a module not found error. Thanks -
Django Carousel doesn't render the images
I am new to web development. I am making portfolio app. The carousel from bootstrap is not working. Am I using the right class-based view or something else is wrong? models.py from django.db import models class Gallery(models.Model): name = models.CharField(max_length=250) new_image = models.ImageField(upload_to='gallery_folder') day_publish = models.DateField() def __str__(self): return self.name gallery_detail.html <div class="container" align="center"> <br> <div id="carouselExampleFade" class="carousel slide carousel-fade" data-ride="carousel"> <div class="carousel-inner"> {% for object in objects_list %} <div class="carousel-item"> <img src="{{ object.new_image.url }}" class="d-block w-100" alt="{{ object.name }}"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleFade" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleFade" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> views.py from django.shortcuts import render from .models import Gallery from django.views.generic import ListView, DetailView class GalleryView(ListView): model = Gallery order_by = ['-day_publish'] class PicView(DetailView): model = Gallery urls.py from django.urls import path from .views import GalleryView, PicView urlpatterns = [ path('portfolio/', GalleryView.as_view(), name="portfolio"), path('detail/<int:pk>/', PicView.as_view(), name="pic_info"), ] -
Django table data self generate without refreshing the page with AJAX
Hello guys i am so confuse now is my first time combining ajax with Django and i feel lost, i try to make this self generate table without refreshing i read online i can do this with ajax i try to do this but it will not update the log table. Can anyone of you shed some light over this i would greatly appreciate it! thanks view.py def dashboard(request): mikrotik_session = request.session.get("mikadmin") host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() resource_log = api.get_resource("log") content_log = resource_log.get() return render(request,"dashboard.html",{"content_log":content_log}) def get_more_table(request): mikrotik_session = request.session.get("mikadmin") host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() increment = int(request.GET.get('append_increment')) increment_to = increment + 20 resource_log = api.get_resource("log") content_log = resource_log.get()[increment:increment_to] return render(request,"get_more_table.html",{"content_log":content_log}) urls.py urlpatterns = [ path("dashboard",views.dashboard,name="dashboard"), path("mikrotiklogin",views.mikrotikapi,name="mikrotiklogin"), path("get_more_table",views.get_more_table,name="get_more_table"), ] get_more_table.html and ajax script in the same file {% load static %} {% for contents_log in content_log %} <li class="left clearfix"><span class="chat-img pull-left"> </span> <div class="chat-body clearfix"> <div class="header"><strong class="primary-font">{{contents_log.topics}}</strong> <small class="text-muted">{{contents_log.time}}</small></div> <p>{{contents_log.message}}</p> </div> </li> {% endfor %} dashboard.html <div class="panel-heading"> Log <span class="pull-right clickable panel-toggle panel-button-tab-left"><em class="fa fa-toggle-up"></em></span></div> <div class="panel-body" id="log_file"> <ul> {% for contents_log in content_log %} <li class="left …