Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF's NoReverseMatch: 'models' is not a registered namespace
Getting this error when running a test: django.urls.exceptions.NoReverseMatch: 'models' is not a registered namespace # urls.py: router = routers.DefaultRouter() router.register(r'models', CdbModelViewSet) ... urlpatterns = [ path('api/', include(router.urls)), ... Should there be some specific configuration added when using reverse with DefaultRouter? -
How to return the current page url inside a wagtail app's model.py file
I have a wagtail app in which I need to return the current page's url. The code for my model.py of my app is as follows import urllib from django.conf import settings from django.db import models from wagtail.core.models import Page from django.http import HttpResponse class PageUrl(Page): def returnPageUrl(self): page_url = """ i need the page url here """ return page_url -
i am not able to run a import export functionality
i want to import export under django admin panel app data import and export https://django-import-export.readthedocs.io/en/stable/getting_started.html also try with this example https://simpleisbetterthancomplex.com/packages/2016/08/11/django-import-export.html python 3.7 django 2.2.5 django-import-export 1.2.0 settings.py IMPORT_EXPORT_USE_TRANSACTIONS = True models Person resource.py from import_export import resources from .models import Person class PersonResource(resources.ModelResource): class Meta: model = Person admin.py from import_export.admin import ImportExportModelAdmin from django.contrib import admin from import_export import resources from .models import Person, Pravacy_check @admin.register(Person) class PersonAdmin(ImportExportModelAdmin): pass Register your models here. class PersonResource(resources.ModelResource): class Meta: model = Person class PersonAdmin(ImportExportModelAdmin): resource_class = PersonResource admin.site.register(PersonAdmin) all app modules data import and export need to work prefect. -
Django Rest + Mongoengine - Allow model fields to be optional
I've setup a REST api with django rest framework, using mongoengine for models. However, By default all the fields of model are mandatory but I want to make some of the fields as optional. my model.py is : class ProjectFormula(EmbeddedDocument): name = fields.StringField() expression = fields.StringField() class ProjectMeta(Document): project_id = fields.IntField() sheet_mapping = fields.DictField() classificication_map = fields.DictField() concept_map = fields.DictField() formulas = fields.ListField(fields.EmbeddedDocumentField(ProjectFormula)) serializers.py class ProjectMetaSerializer(mongoserializer.DocumentSerializer): class Meta: model = ProjectMeta fields = '__all__' response from Post api: { "sheet_mapping": [ "This field is required." ], "classificication_map": [ "This field is required." ], "concept_map": [ "This field is required." ] } I want to make this fields optional, only project_id and sheet_mapping is mandatory. I tried classificication_map = fields.DictField(required=False) in model.py [From some other research] but didn't work. Any help will be appreciated. -
How to resolve conflicts with the same name of content_type app_label and permission codename in django?
Django's ModelBackend in _get_permissions collects list of strings with content_type__app_label and permission codename, but in default Permission model this string can be not unique (in Permission model unique_together = (('content_type', 'codename'),)). How to solve conflicts when in a module two models have the same permission name. Django 2.1 def check_user_perms_by_ct(user, perm_name, ct): """ Verifies user permissions based on permission code name and content type. :param user: User object. :param perm_name: str. :param ct: ContentType object. :return: Boolean. """ return user.has_perm(f'{ct.app_label}.{perm_name}') -
Django edit foreign-key attribute through parent object form
Using: Python 3.7.3 django 2.2.5 mysql 5.7.27 I have the following models defined: class Item(models.Model): ... asset = models.ForeignKey('Assets', default=None, null=True, on_delete=models.SET_DEFAULT) ... class Comments(models.Model): item = models.ForeignKey('Item', default=None, null=True, on_delete=models.CASCADE) comment = models.TextField(max_length=512, default="", blank=True) class Assets(models.Model): ... assettag = models.CharField(db_column='AssetTag', unique=True, max_length=10) ... I want an Update view that will allow me to update the fields of an Item object, while also providing a way to edit a comment or an assettag. I am using class based views and have the following form defined: class ItemUpdateForm(forms.ModelForm): ... Asset = forms.CharField(label="AssetTag", required=False, widget=forms.TextInput(attrs={"placeholder":"Item Inventory Tag", "rows":1, "cols":7, } ) ) ... class Meta: model = Item fields = [ ..., 'Asset', ..., ] def clean_Asset(self, *args, **kwargs): AssetTag = self.cleaned_data.get("Asset") if len(AssetTag) != 7: raise forms.ValidationError("AssetTag length incorrect") if not AssetTag.lower().startswith("dp"): raise forms.ValidationError("This is not a valid AssetTag") else: try: _asset = Assets.objects.get(assettag = AssetTag) except Assets.DoesNotExist: raise forms.ValidationError("Item does not exist") self.Asset = _asset return self.Asset ItemFormSet = forms.inlineformset_factory(Item, Comments, ItemUpdateForm, fields=('Comment',), extra=1) The view is not fancy: class UpdateView(ObjectMixin, generic.UpdateView): template_name = some template form_class = ItemFormSet ObjectMixin provides some methods that I've used in multiple views: get_object, get_success_url, form_valid and a dispatch with login_required decorator. The … -
i make a project in python and i want to a make web app in django i can't understand how to make web app using these function
1) Create account 2) Deposit 3) Withdraw 4) Balance Inquiry 5) All Account holder list 6) Close Account 7) update info -
Does this selection of AWS Free-Tier Services is appropriate for my web application?
Just to say that I am an absolute beginner to these concepts. My web app right now The user makes requests that Django handles as follows: 1.a) Django run queries (based on user selection) on csv files that it keeps 2.b) Django keeps also 1 small database for registered users Possible upgrade of my web app If ever I want to upgrade my app, I will replace csv files with databases (1 for each user) Note, that I have already dockerized my whole application in order to have the same development and production environment, using this architecture: 2.a) Nginx Container that sends requests either to b1 or to b2 2.b1) Angular Static Files Container 2.b2) Django App Container 2.c) Django Database Container Selected Free Tier AWS Services So, Ι have concluded the use of the follows AWS Free-Tier Services: 3.a) Angular static files -> AWS S3 and AWS Cloudfront 3.b) Django Docker Container -> AWS ECS 3.c) Django Database -> AWS RDS Questions 4.a) Does this selection of Free-Tier AWS Services make sense? 4.b) What about the consistency of development and production environments that I had using Docker before? -
How to display all my model's fields in django admin?
This code displays objects like this: Home Object(1) ,Home Object(2) but I want to display all the model fields in my django admin page.How can I do this? I am very beginner in django and this is my first project. models.py class Home(models.Model): image=models.ImageField(upload_to='home') paragraph=models.TextField() created=models.DateTimeField(auto_now_add=True) admin.py admin.site.register(Home) -
Could not submit Django form with <a> element
I'm trying to make Django submit a form with <a> element, but have GET metod instead POST <form id="add-employee-form" action="add/" method="POST"> <table> <tr> <th class="table-title" id="second-name"> Фамилия </th> <th class="table-title" id="first-name"> Имя </th> <th class="table-title" id="patronymic"> Отчество </th> <th class="table-title" id="birth-date"> Дата рождения </th> </tr> <tr> <th id="second-name"> <div class="field-wrapper"> {{ form.second_name.errors }} {{ form.second_name }} </div> </th> <th id="first-name"> <div class="field-wrapper"> {{ form.first_name.errors }} {{ form.first_name }} </div> </th> <th id="patronymic"> <div class="field-wrapper"> {{ form.patronymic.errors }} {{ form.patronymic }} </div> </th> <th id="birth-date"> <div class="field-wrapper" id="birth-date-wrapper"> {{ form.birth_date.errors }} {{ form.birth_date }} </div> </th> </tr> </table> {% csrf_token %} <div class="button_bar"> <a class="a-button positive" href="{% url 'add-employee-action' %}">Добавить</a> <a class="a-button" href="{% url 'employee' %}">Сотрудники</a> <a class="a-button" href="{% url 'index' %}">На главуную</a> </div> </form> urls.py path('employee/add_employee/add/', views.add_employee_action, name='add-employee-action'), views.py def add_employee_action(request): if request.method == "POST": form = AddEmployeeForm(request.POST) if form.is_valid(): form.save() else: form = AddEmployeeForm() context = { 'form': form, } return render(request, 'add_employee.html', context) How to submit the form using <a> element? -
How to get all user record after me from auth_user table order by date_joined in django
I'm new with django, I just want to get all user record after a specific username from auth_user table order by date_joined. Please guide or reply to your valuable response. Thanks for all! -
Django Model MultipleObjectsReturned
I am using django ORM to talk to a SQL Server DB. I used the .raw() method to run a query: @classmethod def execute_native_queries(cls, query): return cls.objects.raw(query) I later type-cast it into a list by running: data = list(modelName.execute_native_queries(query)) While iterating through the list, i would call certain columns as such: for entry in data: a = entry.colA b = entry.colB c = entry.colC For certain entries, I am able to run one loop-iteration fine, however for some i get the following error: api.models.modelName.MultipleObjectsReturned: get() returned more than one modelName-- it returned 2! What i do not get is how come this error is surfacing? -
Django not finding static js scripts in the correct folder
I've already run collectstatic and created the static directory in my urls.py, and all other static files work fine (bootstrap, the custom CSS) and other scripts in the same directory work perfectly fine. This is the error code in the console. Failed to load resource: the server responded with a status of 404 (Not Found) ... jquery.formset.js:1 (http://localhost:8000/static/js/django-dynamic-formset/jquery.formset.js) (index):86 Uncaught TypeError: $(...).formset is not a function at (index):86 This is the script section from the rendered html For the second error, I've run into a similar problem before. Moving the jQuery CDN tags above the script itself solved the issue then, but it's not working now. This is my root urls.py urlpatterns = [ path('admin/', admin.site.urls), path('showroom/', include('showroom.urls')), path('', RedirectView.as_view(url='/showroom/', permanent=True)), # Redirect homepage to showroom path('accounts/', include('allauth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py # Static and media files STATIC_URL = '/static/' STATIC_ROOT = ( os.path.join(BASE_DIR, 'static') ) MEDIA_URL = '/media/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media') ) <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="/static/js/django-dynamic-formset/jquery.formset.js"></script> <script type="text/javascript"> $('.formset_row-image_set').formset({ addtext: 'add another', deleteText: 'remove', prefix: 'image_set', }); </script> </body> For context, this is an object creation form. The script allows dynamically created server-side formsets so users can upload individual images. … -
CSRF verification failed on submit after rendering the template via Ajax before
I have a large model formset with initial data, which is injected by ajax through a seperates rendered template. I also pass the csrf token to the template. In the inspector you can also see that the csrf hidden input looks exactly like the other forms on the same page. However, if I want to submit the form, I still get a csrf error. So the complete interface works and also the token is rendered into the template, only I can't submit the form and I don't know why I already tried to render the form without input and inject the inputs via Ajax, but the result was the same. views.py that is called by ajax POST request def render_revolver_table_form(request, product_id, production_step): context = {} context['csrfmiddlewaretoken'] = _get_new_csrf_token template = 'products/product_details/setup_revolver_table.html' SetupRevolverMapFormSet = modelformset_factory(SetupRevolverMap, exclude=( 'product', 'production_step', 'kanal', 'id'), form=SetupRevolverMapForm) setup_revolver_maps = SetupRevolverMap.objects.filter( product=product_id, production_step=production_step).all() context['formset'] = SetupRevolverMapFormSet( queryset=setup_revolver_maps.filter(kanal=1)) return render(request, template, context) injected template <table class="table"> <thead class="thead-dark"> <tr> <!-- Here is content from the formset --> </tr> </thead> <form id="setup_revolver_form_kanal_1" action="" method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value={{csrfmiddlewaretoken}}" /> {{ formset.management_form }} <tbody> <!-- Here is content from the formset --> </tbody> </form> </table> ajax.js csrftoken = $('input[name="csrfmiddlewaretoken"]').val() $.ajax({ url: … -
how to call an url in django view function
I am trying to execute one of the url of urls.py with urllib in djnago view function. After execution i got error like 'url': request.get_host() + new_path, [Thu Oct 17 11:19:27.634475 2019] [wsgi:error] [pid 5120] [remote 202.88.246.2:46648] RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to app.dev-mintaka.aavso.org/member/change_password/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Is this possible to execute url with urllib inside django view function. @login_required(login_url='http://domain/user/login?destination=apps/member/change_password') def change_password(request): '''Form for user to change their password''' form = SetPasswordForm(user=request.user, data=request.POST or None) if form.is_valid(): form.save() ob = urllib.request.urlopen(url='http://app.dev-mintaka.aavso.org/login/', data=request) messages.success(request, 'Your password has been succesfully updated!') return redirect('hq:profile') return render(request, 'registration/password_change_form.html', {'form': form}) when i execute urllib -
Getting forbidden You don't have permission to access / on this server
i'm trying to deploy django application using apache & mod_wsgi on centos 7. I have added the following lines in the httpd.conf file: Alias /robots.txt /home/centos/sunlife/static/robots.txt Alias /favicon.ico /home/centos/sunlife/static/favicon.ico #Alias /media/ /path/to/mysite.com/media/ Alias /static/ /home/centos/sunlife/static/ <Directory /home/centos/sunlife/static> Require all granted </Directory> #<Directory /path/to/mysite.com/media> #Require all granted #</Directory> WSGIScriptAlias / /home/centos/sunlife/sunlife/wsgi.py <Directory /home/centos/sunlife/sunlife> <Files wsgi.py> Require all granted </Files> </Directory> While trying to access the ip, I am getting Forbidden You don't have permission to access / on this server. -
JavaScript / Django - Displaying Prices on the JQuery date picker calendar
I have implemented a JQuery UI date picker on my "booking" website. I can choose from and to dates, and submit them and make a reservation for the apartment. What I would like to do next is to display prices for each individual day. I also need to be able to do "price-ranges", so one price from date 01-05, another price from 06-12, etc. I'm doing this in Django, as a task I was given, only the calendar is JS, which I don't have much experience with. In the Django backend there is a model where I store the "start_price_date and "end_price_date", aswell as the "price". When I query the backend in JS, this is what I get : 0: "3-10-2019" 1: "999" 2: "4-10-2019" 3: "999" 4: "5-10-2019" 5: "999" 6: "20-10-2019" 7: "666" 8: "21-10-2019" 8: "666" 10: "22-10-2019" 11: "666" So, I get back the dates, and the price for each date. I am having trouble implementing this in the JQuery calendar since I have little to no experience with JS/JQuery. I have tried googling, and went over a few stack overflow posts, tried a few functions but I honestly dont know what I'm doing, this is … -
Django exclude field from all queries
I am running Django on Heroku with zero-downtime feature. This means that during deployment there are two version of code running (old and new) on the same database. That's why we need to avoid any backward incompatible migrations. It there a possibility to exclude a field from Django query on a given model? Let say we have a model (version 1): class Person(models.Model): name = models.CharField() address = models.TextField() In some time in the future we want to move address to the separate table. We know that we should not delete a field for older code to work so Person model may look like (version 2): class Person(models.Model): name = models.CharField() address = models.ForeignKey(Address) _address = models.TextField(db_name='address') This way if old code will query for address it will get it from Person table even if database has been migrated (it will be an old value, but let assume thats not a big issue). How now I can safetly delete _address field? If we will deploy version 3 with _address field deleted then code for version 2 will still try to fetch _address on select, even if it's not used anywhere and will fail with "No such column" exception. Is there … -
Nested For Loop In JINJA for django
My problem is that When I run, Web Page Shows Blank Page, Is there any other way to access Nested For loop for this kind of problem.? This Is my Template. {% for j in N %} {% for k in j %} <h1>{{ k.Name }}</h1> {% endfor %} {% endfor %} and this is view.py post1 = [ { "Name":"Mustafa" } ] post2 = [ { "Name":"Abbas" } ] N = ["post1","post2"] def home_page(request): context = { "post1":post1, "post2":post2, "N":N } return render(request , 'app01/index.html',context) -
How to display sympy output in proper manner
I am very new to coding in Python and using the django. My question: is it possible to get the input-format of an output I get from previous calculations? For example, if I obtain an output is like x**2 how can I get x^2 automatically? https://i.imgur.com/Screenshot_2.png" -
Django unknown column error when trying to get a model objects
I'm trying to set up a web-app that modify an existing MySQL database using Dajngo, the model for my table below was generated via Django inspectdb: class BaseCase(models.Model): base_case_name = models.TextField(blank=True, null=True) version = models.TextField(blank=True, null=True) default = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'base_case' and here is an SQL of that base_case table in the database : CREATE TABLE `base_case` ( `base_case_name` tinytext, `version` tinytext, `default` bit(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; the problem is when I try to get the objects via Django ORM I keep getting this error django.db.utils.OperationalError: (1054, "Unknown column 'base_case.id' in 'field list'") -
SOLUTION to "programming error... relation ... does not exist" on Heroku Django
app is successfully deployed static index page works okay but pages that involve data do not work, giving "programming error ...relation ...does not exit" solution is: heroku run python manage.py migrate --run-syncdb -a appname redeploying didn't work delete all migration files locally, run makemigrations again locally, and push the generated migration files to git: didn't work - what works is this: heroku run python manage.py migrate --run-syncdb -a appname i learned it from here: Relation does not exist on Heroku hope it helps -
tabs link not working in the modal bootstrap with django
I am using django with bootstrap where i have a modal that includes tabs as links where each tab run a function and return the required data. The problem is that one of these tabs is not working... yet if i remove this tab and use it as a button the function works and return the correct values. Note the first 2 tabs run the same function where as the third one run another function. views.py def search(request): # search for person query = request.GET.get('search') print('query===>',query) try: if query != "": print("query is not empty!") try: c = cursor.execute('SELECT Person_.ID,Person_.Full_Name,Person_.Mothers_Name,Person_.Nickname_,Person_.Details,Person_.Address_,Person_.preferedActivity,Person_.Other_Activity,Person_.Other_Descriptive_Details,Person_.Status, Person_.Date_of_Birth,Person_.Place_of_Birth FROM Person_ WHERE Person_.ID LIKE ? or Person_.Full_Name LIKE ? or Person_.Mothers_Name like ? or Person_.Nickname_ LIKE ? or Person_.Details LIKE ? ORDER BY Person_.ID DESC',('%' + query + '%' ,'%' + query + '%', '%' + query + '%', '%' + query + '%', '%' + query + '%')) cc = c.fetchall() paginator = Paginator(cc,20) page_request_var = "page" print("page_request_var===>",page_request_var) page = request.GET.get(page_request_var) print("page====>",page) queryset = paginator.get_page(page) print("queryset=====>",queryset) return render(request,'pictureCard.html', {'c': cc,'countID':countID, 'countFullName': countFullName, 'countMother': countMother, 'countNickname':countNickname, 'countCritical':countCritical, "object_list":queryset, "page_request_var":page_request_var, }) else: print("Search value is empty") return redirect('../../') except pyodbc.DataError: print("DataError: Invalid value!") return redirect('../../') def getEvents(request,id): # search … -
How to serialize distinct queryset in django rest framework?
I have a model that handles Italian's VAT rates. There are three types of rate: 'Ordinaria', 'Ridotta', 'Minima' each type of rate can store multiple values according to a date. For example the current rate for ordinary VAT is 22% and has been set on the 1st oct 2013 but rates have changed during time and I need to store changes and to retrieve the three rates according to a specific date. The model to describe rates is called AliquoteIVA. I use a custom manager to retrieve the current rates as of today or by providing a specific date: class AliquoteIVAManager(models.Manager): def current(self, data): return self.filter(data__lte=data) \ .order_by('descrizione', '-data') \ .distinct('descrizione') class AliquoteIVA(models.Model): """ Modello delle aliquote IVA """ data = models.DateField( blank = False, ) descrizione = models.CharField( blank = False, max_length = 1, default = IVA.IVA_ORDINARIA, choices = IVA.IVA_TIPOLOGIA_CHOICES, ) aliquota = models.DecimalField( blank = False, null = False, default = '0', max_digits=19, decimal_places = 2, validators = [MinValueValidator(0.0)], ) objects = AliquoteIVAManager() def __str__(self): str_aliquota = "{0:.2f}".format(self.aliquota).replace('.', ',') return "IVA {descrizione} al {aliquota}% in vigore dal {data}".format( descrizione=self.get_descrizione_display(), aliquota=str_aliquota, data=self.data ) class Meta: ordering = ('-data', 'aliquota',) verbose_name = 'Aliquota IVA' verbose_name_plural = 'Aliquote IVA' I've tested … -
How can we setup Malayalam Language in Python Django?
I would like to create a Python Django website in "Malayalam". I think we can implement that using the Localisation method while enabling USE_I18N = True, USE_L10N = True in "settings.py". Is there any apps available for performing these?