Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Redirecting after a XMLHttpRequest
I'm drawing on a canvas and then I upload the drawing to a database (Django). I have made this work by creating a Blob and sending a Form with XMLHttpRequest. But once uploaded, how do I navigate to the page that shows this new file? I would like the server to send a redirect, but that doesn't work and apparently that's not how you should do it. But how otherwise? Here's the Javascript: function submitFunction() { canvas = document.getElementById('myCanvas'); var dataURL = canvas.toDataURL("image/jpeg"); form = document.getElementById('myForm'); formData = new FormData(form); blob = dataURItoBlob(dataURL); url = window.location.href; xhr = new XMLHttpRequest(); xhr.open('POST', url, true); formData.set('artwork_img', blob, 'artwork.jpeg'); xhr.send(formData); } And here's the Django View: def create (request, id): artwork = get_object_or_404(Artwork, pk=id) context = {'artwork' : artwork} if request.method == 'POST': form = ArtworkForm2(request.POST, request.FILES) if form.is_valid(): newChild = Artwork() newChild.parent = artwork newChild.artwork_img = form.cleaned_data['artwork_img'] newChild.artwork_title = form.cleaned_data['artwork_title'] newChild.ancestors = artwork.ancestors+1 newChild.save() newChild.updateAncestors() # ---> this is kind of what I'd like to do: return redirect('showwork', newChild.id) else: print(form.errors) else: form = ArtworkForm2() context.update({'form' : form}) return render(request, 'exp/create.html', context) -
Why my 127.0.0.1/800 is not connecting to Django admin database even after migrate 001 initial.py
as I am new to Django. I create a project named as trackback in which I create an app named as projects after successfully creating superuser to my Django admin and migrate my 0001 initial.py database is not connecting. I register my model name inadmin.py too. -
Django - Adding meta table for dynamic table
I would like to create a dynamic table as Person. The extra information depends on user's requirements as key-value. So, I'm looking what is the correct way to do this operation. My codes are: class Person(models.Model): age = models.CharField(..) name = models.CharField(..) class PersonMeta(models.Model): value = models.CharField(max_length=255) key = models.CharField(max_length=255) person = models.ForeignKey(Person, on_delete=models.CASCADE) with this way it works but is this correct way to do that? -
Errors getting started with django-eav2
I'm trying to make a simple app for users to create multiple choice tests for each other, where they can specify which data type should apply to the answer for each question. To this end, I'm trying to get django-eav2 working, following this guide. However, I run into errors as soon as I try to makemigrations. Using eav.register: from django.db import models from django.utils.translation import ugettext as _ from eav.models import Attribute class Question(models.Model): class DataType(models.TextChoices): TEXT = 'TXT', _('Text') INTEGER = 'INT', _('Integer (whole number)') FLOAT = 'FLT', _('Float (number with fractional parts, e.g. 3.14159)') question_text = models.CharField(max_length=400) question_type = models.CharField(max_length=3, choices=DataType.choices, default=DataType.TEXT) class Answer(models.Model): question = models.ManyToManyField(Question) import eav eav.register(Answer) Attribute.objects.create(slug='txt_value', datatype=Attribute.TYPE_TEXT) Attribute.objects.create(slug='int_value', datatype=Attribute.TYPE_INT) Attribute.objects.create(slug='flt_value', datatype=Attribute.TYPE_FLOAT) I get "django.db.utils.OperationalError: no such table: eav_attribute" Using decorators: from django.db import models from django.utils.translation import ugettext as _ from eav.models import Attribute from eav.decorators import register_eav #Dynamic user-specified data types is tricky, see # https://stackoverflow.com/questions/7933596/django-dynamic-model-fields class Question(models.Model): class DataType(models.TextChoices): TEXT = 'TXT', _('Text') INTEGER = 'INT', _('Integer (whole number)') FLOAT = 'FLT', _('Float (number with fractional parts, e.g. 3.14159)') question_text = models.CharField(max_length=400) question_type = models.CharField(max_length=3, choices=DataType.choices, default=DataType.TEXT) @register_eav class Answer(models.Model): question = models.ManyToManyField(Question) Attribute.objects.create(slug='txt_value', datatype=Attribute.TYPE_TEXT) Attribute.objects.create(slug='int_value', datatype=Attribute.TYPE_INT) Attribute.objects.create(slug='flt_value', datatype=Attribute.TYPE_FLOAT) I get … -
After any bug in Django html i get same exception: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128)
Exception inside application: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) File "/venv/lib/python3.6/site-packages/channels/http.py", line 213, in __call__ await self.handle(body) File "/venv/lib/python3.6/site-packages/asgiref/sync.py", line 150, in __call__ return await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 333, in wait_for return (yield from fut) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 55, in run result = self.fn(*self.args, **self.kwargs) File "/venv/lib/python3.6/site-packages/asgiref/sync.py", line 169, in thread_handler return func(*args, **kwargs) File "/venv/lib/python3.6/site-packages/channels/http.py", line 246, in handle response = self.get_response(request) File "/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response html = reporter.get_traceback_html() File "/venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html t = DEBUG_ENGINE.from_string(fh.read()) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) Always get the same exception when i get error in html files (include django admin). Project haven't any cyrillic symbols, only latin.