Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my Django object deleted with no reason?
I know this question may not be in appropriate shape, but I have no other way to describe it. I have a Django project, deployed with Heroku. I'm using Postgres add-on. The problem is, few of the objects that my users created is being deleted for some reason. I tried to see if there's a pattern with this issue, but I haven't found one. It happens randomly. (This usually happens when I share(copy+paste) a user's post to other people, but I'm not sure if it's a pattern.) I know it's not the heroku ephemeral filesystem issue, because I'm using the Postgres add-on. So I started wondering if there could be something wrong with Heroku or the Postgres add-on itself. This is a quite serious issue, but I can't figure out what the problem is. Has anyone experienced similar issue or knows the answer to this? Thank you very much. -
Django Unique Constraint Failures
I am trying to create a meal planner with react and django. I am having issues with the form and getting it to the backend. Right now I can submit the form from react and I get the data back to django correctly. Unless I need to add another mealItem for the same date and serviceType ('lunch', 'dinner'). I get the unique constraint error for the following fields: "meals_meal.menu_id, meals_meal.date, meals_meal.type, meals_meal.url". My options are to either re do the form on the frontend or change the way I deal with the data on the back end. For the front end I have a button that adds a form. Depending on the button clicked, the date, serviceType is selected to send to the backend. The form has an text input for item name, a type ('entre','side','other'), and diet type ('vegetarian', gluten_free, diary_free) Any help figuring this out would be awesome thank you. I should add most of the model was set up by my brother in law, but due to knew family member. He doesn't have much time to help me. Models.py class Menu(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name='menus') created_at = models.DateTimeField( auto_now_add=True, editable=False, ) updated_at = models.DateTimeField( … -
Getting postgres connected in docker-compose
So I have a successfully built image where I have postgres mounted as a volume, however I keep getting django.db.utils.OperationalError: could not connect to server: Connection refused- when I ran docker-compose up. My Dockerfile and docker-compose.yml looks like this: # syntax=docker/dockerfile:1 FROM python:3.10-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /track COPY requirements.txt . RUN apt-get update \ && apt-get -y install libpq-dev gcc \ && pip install --upgrade pip \ && pip install --default-timeout=100 -r requirements.txt COPY . . ENV DJANGO_SETTINGS_MODULE track.settings EXPOSE 8000 version: "3.9" services: django: build: . command: python manage.py runserver 0.0.0.0:8000 stdin_open: true tty: true volumes: - .:/track ports: - "8000:8000" depends_on: - db db: image: postgres:9.6.10-alpine restart: always user: postgres volumes: - track_db:/var/lib/postgresql/data environment: POSTGRES_USER: postgres POSTGRES_PASS: postgres POSTGRES_DB: postgres volumes: track_db: {} Please, what am I doing wrong? -
userserializer asking for groups and user permissions
I am trying to create employees under a company like the following but the Userserializer is throwing errors for groups and user_permissions Models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=500, default=0) email = models.EmailField(max_length=500, default=0) phone = models.CharField(max_length=500, default=0) city = models.CharField(max_length=500, default=0) role = models.CharField(max_length=100, default='View') #View/CRUD created = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) groups = models.ManyToManyField(Group, blank=True) Views.py class EmployeeCreateAPIView(CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.AllowAny,) def post(self, request, format=None, **kwargs): data = {} for key in request.data: data[key] = request.data[key] print("data", data) serializer = UserSerializer(data=data) print("pre serializer ", serializer) ##### this if serializer.is_valid(): print("s data", serializer.data) Employee.objects.create(user_id=serializer.data["id"], company=Company.objects.get(pk=data['company']), name = serializer.data['first_name'] + ' ' + serializer.data['last_name'], email=serializer.data['email'], ) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Where pre seriliazer print statement shows the following: UserSerializer(data={'first_name': 'Ejaz', 'last_name': 'Khan', 'username': 'ash', 'email': 'ekhan5347@gmail.com', 'password': '9', 'confirm': '9', 'company': 5}): id = IntegerField(label='ID', read_only=True) password = CharField(write_only=True) last_login = DateTimeField(allow_null=True, required=False) is_superuser = BooleanField(help_text='Designates that this user has all permissions without explicitly assigning them.', label='Superuser status', required=False) username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <Unique Validator(queryset=User.objects.all())>]) first_name = CharField(allow_blank=True, max_length=30, required=False) last_name = … -
How can I resolve i18n patterns error in settings.urls?
I'm trying to add language support to my app using django-model translation. But I am getting the following error in working urls located in root directory. how can i solve this from django.contrib import admin from django.urls import path, include from django.utils.translation import gettext_lazy as _ from django.conf.urls.i18n import i18n_patterns from New import views as new_views from Home import views as home_views urlpatterns = [ path('admin/', admin.site.urls), path("i18n/", include("django.conf.urls.i18n")), ] home_patterns =([path('', home_views.Index, name="index"), path(_('sistem-cozumumuz/'), home_views.Solution, name='solution'), path(_('teklif-isteyin/'), home_views.OfferRequests, name="offer-request"), path(_('gizlilik-politikasi/'), home_views.PrivacyPolicy, name='policy'), path(_('iletisim/'), home_views.Contact, name='contact'), ]) news_patterns =([path('', new_views.Index, name="index"), path(_('referanslar/'), new_views.References, name="reference"), path(_('yorumlar/'), new_views.Comments, name="event"), path(_('basinda-biz/'),new_views.News,name="new"), path(_('dokumanlar/'), new_views.Downloads, name="download"), path(_('<slug:slug>/'),new_views.NewDetails,name="new-detail"), path(_('yorumlar/<slug:slug>/'),new_views.CommentDetails,name="comment-detail"), path(_('referanslar/<slug:slug>/'),new_views.ReferenceDetails,name="reference-detail"), ]) urlpatterns += i18n_patterns( path('', include(home_patterns, namespace= 'Home'), path(_('haberler/'), include(news_patterns, namespace ='New')), )) Error Message: *** File "/home/ubuntu/Desktop/Makine_Sitesi/XMachine/urls.py", line 48, in path('', include(home_patterns, namespace= 'Home'), File "/home/ubuntu/.local/lib/python3.8/site-packages/django/urls/conf.py", line 38, in include raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.*** -
Show appointments not included in range
I want to show dates that appointments are not booked in a template. For this reason i have so far: # Collect only the dates so that i can find what is not in that range. example_dates = Appointment.objects.values_list('start_appointment', flat=True) # Initialize start and end date start_date = datetime.date.today() end_date = start_date + datetime.timedelta(days=5) # Initialize new list that will include records does not exists not_found_dates = [] # Loop through in date range and if date does not exists # Create a dict and add it to the list for n in range(int((end_date - start_date).days)): new_date = start_date + datetime.timedelta(days=n) if new_date not in not_found_dates: not_found_dates.append(new_date) print(new_date) # Get original queryset examples = Appointment.objects.filter(start_appointment__range=(start_date, end_date)).values('start_appointment') print(examples) # Convert it to a list examples = list(examples) return render(request, 'appointments/add-appointment.html', {'examples': examples, 'not_found_dates': not_found_dates}) When i print the new_date from the loop i got: 2021-11-22 2021-11-23 2021-11-24 2021-11-25 2021-11-26 And the query from examples returns that i have 3 appointments in db in that range (2)on 2021-11-23 and (1) on 2021-11-22. Is it possible to show the dates that appointments not booked i.e 2021-11-24, 2021-11-25, 2021-11-26. -
Unable to install Pillow for Django App using Terminal on Namecheap Shared hosting
I was going to deploy my Django App on Namecheap shared hosting. My app needs Pillow to be able to run perfectly. But while installing pillow using pip install Pillow in Namecheap's Terminal, I get the error. I installed Django and other libraries successfully. But while installing Pillow, it gives me this error. Collecting Pillow==8.4.0 Using cached Pillow-8.4.0.tar.gz (49.4 MB) Preparing metadata (setup.py) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/abduxdcv/virtualenv/iffi-store-app/3.8/bin/python3.8_bin -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-u2_5lsia/pillow_aabaeed7df664fd985a82d84f11f5eac/setup.py'"'"'; __file__='"'"'/tmp/pip-install-u2_5lsia/pillow_aabaeed7df664fd985a82d84f11f5eac/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-vyxwq5up cwd: /tmp/pip-install-u2_5lsia/pillow_aabaeed7df664fd985a82d84f11f5eac/ Complete output (143 lines): /opt/alt/python38/lib64/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) /opt/alt/python38/lib64/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'project_urls' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/PIL copying src/PIL/ImtImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/BmpImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL running egg_info writing src/Pillow.egg-info/PKG-INFO writing dependency_links to src/Pillow.egg-info/dependency_links.txt writing top-level names to src/Pillow.egg-info/top_level.txt reading manifest file 'src/Pillow.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.c' warning: no files found matching '*.h' warning: no files found matching '*.sh' warning: … -
Django-decouple and django-dotenv not pulling variables out of .env file
I apologize in advance if my question is too wide open but I am trying to hide my private passwords of my settings.py file. I created a .env file and and tried using django-dotenv and Django-decouple to access those variables. It works for a 'TEST' variable I write in there but for my 'EMAIL_PASS' and other variables which I have already set in there it pulls the old 'EMAIL_PASS' not the one set in the .env in my Django directory. I probably set the env variables incorrectly (as in not in a virtual environment) last time on a previous project but this time around I am in a local env. I tried doing os.environ.clear() and .pop('EMAIL_PASS') commands. This works while in the CLI but the data comes back somehow. For now I will just change 'EMAIL_PASS' to 'EMAIL_PASSWORD' but I have to figure out why I can't remove the old 'EMAIL_PASS'. I know this is kind of vague but I am hoping someone can see this and pinpoint the source of my confusion. Thanks very much, Darryl -
How to run a rabbitMQ task asynchronously in django rest framework
I have written two python scripts, separate from my django project, to put messages in a rabbitMQ queue, and to take from it. This is my producer script, that reads some sensor values from a file, and every second puts the value to the queue: import pika, csv, time url = 'secret_queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') with open('sensor.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter='\n') for row in reader: channel.basic_publish(exchange='', routing_key='hello', body=row[0]) print(row[0]) time.sleep(1) connection.close() And this is my consumer script: import pika from app.models import Measurement url = 'secret_queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): measurement = Measurement.objects.create(sensor=3, energy_consumption=float(str(body))) measurement.save() channel.basic_consume('hello', callback, auto_ack=True) channel.start_consuming() connection.close() Measurement is a model inside my django project. Like I said, these two files are not included in my project structure, but I have modified my consumer script in order to insert a new measuremet every time a value is read from the queue. I want to integrate the consumer script into my django project, so that it will create a new measurement every time there is something on the queue, and I want this script to run asynchronously, … -
Django - long running tasks
Im looking for and advice for long running tasks in Django. This is my use case: I have an eshop order with over 200 products (rows). When I click on "process" Django runs a function (which consists of multiple smaller functions) to process data. This may take some time but while this task is running, I want to let a user know about the process status. During that time the order is "locked". My current theory is to use combination of Django Celery (or its equivalent) and Django channels. Once the task is done, Channels will push a message via websocket to the frontend and JS will change objects (button, status, texts...). When task starts, a function updates the status in DB. After task is finished, status in DB is updated again. Because the app is not SPA and im using standard Django views and templates, this solution would not work in case the task will end during page refresh. So after the page is loaded again, task is not running, WS wont send any update but at the same time DB query has old status. Example: When process starts I save status as "running". When Celery task is finished, … -
Periodic and Non periodic tasks with Django + Telegram + Celery
I am building a project based on Django and one of my intentions is to have a telegram bot which is receiving information from a Telegram group. I was able to implement the bot to send messages in Telegram, no issues. In this moment I have a couple of Celery tasks which are running with Beat and also the Django web, which are decopled. All good here. I have seen that the python-telegram-bot is running a function in one of the examples (https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py) which is waiting idle to receive data from Telegram. Now, all my tasks in Celery are in this moment periodic and are called each 10 or 60 minutes by Beat. How can I run this non-periodic task with Celery in my configuration? I am saying non-periodic because I understood that it will wait for content until it is manually interrupted. Django~=3.2.6 celery~=5.1.2 CELERY_BEAT_SCHEDULE = { 'task_1': { 'task': 'apps.envc.tasks.Fetch1', 'schedule': 600.0, }, 'task_2': { 'task': 'apps.envc.tasks.Fetch2', 'schedule': crontab(minute='*/60'), }, 'task_3': { 'task': 'apps.envc.tasks.Analyze', 'schedule': 600, }, } In my tasks.py I have one of the tasks like this: @celery_app.task(name='apps.envc.tasks.TelegramBot') def TelegramBot(): status = start_bot() return status And as the start_bot implemenation, I simply copied the echobot.py example … -
Django NestedHyperlinkedModelSerializer not returning Foreign Key Field
Parent id or foreign key is not returning from child. I am trying drf-nested-routers example. models.py class Client(models.Model): name = models.CharField(max_length=255) class MailDrop(models.Model): title = models.CharField(max_length=255) client_id = models.ForeignKey(Client, on_delete=models.CASCADE) serializers.py class ClientSerializer(HyperlinkedModelSerializer): class Meta: model = Client fields = ['id', 'name'] class MailDropSerializer(NestedHyperlinkedModelSerializer): parent_lookup_kwargs = { 'client_pk': 'client_id', } class Meta: model = MailDrop fields = ['id', 'title'] views.py class ClientViewSet(viewsets.ViewSet): serializer_class = ClientSerializer def list(self, request): queryset = Client.objects.filter() serializer = ClientSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Client.objects.filter() client = get_object_or_404(queryset, pk=pk) serializer = ClientSerializer(client) return Response(serializer.data) class MailDropViewSet(viewsets.ViewSet): serializer_class = MailDropSerializer def list(self, request, client_pk=None): queryset = MailDrop.objects.filter(client_id=client_pk) serializer = MailDropSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None, client_pk=None): queryset = MailDrop.objects.filter(pk=pk, client_id=client_pk) maildrop = get_object_or_404(queryset, pk=pk) serializer = MailDropSerializer(maildrop) return Response(serializer.data) If I add fields = ['id', 'title', 'client_id'] in the MailDropSerializer, it throws the following error: AssertionError: `NestedHyperlinkedRelatedField` requires the request in the serializer context. Add `con text={'request': request}` when instantiating the serializer. If I add the request in the serializer context, the output is as follows: url: http://127.0.0.1:8000/clients/4/maildrops/ [ { "id": 3, "title": "Madison Mosley", "client_id": "http://127.0.0.1:8000/clients/4/" }, { "id": 4, "title": "Louis Chen", "client_id": "http://127.0.0.1:8000/clients/4/" } ] I added … -
Error migrating data with models from django-address app
I'm doing a data migration, and using django-address for geographical addresses. I am able to save an address, and everything else seems to work except when I try to assign an address to a building I get the error "Invalid address value." Migration file: from django.db import migrations def forward_data_migration(apps, schema_editor): Address = apps.get_model("address", "Address") Locality = apps.get_model("address", "Locality") Property = apps.get_model("myApp", "Property") db_alias = schema_editor.connection.alias Locality.objects.using(db_alias).bulk_create([ Locality(name="Foo",) ]) Address.objects.using(db_alias).bulk_create([ Address(raw="1 Fake street" locality=Locality.objects.get(name="Foo"), ), ]) Property.objects.using(db_alias).bulk_create([ Property(building_name="Test building", address=Address.objects.get(raw="1 Fake street") ), ]) Property model: class Property(UUIDTimeStampedModel): building_name = models.CharField(max_length=255) address = AddressField(null=True, blank=True) Address models: https://github.com/furious-luke/django-address/blob/master/address/models.py The Address app seems to have a function that checks whether the value being passed to it is a valid instance of "Address" but I don't know why this check fails. -
how to make ImageFiel json serializable - django
I'm trying to add image to my to posts , but when i try to add a new post it raise this error : TypeError: Object of type ImageFieldFile is not JSON serializable and here is my models.py class ModelCategory(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) category = models.ForeignKey(Category,on_delete=models.PROTECT) model = models.CharField(max_length=40) giga = models.ForeignKey(Giga,on_delete=models.PROTECT) image = models.ImageField(upload_to='images',blank=True,null=True) and here is my views.py and forms.py @login_required def create_modelcategory(request): form = ModelCategoryForm() if request.is_ajax() and request.method == 'POST': form = ModelCategoryForm(request.POST,request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() return JsonResponse({'success':True},status=200) else: return JsonResponse({'sucess':False,'error_msg':form.errors},status=400) context = { 'form':form } return render(request,'storage/modelcategory.html',context) class ModelCategoryForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all().order_by('-pk')) giga = forms.ModelChoiceField(queryset=Giga.objects.all().order_by('-pk')) class Meta: model = ModelCategory fields = ['category','model','giga','image'] i tried this solution but still i'm not sure how to use it json.dumps(str(my_imagefield)) $(document).ready(function () { const image = document.getElementById('id_image') const imgBox = document.getElementById('img-box') const category = document.getElementById('id_category') const model = document.getElementById('id_model') const giga = document.getElementById('id_giga') const min_qnt = document.getElementById('id_min_qnt') const csrf = document.getElementsByName('csrfmiddlewaretoken') image.addEventListener('change', ()=>{ const img_data = image.files[0] const url = URL.createObjectURL(img_data) console.log(url) imgBox.innerHTML = `<img src="${url}" width="100%">` }) const create_modelcategory_form = document.getElementById('create-modelcategory') create_modelcategory_form.addEventListener("submit",submitModelCategoryHandler); function submitModelCategoryHandler(e) { e.preventDefault(); const data = new FormData() data.append('csrfmiddlewaretoken',csrf[0].value) data.append('category',category.value) data.append('model',model.value) data.append('min_qnt',min_qnt.value) data.append('giga',giga.value) data.append('image',image.files[0]) $.ajax({ type: 'POST', url: … -
In a multi vendor Django Rest API, how do I restrict customers/buyers to only make order(s) from one vendor at a time?
Here are my simplified models This is my custom user model, email is used instead of a username class CustomUser(AbstractUser): id = models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True ) email = models.EmailField( _('email address'), unique=True, blank=False ) ... Product App This app is used by sellers to post their products class Product(TimeStampedModel): id = models.UUIDField( default=uuid_lib.uuid4, editable=False, primary_key=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, auto_created=True, related_name='products' ) title = models.CharField( _("Title"), max_length=200 ) category = models.ForeignKey( Category, on_delete=models.CASCADE ) ... Cart App contains two models cart and cart item model class Cart(TimeStampedModel): ... user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name="cart", on_delete=models.CASCADE ) ... class CartItem(TimeStampedModel): ... cart = models.ForeignKey( Cart, related_name="items", on_delete=models.CASCADE, null=True, blank=True ) product = models.ForeignKey( Product, related_name="cart_product", on_delete=models.CASCADE, ) seller = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="cart_seller", on_delete=models.CASCADE, null=True, blank=True ) ... class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ( 'email', ) class CartProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( ... 'user', ... ) class CartSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) items = serializers.StringRelatedField(many=True) class Meta: model = Cart fields = ( 'id', 'user', 'created', 'updated', 'items', ) class CartItemSerializer(serializers.ModelSerializer): product = serializers.StringRelatedField(read_only=True) cart = serializers.StringRelatedField(read_only=False) seller = serializers.StringRelatedField(read_only=False) class Meta: model = CartItem fields = ( 'id', 'cart', 'cart_id', 'product', 'product_id', … -
Compare Django-HTML form input with the elements in a list
I have a list of usernames and I want to compare the form input with the elements of the list. Suppose I have a list, say, listA = ["abc", "def", "ghi"] and the HTML form, <form action="#" class="signin-form"> <div class="form-group mb-3"> <label class="label" for="name">Username</label> <input type="text" class="form-control" placeholder="Username required> </div> <div class="form-group"> <button type="submit" class="form-control btn btn-primary submit">Sign In</button> </div> I want to compare the input from the elements in the list. -
I want to run my else statement in (views.py) but when server is run it automatically go to the if statement?
#views.py class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) if forms.is_valid: forms.save() print("If statement") return redirect(reverse('home')) else: print("else statement") return render(request,'file/addQuestion.html') def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) #forms.py from django.forms import ModelForm from .models import Question from django.core.exceptions import ValidationError class QuestionForm(ModelForm): class Meta: model = Question fields = "__all__" def clean_answer(self): answer = self.cleaned_data['answer'] option1 = self.cleaned_data['option1'] option2 = self.cleaned_data['option2'] option3 = self.cleaned_data['option3'] option4 = self.cleaned_data['option4'] if answer == option1 or answer == option2 or answer == option3 or answer == option4: return answer else: raise ValidationError("Select an answer from the options.") -
Why it doesn't show any data after I add it?
Wokring on a simple To Do application using Django 3.2. In the moment I'm working on one to one relationship which every specific user has his own data(which are the tasks to do in this case) I did that by create a field at models.py user = models.ForeignKey(User, on_delete=CASCADE, null=True) The problem is that when I add a task in the home template it doesn't show up. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE # Create your models here. class user_active(models.Model): content = models.CharField(max_length=200, null=True) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) user = models.ForeignKey(User, on_delete=CASCADE, null=True) def __str__(self): return self.content forms.py from django import forms from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import user_active class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] home.html <div> <form class="felx" action="add_content/" method="POST"> {% csrf_token %} <input class="form-control me-2" type="text" name="content" placeholder="Hey"> <button id="add-btn" class="button" type="submit">Add</button> </form> <table> <thead> {% for all_item in all_items %} <tr> <td>{{ all_item.content }}</td> </tr> {% endfor %} </thead> </table> <a href="{% url 'demo1:login' %}">Logout</a> {% if request.user.is_authenticated %} <p>Hello {{request.user}}</p> {% endif %} … -
Django order by count by date
Good morning! I have tried many things but can't get to order my post by likes and by date. For example, I wish to have a "popular post" page, which contains only posts from today, but order by most liked. Here are my models: Class Post(models.Model): name = models.CharField(max_length=40, default=None, null=False) cover = models.CharField(max_length=100, default=None, null=True, blank=True) content = models.TextField(max_length=2000, default=None, null=False) class VoteDate(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField(default=timezone.now) The closest I came but did not work is this line: hot_today = Post.objects.annotate(count=Count('votedate', filter=Q(votedate__date=datetime.today()))).order_by('count')[:30] Thank you for your help! -
Django social share fb link with 500 internal error header [closed]
I've installed django-social-share and added a social share button to fb. How can the text of the shared link be customized? Right not it is showing Server Error 500 although when you click on the link it actually works fine. I cant seem to find the answer to this problem in the library documentation. The goal is that in stead of "Server Error (500)" there would be the header of the page and a favicon like you'd normally see in shared pages In my template I have added this template tag for the social share {% post_to_facebook "Random text" %} -
Can I specify a custom default value to be used when migrating after adding a new parent class in a Django model?
I am writing a Django app that provides a very simple model called Submittable, which users of the app are supposed to inherit from when they want to use other functionalities of the app. # app1 class Submittable(models.Model): is_submitted = models.BooleanField(default=False) # other methods here # app2 class Paper(Submittable): # some fields However, when I add this as a parent to an already existing model in another app and run makemigrations, I am asked to provide a default value to the new field submittable_ptr_id. The problem is, that I want this field to simply point to a new instance of Submittable but I don't know how to do that. I know, that I could simply edit the migration file created like so: class Migration(migrations.Migration): dependencies = [ # some dependencies ] operations = [ migrations.AddField( model_name='Paper', name='submittable_ptr_id', # here I set default to a function from the Submittable app that just creates a new submittable field=models.OneToOneField(auto_created=True, default=app1.utils.create_submittable, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key =True, serialize=False, to='app1.Submittable'), preserve_default=False ), ] But I want to know if I can specify anything somewhere in app1 that makes this happen automatically? I don't want users of the app to have to make this change themselves and instead, … -
File read issue using python
I am trying to read file(text),used readlines() function but not getting in format like bold,headings,italics in the read file -
Read some products Data from a csv file using python in command line
i have a csv file which have information about all the products so i want to perform some basic functions like You have to show data based on user selection. User will select filters he wants to apply (he can select multiple fields). Also user can select the fields he wants to see like he can select full item or he wants to see only price of item or he wants to see some specific fields as am new to it so kindly help to learn. I have read python basics like its Datastructure , loops, file system Here is the sample Data -
TypeError: Object of type ImageFieldFile is not JSON serializable - django
I'm trying to make post via ajax request and JsonResponse but when i try to upload image to the form and submit it raise this error from server side : TypeError: Object of type ImageFieldFile is not JSON serializable and this error from client side (in the console browser) Uncaught TypeError: Illegal invocation and here is my models.py and my views.py @login_required def create_modelcategory(request): form = ModelCategoryForm() if request.is_ajax() and request.method == 'POST': form = ModelCategoryForm(request.POST,request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() data = { 'id':obj.id, 'admin':obj.admin.username, 'category':obj.category.category, 'model':obj.model, 'giga':obj.giga.giga_byte, 'img':obj.image.url, } return JsonResponse({'success':True,'data':data},status=200) else: return JsonResponse({'sucess':False,'error_msg':form.errors},status=400) context = { 'form':form } return render(request,'storage/modelcategory.html',context) and here is my html and jquery-ajax functions is there something i've missed to add ? or if its not right way to save image data into database via ajax and jsonresponse please let me know . I much appreciate your helps .. -
localization bootstrap-Table not displaying as wanted
Im using the following code: Based on the browser language i change up the locale Even if the browser fex is en-US its get defaulted to dutch <script src="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.js"></script> <script src="{% static 'js/bootstrap-table-nl-BE.js'%}"></script> <script src="{% static 'js/bootstrap-table-fr-BE.js'%}"></script> <script> $(document).ready(function() { var userLang = navigator.language || navigator.userLanguage; if (userLang == "fr" || userLang == "fr-FR" || userLang == "fr-BE") { language = "fr-BE" } else { language = "nl-BE" } $("#table").bootstrapTable({ locale : language, }) } ) </script> But even when the browser is in en-US it keeps displaying in French.