Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
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?