Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting time field in django such that the stored time cannot be changed later
I have a orders model which looks like this: class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) date_ordered=models.DateTimeField(auto_now=True) complete=models.BooleanField(default=False,null=True,blank=False) and this is a specific view from my views.py: def handlerequest(request, id): order=Order.objects.get(id=id) items=order.orderitem_set.all() verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) PaytmHistory.objects.create(**response_dict) if verify: if response_dict['RESPCODE'] == '01': order.transaction_id=transaction_id order.complete=True order.save() print('order successful') Now what is happening is that whenever this is view is called the order is saved and the time updates to when the order was saved. But in future when I manually make some changes to the fields like when I update the shipping status of the order and save it then the time updates which I dont want . So is there any fix to this such that after order.complete=True order.save() The time cannot be changed -
Do I need to write the full media path in Django?
I am trying to download a file that is stored in the media folder and it seems as it only works when I am writing the full path as: file_location = '/home/user/user.pythonanywhere.com/media/' In the settings page on pythonanywhere, the 'media url' points to the same directory. So I don't really understand why I just can't write /media/ instead for the full path. Has it something to do with my settings.py file? I have these lines there: MEDIA_ROOT= os.path.join(BASE_DIR, 'media') MEDIA_URL="/media/" Do I need to have these lines at all? -
Django Rest Framework: Get Data by Field
i want to learn django. My first learning project is a django + rest framework api. i want to get a destination by its airport code. not by pk / id currently when i call /api/destination/1 i get the destination with id 1 i want something like /api/destination/PMI or /api/destination/mallorca and as response i only want to get the destination with code PMI or with name mallorca. is this possible? my files: modely.py class Destination(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=3) country = models.CharField(max_length=50) image = models.FileField() serializers.py class DestinationSerializer(serializers.ModelSerializer): class Meta: model = Destination fields = ("id", "name", "code", "country", "image") urls.py router = DefaultRouter() router.register(r'destination', DestinationViewSet) views.py class DestinationViewSet(viewsets.ModelViewSet): serializer_class = DestinationSerializer queryset = Destination.objects.all() -
How can I pass the text which I clicked on href link from one age to another page in JS and that should be usable in django code?
This is the code written in Django. When I click the link on the displayed results of links, the text,link of href (for example Redmi Note 5 rendered in {{post.0}} in the below code)should be saved and pass that text{{pass.0}} and link{{pass.1}} to another page to get the same text and it is used as the title. How can I do it? Page1.html {% for post in product_names %} <a href="{{ post.1 }}" onclick="savefunc({{post.1}},{{post.0}})">{{ post.0 }}</p> {% endfor %} Page2.html <h1 id="h1_title"style="text-align:center;background:linear-gradient(to right,rgb(166, 204, 255),rgb(15, 242, 216));margin-left:2%;margin-right:2%;box-shadow:1px 5px 5px 1px rgb(90,150,100,210);padding:30px;font-weight:bold;">[ Here I want to get that text from page1.html ]</h2> Suggestions in both JS or in Django is accepted. Please help me. -
Category not linking with posts Django
I want to let users choose the category that they want to put their post in, I already have the dropdown menu with all the options available but is not letting me post them, is telling me to insert a list of values, I have a feeling is has something to do with the databases because in my UserPost I dont have the category part. And this is my code: models.py class Categories(models.Model): name = models.CharField(max_length=100, verbose_name='Nombre') def __str__(self): return self.name User= settings.AUTH_USER_MODEL class UserPost(models.Model): user= models.ForeignKey(User, null=False, editable=False, verbose_name='Usuario', on_delete=models.CASCADE) title= models.CharField(max_length=500, null=False) content= models.TextField(null=False) categories = models.ManyToManyField('Categories', null=True, blank=True) public = models.BooleanField(verbose_name='Privada?',default=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name='Creado el ') updated_at = models.DateTimeField(auto_now=True, verbose_name='Actualizado el ') def __str__(self): return self.title + ' | ' + str(self.author) def save(self, *args, **kwargs): super(UserPost, self).save(*args, **kwargs) forms.py from django import forms from .models import UserPost, Categories #cats=[('coding','coding')] choices= Categories.objects.all().values_list('name','name') choice_list= [] for item in choices: choice_list.append(item) class UserPostForm(forms.ModelForm): class Meta: model= UserPost fields= ["title", "content","categories","public"] widgets={ 'categories':forms.Select(choices=choice_list) } views.py #list view @login_required(login_url='login') def userposts_list_view(request): allposts= UserPost.objects.all() context= {'allposts': allposts, } return render(request, 'posts/userposts-list-view.html', context) #detail view @login_required(login_url='login') def userposts_detail_view(request, id=None): post= get_object_or_404(UserPost, id=id) context= {'post': post, } return render(request, 'posts/userposts-detail-view.html', context) #all post … -
TypeError: method() takes 1 positional argument but 2 were given if i did register api
cant do work my register_api if i have view class RegistrationUsersApi(viewsets.ModelViewSet): permission_classes = [AllowAny] def get(self, request): queryset = User.objects.all() serializer = UserSerializerView(queryset, many=True) return Response(serializer.data) def post(self, request): serializer_class = SerializerUserRegistration(data=request.data) data={} if serializer_class.is_valid(): new_user = serializer_class.save() data['response'] = 'Ура ты создал нового персонажа, героя, человека, или не создал?' data['email'] = new_user.email data['username'] = new_user.username else: serializer_class.errors return Response(data) and i have my serilizer class SerializerUserRegistration(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['username', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True} } def save(self): user = User( email=self.validated_data['email'], username=self.validated_data['username'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password must match'}) user.set_password(password) user.save() return user and my usermodel class User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") description = models.TextField(blank=True, null=True) location = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) is_organizer = models.BooleanField(default=False) info_car = models.CharField(max_length=30, blank=True, null=True) first_name = models.CharField(max_length=30, blank=True, null=True) second_name = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.user.username urls urlpatterns = [ path('', views.MainIndexView.as_view(), name='index'), path('registration/', views.RegistrationUsersApi, name='registration') and my root urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path("api/accounts/", include("mainapp.urls")), ] why my register doesnt work. i was … -
Django prefetch_related not printing anything in Template
I have three models: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=130, unique=True) full_name = models.CharField(_('full name'), max_length=130, blank=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_active = models.BooleanField(_('is_active'), default=True) date_joined = models.DateField(_("date_joined"), default=date.today) phone_number_verified = models.BooleanField(default=False) change_pw = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) country_code = models.IntegerField(default='+91') two_factor_auth = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['full_name', 'phone_number', 'country_code'] class Meta: ordering = ('username',) verbose_name = _('user') verbose_name_plural = _('users') def get_short_name(self): """ Returns the display name. If full name is present then return full name as display name else return username. """ if self.full_name != '': return self.full_name else: return self.username class student_group(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) schoolCode = models.ForeignKey(school, on_delete=models.CASCADE) classVal = models.ForeignKey(studentclass, on_delete=models.CASCADE) SECTION_CHOICES = ( ("A", 'Section -A'),("B", 'Section -B'),("C", 'Section -C'),("D", 'Section -D'),) class_section = models.CharField(max_length=2,choices=SECTION_CHOICES,default="A") class studentclass(models.Model): class_id= models.CharField(primary_key=True,max_length=5) classVal =models.CharField(max_length=255, null=True, blank=True) views.py def addStudent(request): student = User.objects.filter(user_type=1) addStudentlink = True schoolval = user_school.objects.filter(username=request.user.id).values_list('schoolCode',flat=True)[0] studentclasses = studentclass.objects.all().prefetch_related('student_group_set__username') print(studentclasses) return render(request, 'dashboard/add-student.html', {'studentclasses': 'studentclasses'}) The print(studentclasses) returns <QuerySet [<studentclass: Class V>, <studentclass: Class VI>, <studentclass: Class VIII>, <studentclass: Class IX>, <studentclass: Class XII>, <studentclass: Class X>, <studentclass: Class XI>, <studentclass: Class VII>]> How should I print this in my template. How should I access my fields. I … -
i am getting error while while "zappa init'
i have installed zappa in virtual envirment and created aws account also but when i am try to command "zappa init" its showing error below (.env) D:\rough work\crud>zappa init Traceback (most recent call last): File "c:\users\dwipal shrirao\appdata\local\programs\python\python38\Lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\dwipal shrirao\appdata\local\programs\python\python38\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\rough work\crud\.env\Scripts\zappa.exe\__main__.py", line 4, in <module> File "d:\rough work\crud\.env\lib\site-packages\zappa\cli.py", line 44, in <module> from .core import Zappa, logger, API_GATEWAY_REGIONS File "d:\rough work\crud\.env\lib\site-packages\zappa\core.py", line 33, in <module> import troposphere File "d:\rough work\crud\.env\lib\site-packages\troposphere\__init__.py", line 586, in <module> class Template(object): File "d:\rough work\crud\.env\lib\site-packages\troposphere\__init__.py", line 588, in Template 'AWSTemplateFormatVersion': (basestring, False), NameError: name 'basestring' is not defined -
The view didn't return an HttpResponse object. It returned None instead by using numpy-stl
I have a Django web application and I'm trying to make an ajax call for uploading 3D images such as .stl, .stp, etc for getting their volume info with pythonocc-core package. When the file size is less than 1 MB, I run it with a normal ajax request, when it is large, I run it as a background-task so that the process avoid timeout. my ajax request; var data = new FormData(); var img = $('#id_Volume')[0].files[0]; var img_size = (img.size / 1048576).toFixed(2); data.append('img', img); data.append('csrfmiddlewaretoken', '{{ csrf_token }}'); if (img_size <= 1){ $.ajax({ method: 'POST', url: '{% url 'data:smallUpload' %}', type: 'POST', contentType: false, processData: false, data: data, }).done(function(data) { $("#id_rectangleRemovedVolume").val(data['removed_volume']); $("#id_rectangleVolume").val(data['volume']); loader.style.display = 'none'; $("#id_Volume").val(''); }).fail(function(xhr, text, error) { console.log(text, error) }); } else { $.ajax({ method: 'POST', url: '{% url 'data:upload' %}', type: 'POST', contentType: false, processData: false, data: data, }).done(function(data) { window.location.href = "{% url 'data:uploadStatus' %}"; }).fail(function(xhr, text, error) { console.log(text, error) }); } my smallUpload view; def uploadSmallFile(request): if request.POST or None: file = request.FILES.get('img') filename = file.name key = 'media/' + filename s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket('bucket') bucket.put_object(Key=key, Body=file) if filename != '': volume, removed_volume = Methods.get_volume_info(key) #do something context = {'volume': volume, … -
Pillow does not install in docker container
I have a Django app that uses Pillow. I get ERRORS: accounts.UserProfile.avatar: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". SystemCheckError: System check identified some issues: when I deploy it to aws-ec2 in a docker container. Things I've tried I have installed Pillow normally in virtual environment and frozen it to requirements.txt I downgraded and upgraded the version of Pillow I copied the dependencies from here into my Dockerfile. Following this issue I added the ENV LDFLAGS=-L/usr/lib/x86_64-linux-gnu/ to my container None of these seem to fix issue. Here's a sample of my Dockerfile Dockerfile FROM python:3.6-slim # create the appropriate directories ENV APP_HOME=/paalup_web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME ENV PYTHONUNBUFFERED=1 # Add unstable repo to allow us to access latest GDAL builds # Existing binutils causes a dependency conflict, correct version will be installed when GDAL gets intalled RUN echo deb http://deb.debian.org/debian testing main contrib non-free >> /etc/apt/sources.list && \ apt-get update && \ apt-get remove -y binutils && \ apt-get autoremove -y # Install GDAL dependencies RUN apt-get install -y libgdal-dev g++ --no-install-recommends && \ pip install pipenv && … -
I cant use postgresql for my new django project even though I wrote as other stack overflow answer said
I try to make the web app using postgresql. I wrote the setting and checked stackoverflow. I wrote the setting below and still get errors when i try to run the server locally. How can i fix this issue? The message is "django.db.utils.OperationalError: fe_sendauth: no password supplied" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': "blog", "USER": os.environ.get("DB_USER"), } } -
Django Static URL loading but by adding double slashes "http://127.0.0.1:8000//static/"
I am developing a web application for the last 2 weeks. Everything was working fine. Today when I started the server to continue. The static files were not loaded and were giving a 404 error. Static Files were loading on this URL before the ERROR http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.2.1.min.js Now Static Files are loading by appending extra slash "/" after base URL. http://127.0.0.1:8000//static/assets/plugins/jquery/jquery-3.2.1.min.js Please Help! """ Django settings for phm project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$$ttyfq=l6%3x44ooo8pi6s=c))ef5zk__u%2ox6n8qwv*0@1s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'crispy_forms', 'debug_toolbar', #local apps 'phm', 'arrival_and_departure', ] 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', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] ROOT_URLCONF = 'phm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates/'], … -
Django Filter in View or HTML
I am working on a basic assignments project where the teachers can add assignments and the students can submit the answers. I have saved it with models Assignments and Submissions as shown in the code below. The thing I am trying to do is that I want to show different buttons with different links when a parent has submitted the assignments. To be exact I want to show "Add submission" if a parent has not submitted and "Update Submission" when he/she has submitted already to a particular assignment. The problem I am having is that when a parent submits to a certain assignment then other parents also see "Update Assignment" if I give some filtering on the querysets. How can this be handled? Is there something we can do in html or some other filtering in views.py? Or I have to change by style of doing this. Please your support will be a great help. My models: class Assignments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=500) description = models.TextField(blank=True, null=True) file = models.FileField(upload_to='assignments/', null=True, blank=True, verbose_name="File") date_posted = models.DateTimeField(default=timezone.now) deadline = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): super(Assignments, self).save(*args, **kwargs) class Meta: ordering = ['-date_posted'] def __str__(self): return (self.title … -
Changing the choices of the model in the serializer
please I need your help, I have choices in the model and make model Serializer from this model but need to modify on those choices as i use filterset in the Serializer so i need to add more options in the dropdown menu, here is the code. Serializer.py: class BlaListSerializer(serializers.ModelSerializer): STATUS_new1='new1' STATUS_new1='new2' STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_new1, _('New1')), (STATUS_new2, _('New2')), (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) status = serializers.ChoiceField(choices=STATUS_CHOICES) class Meta: model = Bla fields = ( "id", "title", "status", ) model.py: class Bla(ProjectBaseModel, AuditLogMixin): STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) title = models.CharField(max_length=200, blank=True, null=True, verbose_name=_('Title')) status = models.CharField(max_length=200, blank=False, null=True, choices=STATUS_CHOICES) view.py: class MyBla(ListAPIView): serializer_class = BlaListSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['status', ] my problem is that the status isn't updated with the new options in the DRF -
Django traceback errors
I am a beginner in python, pycharm and Linux, I want to open an existing Django project. But when I use "python manage.py runserver", I am getting a series of trace-back errors which I am attaching below. I have installed all the LAMP stack i.e., Linux OS, Apache2 Web server,MariaDB and MYSQLclient with latest versions and have also tried updating the versions in requirements.txt. However, I haven't installed PhpMyAdmin yet, for time basis I would want to just use terminal for viewing my data tables. Could you please explain me about the tracebacks and what can I do to run the program. It would be of great support if you can provide me with a solution. Thank you. Keep safe and kind regards, SD. Django_Pycharm_traceback_1 Django_Pycharm_traceback_2 -
Python urllib library giving an error in python 3+
I'm trying to create a shipment using the easyship API docs. I'm using python 3+ and I'm receiving this error " can't concat str to bytes ". I think this is probably because of the urllib library. How can I solve this error ? from urllib.request import Request, urlopen headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer xxxxxxxxxxxxxAPIKEYxxxxxxxxxx' } request = Request('https://api.easyship.com/shipment/v1/shipments', data=values, headers=headers) response_body = urlopen(request).read() print(response_body) -
Django How to save JSON data outside a view in a session and retrieve the saved data inside the view?
I have JSON data which I want to store uniquely for each user inside a session. The problem is, the module which generates the JSON data is async is outside the Django view because it is very resource demanding. I want the JSON data this separate module generates to be stored in a session so that the data is unique for each user. I have tried the following outside my view module: from django.contrib.sessions.backends.db import SessionStore s = SessionStore() s['json_data'] = json_var s.save() But when I try to read the saved session data back inside a view, it loads nothing e.g. it doesn't go inside if statement: if 'json_data' in request.session: json_var = request.session['json_data'] Is there an elegant way to do this? -
Django API returning a single object rather than my whole list when using Table.objects.filter(condition)
In my Django project I have two tables: User and Post, where each Post has a foreign key 'author' to a User. I want to display all the posts that belong to a single user, with the URL: .../users/<int:pk>/posts. I parse this into my view function with the header: def user_post_list(request, pk):, which to my knowledge gives my view function access to this int:pk variable. I define the posts I want to return using posts = Post.objects.filter(author=pk), which should give me a list of all the objects that have an 'author' attribute equal to int:pk. However, when I go to return these posts, rather than a list I get only one JSON object from the Post table with an 'id' attribute and 'author' attribute equal to int:pk Thanks -
how to submit the same forms in one page in django
i am struggling how to submit multiple the same forms in one page. i have 3 model classes: 1- Group_attribut 2- Attribute 3- Attribut_items i create this form : from django import forms from .models import Attribute, Attribute_Item class GroupAttrForm(forms.ModelForm): class Meta: model = Group_attribute fields = ('title', 'catId', 'slug', 'display_order',) class AttForm(forms.ModelForm): list = forms.ModelMultipleChoiceField( queryset=Attribute_Item.objects.all(), label='لیست ایتمها' ) class Meta: model = Attribute fields = ('title', 'type', 'slug', 'group_attributeId',) i want to use this form while creating Group_attribut - with on click save the group and its Attributes with their all Attribut_items- page is something like following link: http://uupload.ir/files/6vbl_attributes.jpg please help me -
how to pass data in dictionary in django
i want to pass the data from dictionary def add(request): if request.method == "POST": src=request.POST['src'] width=int(request.POST['width']) height=int(request.POST['height']) name=request.POST['name'] report_name ={'src':src, 'width':width, 'height':height, 'name':name} return render(request, 'report_one.html', {'report_name':report_name}) else: pass in above code if i pass whole dictionary report_name ={'src':src, 'width':width, 'height':height, 'name':name} in return like this ----- return render(request, 'report_one.html', {'src':src, 'width':width, 'height':height, 'name':name}) this will work and display the required page but if i pass report_name like this ---return render(request, 'report_one.html'{'report_name':report_name}) this will not work so my question is how to pass the dictionary from view to html templates in case of the data is taken by the other page -
error messages are not shown in django form
error messages are not working in Django templates. after add error code in html template it shows no error message in webapp when fields are empty and press on submit button. html5 error is "novalidate" in template. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django.contrib.auth.models import User from django.utils.translation import gettext,gettext_lazy as _ class SignUpForm(UserCreationForm): password1 = forms.CharField(label='Password',widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(label='Confirm Password(again)',widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username','first_name','last_name','email'] labels = {'username':'Username','first_name':'First Name','last_name':'Last Name','email':'Email'} widgets = {'username':forms.TextInput(attrs={'class':'form-control'}), 'first_name':forms.TextInput(attrs={'class':'form-control'}), 'last_name':forms.TextInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}),} class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus':True, 'class':'form-control'})) password = forms.CharField(label=_('password'),strip=False, widget=forms.PasswordInput(attrs={'autocomplete':'current-password','class':'form-control'})) signup.html {% extends 'blog/base.html' %} {% load static %} {% block content %} <div class="col-sm-10"> <h3 class="text-white my-5">Signup Page</h3> <form action="" class="post" novalidate> {% csrf_token %} {% for fm in form %} <div class="form-group"> {{fm.label_tag}} {{fm}} {{fm.errors | striptags}} </div> {% endfor %} <input type="submit" value='Submit' class='btn btn-primary'> {% if form.non_field_errors %} {% for error in form.non_field_errors %} <p> {{error}} </p> {% endfor %} {% endif %} </form> </div> {% endblock content %} -
Use fullCalendar header only
I am using fullCalendar for my django project. For some of my template files(HTML files), I want to use only the header of the calendar not the calendar container. Can I use only the header of fullCalendar? if so how can I subtract container of the fullCalendar? Can anyone suggest me a better way to build a calendar header only? -
Django REST file upload results in different file size than original
When using Django REST Framework to handle file uploads using the FileUploadParser and storing the file on disk, is it normal for the final stored file (on the Django side) to have a different file size than the original file? I'm a newbie to Django (and Python in general) - my second week doing Django. I have a Python 3 script on a server (Ubuntu) that periodically uploads zip files to the Django (3.1) server using the Django REST Framework, also on Ubuntu. Using Python 3.8 on both sides. In each upload event, the file is always a single zip file (which only contains .txt and/or .csv files). The file upload is simple and is stored on disk on the Django side. From the sending side, I have experimented with a simple Python 3 script and curl as well, with differing results - the transferred files are always bigger than the original, and different between curl and my Python script. I am able to unzip and inspect the contents without issue; the text and csv files are identical in all cases. Needless to say, when I do a simple sftp, bypassing Django, the file size is identical - this is … -
Django - relation "app_name_modelname" does not exist
I've deployed my application to DigitalOcean. Everything works fine except this situation. I've added new GeneralComplaintDocument model, made migration locally, pulled from Github last version of project on DigitalOcean's server, deleted all migration files, migrated again, but still getting this error: relation "documents_app_generalcomplaintdocument" does not exist LINE 1: INSERT INTO "documents_app_generalcomplaintdocument" P.S: everything works fine on local server. -
Exception Value: 'NoneType' object has no attribute 'add', Categories name dont show up Django
Im trying to let user create a post and select a category, but when it selects a category and I post it, it gives me the error: Exception Value: 'NoneType' object has no attribute 'add'. If i go to my database, whatever I type, it is save except the category_id which is null. This is my code views.py: @login_required(login_url='login') def userposts_create_view(request): form= UserPostForm(request.POST or None) if form.is_valid(): data = form.cleaned_data categories = data.pop('categories', None) user_post = UserPost.objects.create(**data, user=request.user) if categories: user_post.categories.add(*categories) return HttpResponseRedirect("/posted/") context= {'form': form} return render(request, 'posts/userposts-create-view.html', context) #list view @login_required(login_url='login') def userposts_list_view(request): allposts= UserPost.objects.all() context= {'allposts': allposts, } return render(request, 'posts/userposts-list-view.html', context) #detail view @login_required(login_url='login') def userposts_detail_view(request, id=None): post= get_object_or_404(UserPost, id=id) context= {'post': post, } return render(request, 'posts/userposts-detail-view.html', context) I assume the error must be in the models but not sure... Models.py class Categories(models.Model): name = models.CharField(max_length=100, verbose_name='Nombre') User= settings.AUTH_USER_MODEL class UserPost(models.Model): user= models.ForeignKey(User, null=False, editable=False, verbose_name='Usuario', on_delete=models.CASCADE) title= models.CharField(max_length=500, null=False) content= models.TextField(null=False) categories = models.ForeignKey('Categories', null=True, blank=True, on_delete=models.CASCADE) public = models.BooleanField(verbose_name='Privada?',default=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name='Creado el ') updated_at = models.DateTimeField(auto_now=True, verbose_name='Actualizado el ') def save(self, *args, **kwargs): super(UserPost, self).save(*args, **kwargs) Forms.py from django import forms from .models import UserPost class UserPostForm(forms.ModelForm): class Meta: model= UserPost fields= …