Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple Parameters on Django Validator
I have problems with the parameters, when The validator is written used this way: cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias]) It automatically gets the value of the respective field in the validator.py def insumo_existencias(value): #Por alguna razon, me esta devolviendo un string insumo = models.Insumo.objects.get(id=1) if (insumo.cantidadexistencias < value): raise ValidationError( _('Error no hay existencias suficientes'), ) So, I just have to call it value and thats it, but I want to pass another parameter,but when the function has another parameter it does not longer get the value of the field. I tried this: cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias(cantidadusada,idinsumo)]) It is not working. Obviosuly the validator function was changed to acept to parameters -
Protect a GET and POST endpoint?
I'm trying to protect a GET and a POST endpoint on my backend. The user is not logged in, but I want to prevent ppl from accessing the API endpoint unless they're using my app. I'm using React and axios to make the request, with Django and Python accepting the request. I'm trying to use a CSRF decorator: class ClassView(View): @method_decorator(csrf_protect) def get(self, request): # Protected endpoint. @method_decorator(csrf_protect) def post(self, request): # Protected endpoint. This doesn't work because I can still go directly to the API endpoint and make requests. I've also tried @requires_csrf_token and @csrf_protect without success. -
Django - Sending Form Data View and Back to template
I'm trying to capture data from my form and send it to my view so I can do some business logic there. I have a "booking" website project, I want the user to pick start and end dates( i have a jquery date picker in my template), and on form submit send it to my view (and the db). My view then compares the dates to the prices stored in the database so it knows the price for each day, and on redirect after form submit, data is shown in the website. Hope that makes sense. Here is my view: def apartment_view(request, apartment_id): reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) unavailable = [] for start, end in apartment.reservations.values_list('start_date', 'end_date'): while start <= end: unavailable.append(start.strftime('%-d-%m-%Y')) start += datetime.timedelta(days=1) form = ReservationForm() if request.method == 'GET': form = ReservationForm() date = request.GET.get('reservation.start_date') print(date) elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): reservation = form.save(commit=False) reservation.apartment = apartment reservation.save() form.save() return HttpResponseRedirect(reverse('booking:apartment', kwargs={'apartment_id': apartment.pk})) context = {} context['form'] = form context['apartment'] = apartment context['unavailable_dates'] = json.dumps(unavailable) my form: class ReservationForm(forms.ModelForm): class Meta: model = Reservation fields = [ 'start_date', 'end_date', 'name', ] widgets = { 'start_date': TextInput(attrs={'id': 'datepicker'}), 'end_date': TextInput(attrs={'id': 'datepicker2'}), } … -
Django- how to merge this the StudentsEnrollmentRecord and ScheduleOfPayment in admin-site
\models class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Month_Name = models.ForeignKey(MonthName, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Day = models.CharField(max_length=500, blank=True, null=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) def __str__(self): suser = '{0.Education_Levels}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) \admin.py class InLinescheduleofpayment(admin.TabularInline): model = ScheduleOfPayment extra = 0 @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin): inlines = [InLinescheduleofpayment] list_display = ('Student_Users', 'School_Year','Courses','Section','Payment_Type','Education_Levels','Discount_Type','Remarks') ordering = ('Education_Levels',) list_filter = ('Student_Users',) I just want to merge the StudentsEnrollmentRecord and ScheduleOfPayment using the foreign key of ScheduleOfPayment(Education_Levels) and StudentsEnrollmentRecord(Education_Levels), but i dont know if i am doing it right.. can you guys help me with solutions? please -
run django multiple application on different ports
How to run multiple apps in different port in django? i am using gunicorn. i want to run the multiple applications on same domain. my Procfile: web: gunicorn DCMS_API.wsgi:application i have app1 and app2 in DCMS_API. How do i host the multiple applications on same domain name as i am new to django, i am facing issue while hosting the application. my django project is uploaded with different domain names apps name getting added in the domain name. -
How to place css and html files in single directory in django
I am working on a django web application where users login to the application and create web pages. Each page can have different themes, just like a wordpress themes. Problem: I am able to create themes(templates) and dynamically load them depending upon the user choice. My problem is all the css and html files of a single theme are not located in single folder. css files are in 'static' directory and html are in 'templates' directory. I want to segregate these files. I want to create a single directory called 'Themes' in which mutliptle directories will be there for each theme like 'theme A' and 'theme B'. In each theme directory again there will be 'css' and 'js' directories. How to implement thesevand load them? -
How to save an ImageField class object in a Django session?
I couldn't save an ImageField class object in a Django session. The type of object which I like to save in a session is below. <class 'django.db.models.fields.files.ImageFieldFile'> The reason I want to do this is that I want to save the data until the ultimate registration so that this posted image data will not disappear when transitioning from the form to the confirmation page. I tried below. views.py class ProductRegister(LoginRequiredMixin, CreateView): template_name = 'app/product_register.html' form_class = ProductRegisterForm def form_valid(self, form): ctx = {'form': form} temporary_product_object = form.save(commit=False) self.request.session['product_image'] = temporary_product_object.product_image but error occurred. error message TypeError at /app/product_register/35 Object of type ImageFieldFile is not JSON serializable Here is models.py for reference. models.py product_image = models.ImageField( upload_to='images/', blank=True, null=True, ) Any feedback is greatly appreciated. Thank you in advance. -
Pagination Django Rest Framework POST
I'm trying to send a POST request through an endpoint with generic APIVIEW class. The response rendered through this post request needs to be paginated using the limit and offset which again need to be passed in the same POST request body. How can same be implemented using the LimitOffsetPagination. I have seen seen various examples of pagination in GET requests but no luck on POST request. -
TypeError: 'ForeignKey' object is not callable
class ContactInfo(models.Model): TYPES_CHOICES = ( ('Phone', ('telephone')), ('whatsapp', ('whatsapp')), ('OTHER', ('Other')) ) type = models.CharField(_('Type'), max_length=20, choices=TYPES_CHOICES) number = models.CharField(max_length=10) def __str__(self): return self.type class Address(models.Model): TYPES_CHOICES = ( ('HOME', ('Home')), ('WORK', ('Work')), ('OTHER', ('Other')) ) type = models.CharField(_('Type'), max_length=20, choices=TYPES_CHOICES) departement = models.CharField(_('Departement'), max_length=50, blank=True) corporation = models.CharField(_('Corporation'), max_length=100, blank=True) building = models.CharField(_('Building'), max_length=20, blank=True) floor = models.CharField(_('Floor'), max_length=20, blank=True) door = models.CharField(_('Door'), max_length=20, blank=True) number = models.CharField(_('Number'), max_length=30, blank=True) street_line1 = models.CharField(_('Address 1'), max_length=100, blank=True) street_line2 = models.CharField(_('Address 2'), max_length=100, blank=True) zipcode = models.CharField(_('ZIP code'), max_length=5, blank=True) city = models.CharField(_('City'), max_length=100, blank=True) state = models.CharField(_('State'), max_length=100, blank=True) country = models.CharField(_('Country'), max_length=100, blank=True) contact = models.ForeignKey(ContactInfo, on_delete=models.CASCADE, null=True, related_name='contact_info') def __str__(self): return self.zipcode Im trying to run makemigrations, but im getting this error TypeError: 'ForeignKey' object is not callable, i dont know why even thougth i been using django for a while now, but maybe im missing something, any idea what im doign wrong? -
Django - use value from GET
I am newbie in Django and I try to understand better doing what should be very easy and simple... but unfortunetly I did not manage for example I want to get a value from a GET request I have a simple view (bellow) I type the url 127.0.0.1:8000/ecrf/index/?name='Slater' in my browser I can see using my terminal that i get the value 'Slater' from request.GET['name'] but it is not display (I only see 'Hello') views.py def IndexView(request): userconnected = request.GET['name'] print('GET',request.GET['name']) return HttpResponse('Hello', userconnected) urls.py urlpatterns = [ path('index/', views.IndexView), ] -
Sentry DjangoIntegration event_level
I'm using Sentry with Django like this: sentry_integration = DjangoIntegration() sentry_sdk.init( dsn="https://xxx@sentry.io/xxx", integrations=[sentry_integration] ) and with these settings for logging: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'django.log'), }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'django.template': { 'handlers': ['file', 'console'], 'level': 'INFO', }, 'app': { 'handlers': ['file', 'console'], 'level': 'DEBUG', } }, } If I instiantiate and call a logger in my code, this gets sent to Sentry. import logging logger = logging.getLogger(__name__) logger.error("error!") However, now I'd like to also log .warning calls. The documentation says to do this: sentry_logging = LoggingIntegration(event_level=logging.WARNING) sentry_sdk.init( dsn="https://xxx@sentry.io/xxx", integrations=[sentry_logging] ) But the LoggingIntegration is used rather than the DjangoIntegration. I've tried to use DjangoIntegration in the code above but I get this error: TypeError: init() got an unexpected keyword argument 'event_level' Is this possible? -
Unable to create Model without fields in Django rest framework
I am trying to create a model in Django rest framework, without any field information as I'm using MongoDB which doesn't have any fixed fields twitterdashmodel.py----- class TwitterMaster(models.Model): I need a way out so that I can use model to make query functionality from function based views. I am novice to Django rest framework. Need a guidance/solution to it -
"<StudentProfile: None None None>": "StudentsSubmittedDocument.Students_Enrollment_Records" must be a "StudentsEnrollmentRecord" instance
\views id = request.POST.get('ids') studentname = StudentProfile(id=id) myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) student = StudentsEnrollmentRecord.Student_Users V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = studentname, Document = myfile ) insert_doc.save() return render(request, 'Homepage/pending.html') \models class StudentProfile(models.Model): DoesNotExist = None objects = None Pending_Request = [ ('Pending_Request', 'Pending_Request'), ('Enrolled', 'Enrolled'), ] Image = models.ImageField(upload_to='images',null=True,blank=True) Username = models.CharField(max_length=500,null=True,blank=True) Password = models.CharField(max_length=500,null=True,blank=True) LRN = models.IntegerField(null=True,blank=True) Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files',null=True,blank=True) **how to fix this error? i tried so many times to fix this but i cant, i dont know how to fix this error, i just want to save the StudentsEnrollmentRecord(Student_Users) to StudentsSubmittedDocument(Students_Enrollment_Records) by the way this is my error. ValueError at /newEnroll/ Cannot assign "": "StudentsSubmittedDocument.Students_Enrollment_Records" must be a "StudentsEnrollmentRecord" instance.** -
Saving data to models in Django with ForeignKey relationship
When I am parsing a page I can't save category and topic to DB in Django. What should I do? class Category(models.Model): category = models.CharField(max_length=50) slug = models.CharField(max_length=60, unique=True) class Topic(models.Model): topic = models.CharField(max_length=50) slug = models.CharField(max_length=60, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) ... I wrote it, but it doesn't work. Most likely add() cannot be used with models.ForeignKey, right? If yes, how to do? from django.template.defaultfilters import slugify ... page = { 'datetime': datetime, 'title':title, 'slug':slug, 'short_text':short_text, 'text':text, 'image':image_name, 'img_source':img_source, 'page_source':page_source, } try: page = Page.objects.create(**page) except Exception as e: print(e, type(e)) category = {'category':category, 'slug':slugify(category)} category, created = Topic.objects.get_or_create(**category) page.category.add(category) topic = {'topic':topic, 'slug':slugify(topic)} topic, created = Topic.objects.get_or_create(**topic) page.topic.add(topic) -
Django and Bokeh: How do I add my graph to a Class Detail View?
I can't seem to figure out how to add my graph to a Class Detail View? Is it not possible to do so? I add it to the detailView, and call it in my template with: {{ div | safe }} But it does not show? I've gotten it to work perfectly fine in a view and template separately. Here's the whole detailview I'm trying to implement it into. DetailView class MedarbejderDetailView(FormMixin, DetailView): template_name = 'evalsys/medarbejder/detail.html' model = Medarbejder form_class = OpretEvalForm def evalgraph(self): colors = ["#40e862", "#ff9d26", "#ff1424"] over = 0 møder = 0 under = 0 none = 0 counts = [] items = ["Overstiger forventning", "Møder forventning", "Under forventning", "Ingen bedømmelse"] eval_vudering = Evaluering.objects.values("vuderingsnavn__vuderingsnavn") source = ColumnDataSource(data=dict(items=items, counts=counts)) for i in eval_vudering: if "Overstiger forventning" in i.values(): over += 1 elif "Møder forventning" in i.values(): møder += 1 elif "Under forventning" in i.values(): under += 1 elif None in i.values(): none += 1 counts.extend([over, møder, under, none]) plot = figure(x_range=items, plot_height=500, plot_width=500, title="Opsumering af evalueringer", toolbar_location=None, tools="pan, wheel_zoom, box_zoom, reset, tap", tooltips="@items: @counts") plot.title.text_font_size = "20pt" plot.vbar(x="items", top="counts", width=0.9, source=source, legend="items", line_color='black', fill_color=factor_cmap("items", palette=colors, factors=items)) plot.legend.label_text_font_size = "13pt" script, div = components(plot) return render(self, 'evalsys/medarbejder/detail.html', {'script': script, … -
How to install GDAL Library in Docker Python image?
I'm using python3.7-slim-buster docker image for my django project. Now I want to use Geo features of django. But it seems I have to install GDAL. So, I do RUN apt-get install gdal and it raises exception "E: Unable to locate package gdal-bin". Here is my docker file: FROM python:3.7-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # DB vars ENV DB_USER_NAME ${DB_USER_NAME} ENV DB_NAME ${DB_NAME} ENV DB_HOST ${DB_HOST} ENV DB_PORT ${DB_PORT} ENV DB_PASSWORD ${DB_PASSWORD} ENV DJANGO_SECRET_KEY ${DJANGO_SECRET_KEY} RUN apt-get install -y gdal-bin python-gdal python3-gdal RUN ["adduser", "${USER_NAME}", "--disabled-password", "--ingroup", "www-data", "--quiet"] USER ${USER_NAME} ADD ${PROJECT_NAME}/ /home/${USER_NAME}/${PROJECT_NAME} WORKDIR /home/${USER_NAME}/${PROJECT_NAME} ENV PATH="/home/${USER_NAME}/.local/bin:\${PATH}:/usr/local/python3/bin" RUN pip install --user -r requirements.txt CMD python manage.py runserver 0.0.0.0:9000 #CMD gunicorn ${PROJECT_NAME}.wsgi:application --bind 0.0.0.0:8000 EXPOSE 8000 -
Replacing links to images with images with JQuery
I am not quite experienced in JQuery but basically I am trying to build an blog ish website using django. Now I want to add images to the post and I am using this method which works fine in pure html but it doesen't seem to work with django: <html ><head></head> <body> <p>Some text with http://example.com/image.png and image and <span> nested http://example.com/second.png</span> image and an <img src="https://drop.ndtv.com/albums/AUTO/porsche-taycan-turbo/6401200x900_1_640x480.jpg"> img <span>foo</span> tag</p> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> jQuery(function () {jQuery('body').find('*').contents().filter(function() { return this.nodeType == 3; }).each(function(i, elem) { var matches = /(.*)(http:\/\/\S+(?:\.png|\.jpg|\.gif))(.*)/g.exec(elem.wholeText); if (matches) { var parent = elem.parentNode; var before = matches[1]; var replace = jQuery('<a />').attr('href', matches[2]).append(jQuery('<img />').attr('href', matches[2]))[0]; var after = matches[3]; parent.insertBefore(document.createTextNode(before), elem); parent.insertBefore(replace, elem); parent.insertBefore(document.createTextNode(after), elem); parent.removeChild(elem); } });}); </script> </body> </html> And this is my django template where I want to use it: {% extends "blog/base.html" %} {% block title %}{{ object.title }}{% endblock %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img " src="{{object.author.profile.image.url}}"><!--adding pfp beside blog posts--> <class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small> <small class="text-muted">{{ object.category }}</small> {% if object.author == user %} <div class="d-flex justify-content-end"> <div class="btn-group" role="group" aria-label="Basic example"> <a class="btn … -
Import .csv file to PostgreSQL and add an autoincrementing ID in the first column
i have downloaded a csv file for testing purposes and would like to upload all of the data to postgresql Database. However, i need to have an autoincrementing ID as the first column of the DB. Initially, i created the DB with SQL Query: CREATE TABLE pps3 ( id integer NOT NULL DEFAULT nextval('products_product_id_seq'::regclass), "brandname" character varying(25), "type1" integer, "type2" integer, "type3" integer, "Total" integer ) CSV data: "brandname","type1","type2","type3" "brand1","0","0","32" "brand1","0","12","0" I tried to move the data from the CSV with this code: import psycopg2 import datetime import csv import psycopg2 conn = psycopg2.connect("host=localhost dbname=my_django_db user=postgres") cur = conn.cursor() with open('PPS-Sep.csv', 'r') as f: reader = csv.reader(f) next(reader) # Skip the header row. for row in reader: cur.execute( "INSERT INTO pps3 VALUES (%s, %s, %s, %s)",row) conn.commit() This is working fine if I do not create the initial ID column. However, if I run it like that I get an error message that I am trying to insert the brandname to the ID. Any ideas on how to go around this? -
DJANGO createsuperuser not working...TypeError: create_superuser() missing 1 required positional argument: 'username'
I am trying to create a RESTful API using Django and DRF. I have a User model which extends AbstractUser. I'm neither able to create normal users nor a superuser. For some reason, It says "TypeError: create_superuser() missing 1 required positional argument: 'username'" Here's the models.py file: import uuid from django.db import models from django.conf import settings from django.dispatch import receiver from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible from django.db.models.signals import post_save from rest_framework.authtoken.models import Token from api.fileupload.models import File @python_2_unicode_compatible class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile_picture = models.ForeignKey(File, on_delete=models.DO_NOTHING, null=True, blank=True) email = models.EmailField('Email address', unique=True) name = models.CharField('Name', default='', max_length=255) phone_no = models.CharField('Phone Number', max_length=255, unique=True) company_name = models.CharField('Company Name', default='', max_length=255) address = models.CharField('Address', default='', max_length=255) address_coordinates = models.CharField('Address Coordinates', default='', max_length=255) country = models.CharField('Country', default='', max_length=255) pincode = models.CharField('Pincode', default='', max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) The serializers.py file: from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from .models import User from api.fileupload.serializers import FileSerializer class UserSerializer(serializers.ModelSerializer): profile_picture = FileSerializer() def create(self, validated_data): user = User.objects.create(**validated_data) return user def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.company_name = … -
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 …