Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
view must be a callable or a list/tuple in the case of include()
File "/home/bsd/PycharmProjects/BSD/BSD_2_7/BSD_2_7/urls.py", line 10, in <module> url('$', 'base.views.index'), File "/usr/local/lib/python3.6/dist-packages/django/conf/urls/__init__.py", line 13, in url return re_path(regex, view, kwargs, name) File "/usr/local/lib/python3.6/dist-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). urlpatterns = [ url('$', 'myapp.views.index')] I am using django 2.2, pythong 3.6. The app previously written in django 1.7, I dont know how to fix that error into django 2.2 . When I try to do from myapp.views import index and url('$', index, name="index")] it doesnt see from myapp.views -
first django_project / password reset timeout error
Hello I'm following an incredibly informative tutorial series on YouTube by a guy named CoreyMS https://www.youtube.com/watch?v=-tyBEsHSv7w&t=394s I've made it the 12th video where he is teaching me how to set up a password reset page. I initially had trouble getting my gmail info placed in an environment variable, and perhaps that is still my problem, but every time I type in my email then hit Request Password Reset it just does nothing for a long time then eventually times out: /password-reset [Errno 60] Operation timed out Can someone please help me to figure this out? Thank you :) -
Django How to upload multiple images and associate with a model
Errors when attempting to upload multiple images Description of issue: I have a model, Vehicle which has vehicle information as well as a cover photo. To add images for a gallery, I have a second model VehicleImage with a foreign key to Vehicle. I'm attempting to upload multiple images with a single file picker and save those all to a defined path (/media/vehicles/vehicle#/) I've tried different views to no avail. Right now i'm getting the following error. Raised by: main.views.ImageFieldView No vehicle image found matching the query Thank you, any help would be greatly appreciated. I'm still learning but I work at it every day. models.py def vehicle_directory_path(instance, filename): #! file will be uploaded to media_cdn/vehicle/<id>/<filename>.<ext> ext = filename.split('.')[-1] name = filename.split('.')[0] vehicle = Vehicle.objects.get(id=instance.id) return 'vehicles/{0}/{1}.{2}'.format(vehicle.id, name, ext) class VehicleImage(models.Model): # TODO Set up ModelFormset in forms.py, one for Vehicle and one for VehicleImage vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to=vehicle_directory_path, null=True, blank=True) forms.py class ImageFieldForm(forms.ModelForm): image_field = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = VehicleImage exclude = ('image', 'vehicle') views.py class ImageFieldView(CreateView): model = VehicleImage form_class = ImageFieldForm def get(self, request, *args, **kwargs): context = {'form': ImageFieldForm} return render(request, 'main/vehicle_upload.html', context) def post(self, request, *args, **kwargs): self.object = … -
CSS is not showing
I am learning Django and while I was trying to load CSS from static file, it is not showing any output. Here is my code settings.py code # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), 'bloodnepal/bloodnepal/static', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') HTML <head> {% load static %} <meta charset="utf-8"> <title>Bloodnepal</title> <link rel="stylesheet" href="{% static 'css_files/style.css' %}"> <link rel="stylesheet" href='{% static "css_files/link.css" %}'> <link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Fira Sans Extra Condensed' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Nanum Myeongjo' rel='stylesheet' type='text/css'> </head> url.py from django.contrib import admin from django.urls import path from . import views #imported the views.py files here for our pipeline from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('home/',views.home,name="Homepage"), path('donate/',views.donate,name="Donatepage"), path('organization/',views.organization,name="Organizationpage"), path('getinvolved/',views.getinvolved,name="Getinvolvedpage"), path('about/',views.about,name="AboutUspage"), ] urlpatterns += staticfiles_urlpatterns() -
django.db.utils.InterfaceError: connection already closed failures when updating to Django 3.0
I am updating a medium-sized project to Django 3.0 and I am encountering several errors in my tests after doing nothing more than bumping the Django version from 2.3. The whole test suite has been running correctly for years and I couldn't find any relevant change in the changelog that may point to the cause of this issue. Apparently a single test fail is triggering every remaining test in the same TestCase class to fail with the following exception: Traceback (most recent call last): File "/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 238, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/env/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner return func(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 231, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed I am out of ideas as to what could be going on here. -
Django HTTP Redirect W/ Context & Arguments
I'm trying to redirect my users to a classroom page that redirects them with the following url & the context. /points/k8_points_classroom/ If i do a regular return HTTPResponseRedirect with a reverse i can send the argument of classid , however i cant send my context . What is the proper way of doing this or work around ? Thanks K8Points View def K8_Points(request): if request.method == "POST": form = K8PointsForm(request.POST) if form.is_valid(): form.save(commit=False) class_name = form.cleaned_data.get('class_name') classid = TeacherClass.objects.values_list('id', flat = True).filter(class_name=class_name) getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all().order_by('student_name') form = K8Points_ClassroomForm() context = {'form': form ,'students' : students, 'class_name': class_name, 'classid':classid} return render(request, 'points/k8_points_classroom.html', context )<---This is where redirect should be to get to next view. if request.method == "GET": form= K8PointsForm(request.GET) return render(request, 'points/k8_points.html', {'form': form } ) K8_Points_Classroom Views @login_required def K8_Points_Classroom(request, classid,): if request.method == 'POST': form = K8Points_ClassroomForm(request.POST) if form.is_valid(): form.save(commit=False) form.save() class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all().order_by('student_name') form = K8Points_ClassroomForm() date = datetime.date.today() context = {'form': form ,'students' : students, 'class_name': class_name,} messages.success(request,("Points were successfully added for student !")) return render(request, 'points/k8_points_classroom.html', context ) if not form.is_valid(): messages.warning(request,(form._errors)) class_name = request.POST.get('class_name')[0] getstudents = Student.objects.filter(class_name = class_name) students = … -
Filtering django queryset by a value of the through table of a m2m relationship
I'm trying to do this: queryset.filter(m2m_related_lookup__through_table_field=value) These are the models, simplified: class User(models.Model): name = models.CharField("nom", max_length=100) surname = models.CharField("cognoms", max_length=100) class Activity(models.Model): name = models.CharField("Títol", max_length=200) date_start = models.DateField("Dia inici") date_end = models.DateField("Dia finalització") enrolled = models.ManyToManyField(User, related_name='enrolled_activities', through='ActivityEnrolled') class ActivityEnrolled(models.Model): class Meta: db_table = 'main_activity_personetes_enrolled' activity = models.ForeignKey(Activity, on_delete=models.CASCADE) user = models.ForeignKey(Personeta, on_delete=models.CASCADE) date_enrolled = models.DateTimeField("data d'inscripció") confirmed = models.BooleanField("confirmada", default=False) I guess is quite simple, just a many 2 many with a custom through table, so I can store the enrollment date and some other things there. This relationship is set at Activity, with a related_name of 'enrolled_activities'. So, how can I query "all the users where the ActivityEnrolled.enrollment_date is in 2019" using Django's ORM? This is for a custom filter (with admin.SimpleListFilter) for a change_list view in the Django Admin, which is listing the User items. In other words, is like I'm doing User.objects.filter(blabla). Trying: queryset.filter(enrolled_activities__date_enrolled__year=2019) obviously throws the error Related Field got invalid lookup: date_enrolled, because enrolled_activities does not refer to the through table but to the related table (this is: Activity), and this field does not exist there. Is the only solution to query the through table instead of Users? Like: ActivityEnrolled.objects.filter(date_enrolled__year=2019) + grouping … -
How to properly display images to html template in Django framework?
I've been trying for a day to try to get the images that are saved to the media folder to display in my template file, but to no avail. The images are uploaded to the media/images folder, but I can't figure out how to display them. I can't figure out what I'm doing wrong because I see many people use these methods and get a result. I'm thinking maybe my post function isn't returning the correct data to the template? I'm extremely new in Django and html, so please forgive my mistakes. This is my current setup: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py from django.db import models class Post(models.Model): post = models.ImageField(upload_to="images") forms.py from django import forms from imageDetection.models import Post class HomeForm(forms.ModelForm): class Meta: model = Post fields = ('post',) views.py class HomeView(TemplateView): template_name = 'imageDetection/test.html' @staticmethod def detect(request): return render(request, 'imageDetection/detection.html') def get(self, request): form = forms.HomeForm() return render(request, self.template_name, {'form': form}) def post (self, request): context = {} if request.method == "POST": form = forms.HomeForm(request.POST, request.FILES) if form.is_valid(): image_form = models.Post() image_form.post = form.cleaned_data['post'] image_form.save() context['form'] = image_form return render (request, 'imageDetection/detection.html', context) else: form = forms.HomeForm() context['form'] = form return render(request, self.template_name, context) … -
XMLHttpRequest is not sending POST data to Django server
Javascript to send data via XMLHttpRequest csrftoken = getCookie('csrftoken'); var request = new XMLHttpRequest(); request.open('POST', '/register'); request.setRequestHeader("X-CSRFToken", csrftoken); request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); request.send("data"); Django view: def register_user(request): if request.method == "POST": print("django server") print(request.POST) Sever is printing: django server <QueryDict: {}> I have also triend application/json as content type with json data, but that is also not working. The data does not seem to be being passed to the server. Not sure why. -
How can i show error message in django registration form?
I want to register user using custom form. Everything is fine, but registration is incorrect if the form is incorrect, but I want the error message to show the form but it does not. How can i get error message in my html page ? forms.py views.py registration.html -
Deserialize nested JSON structures to Django model objects
I need to consume a service that sends JSON responses containing JSON-serialized nested structures, which I would like to deserialize and store in my database - my application uses Django. If I flatten the structure to save into a single model, there will be a horrendous replication of data, against all data normalization rules. So I wrote related models mirroring the expected data. But I would like to know whether Django offers a way of pushing each nested JSON structure into a sort of recursive update_or_create() operation, so that each related object would then be "updated or created" as well, or, in the other hand, I would need to hard code the whole deserialization process for each of those object models... I would be dealing with two types of relations: { "foreign_key_object": {"pk": 123}, "many_to_many_objects": [{"pk": 456}, {"pk": 789}, {"pk": 987}], } Below I'm reproducing a very abridged sample of the data I receive from the service and the models I in which I want to store it. The real thing is much, much more bulky and complex than that, and that's why I'm so wanting to learn a way of letting the ORM take care of the problem, should … -
How do I fix this attribute error in my Django App?
I am developing a Django app and I've created a place where the users can upvote or downvote a film, the problem is that when I hit one of these buttons this error shows up: in likesDislikesPelicula voto = Likes.objects.filter(usuario=request.Usuarioclte, pelicula__pk=idpelicula) AttributeError: 'WSGIRequest' object has no attribute 'Usuarioclte' my views.py def detallesPelicula(request, pelicula_id): peliculas = get_list_or_404(Pelicula.objects.order_by('titulo')) pelicula = get_object_or_404(Pelicula, pk=pelicula_id) actor = get_list_or_404(Actor.objects) likes = conteolikes(pelicula) dislikes = conteodislikes(pelicula) context = { 'pelicula': pelicula, 'peliculas': peliculas, 'likes': likes, 'dislikes': dislikes } return render(request, 'detallesPelicula.html', context) def conteolikes(pelicula): return pelicula.users_vote.filter(valor__gt=0).count() def conteodislikes(pelicula): return pelicula.users_vote.filter(valor__lt=0).count() @csrf_exempt def likesDislikesPelicula(request): if request.method == 'POST': idpelicula= request.POST.get('idpelicula','') valor = request.POST.get('valor','') try: voto = Likes.objects.filter(usuario=request.Usuarioclte, pelicula__pk=idpelicula) print("Existe") print(voto) except Likes.DoesNotExist: print("No existe") my models.py (Simplified) class Usuarioclte(models.Model): nickname = models.CharField(max_length=50) contraseña = models.CharField(max_length=50) email = models.EmailField(max_length=50) def __str__(self): return self.nickname class Likes(models.Model): #necesito que usuario y pelicula sean una calve compuesta #usuario_id= models.ForeignKey(User.id,on_delete= models.CASCADE) pelicula = models.ForeignKey(Pelicula, on_delete=models.CASCADE, related_name = 'users_vote') usuarioclte = models.ForeignKey(Usuarioclte, on_delete=models.CASCADE, related_name= 'likes_and_dislikes') valor = models.IntegerField(default=0) def __str__(self): return self.usuarioclte.nickname Note: The users are taken and stored by the Django Authentication system, not in a table that I've created. I have seen that is has to do something with the MIDDLEWARE AND … -
Django 2.2 make migrations fails with cryptic (AttributeError: 'Node' object has no attribute 'ancestors') message while 2.1 succeeds
Have the following problem and I do not know how to tackle it: While trying to python manage.py makemigrations on Django 2.2.10 even without anything new, I get the following error: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/path/to/virtualenv/lib/python3.7/site-packages/migrate_sql/management/commands/makemigrations.py", line 119, in handle migration_name=self.migration_name, File "/path/to/virtualenv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/path/to/virtualenv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 186, in _detect_changes self.generate_altered_fields() File "/path/to/virtualenv/lib/python3.7/site-packages/migrate_sql/autodetector.py", line 255, in generate_altered_fields self.generate_sql_changes() File "/path/to/virtualenv/lib/python3.7/site-packages/migrate_sql/autodetector.py", line 229, in generate_sql_changes keys = self.assemble_changes(new_keys, changed_keys, self.to_sql_graph) File "/path/to/virtualenv/lib/python3.7/site-packages/migrate_sql/autodetector.py", line 95, in assemble_changes ancs = node.ancestors()[:-1] AttributeError: 'Node' object has no attribute 'ancestors' The only way I could fix this was to revert back to Django 2.1.10 then create from then the models I needed and then install again. Then python manage.py migrate runs - on Django 2.2.10 without a problem. Because of the message, I have no indication on what has gone wrong or why. Could it be one of the installed applications that are model related? Any idea … -
Permalink removed in Django
def get_absolute_url(self): return ('threads_reply', [self.id]) get_absolute_url = models.permalink(get_absolute_url) So here is the issue, I get error on that line Attribute error: module named Django.db.models has no attribute named permalink. I went through documentation, I read that I have to change permalink with reverse. Once I TRIED that, I got same error ttribute error: module named Django.db.models has no attribute named reverse. I have a Django 1.8 app, switching over to Django 2.2 -
get producer name for a particular item object
Short question. i have 2 models: Class Producer(models.Model): First_Name = models.CharField(max_length=15) Last_Name = models.CharField(max_length=15) class Product(models.Model): category = models.CharField(choices=CATEGORY_CHOICES, max_length=6) ammount_in_KG = models.IntegerField(default=1) price = models.FloatField() producer = models.ManyToManyField( Producer,related_name='item_far' ) slug = models.SlugField(default=sluger) description = models.TextField() i'm trying to build an eCommerce website and i want to query name of producer,who owns a particular product selected by the customer.i want to show it in my product detail page.so i want to show on my product detail page the following: "product name" owned by "producer name". SO my questions are: 1.How can query the producers name in view.py and in templates 2.assuming a certain product is owned by multiple producers, if the customer wants to buy more products than one producer has, how can i display the names and the product of those 2 or more producers who own the product on the page -
Error Reading an Uploaded CSV Using Dask in Django: 'InMemoryUploadedFile' object has no attribute 'startswith'
I'm building a Django app that enables users to upload a CSV via a form using a FormField. Once the CSV is imported I use the Pandas read_csv(filename) command to read in the CSV so I can do some processing on the CSV using Pandas. I've recently started learning the really useful Dask library because the size of the uploaded files can be larger than memory. Everything works fine when using Pandas pd.read_csv(filename) but when I try and use Dask dd.read_csv(filename) I get the error "'InMemoryUploadedFile' object has no attribute 'startswith'". I'm pretty new to Django, Pandas and Dask so apologies if I'm missing something obvious here. I've searched high and low and can't seem to find this error when associated with Dask anywhere on Google and I've been stuck on this for hours now! Here is the code I'm trying to use below (just the relevant bits... I hope): Inside forms.py I have: class ImportFileForm(forms.Form): file_name = forms.FileField(label='Select a csv',validators=[validate_file_extension, file_size]) Inside views.py import pandas as pd import codecs import dask.array as da import dask.dataframe as dd from dask.distributed import Client client = Client() if request.method == 'POST': form = ImportFileForm(request.POST, request.FILES) if form.is_valid(): utf8_file = codecs.EncodedFile(request.FILES['file_name'].open(),"utf-8") # IF … -
Django - render context on two HTML pages
I have a simple(I think) question, about Django context rendering. I'll step right into it - I have a 2 models, in this case, one is a table called Locked, and another is OpportunityList. OpportunityList is a model which has all the objects, and I rendered that part good(no problems with that one). When a User presses a button, which is a form, an OpportunityList's object goes into Locked table. They are linked through the PK. Locked table has parameter 'is_locked'. And my idea is, when a object is inside the Locked table, a button shows next to it(inside the html table), with an locker icon(). But, my problem is, since in my views.py, my lock function is not returning exact html where I want to render that locker icon, instead, it returns another html, which needs to be like that. Is there any way, to render same context, on 2 html pages? Thank's. This is my code : views.py def lock(request, pk): # Linking by pk. opp = get_object_or_404(OpportunityList, pk=pk) opp_locked = get_object_or_404(Locked, pk=pk) # Taking two parametters for 2 fields. eluid = Elementiur.objects.get(eluid=pk) user = User.objects.get(username=request.user) # Dont bother with this one! Just pulling one field value. field_name … -
how to click button generate an Excel file and download it in django?
I'm using django. At first there's only one button "Generate Summary". When click on it, the file {{ group.file_output_summary }} will be generated on the server, then the download button "Download Summary" will be available for click and download. I wonder is there a way to combine the generation and download by only one click/button. How to revise script #1 below to achieve that? In script #1, the line this_table.find(".generate-summary-box").click(); did nothing, because {{ group.file_output_summary.url }} is only available after the first click finishes running. {% if request.user.is_staff %} $('.generate-summary').click(function(e) { e.preventDefault(); var this_table = $(this).closest('table'); $.ajax({ type: "POST", url: "/generate_summary/", data: { 'group_id': $(this).attr('data-group-id'), 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function(result) { setTimeout(function() { window.location.href = "/pending_offers"; }, 500); alert('Offers summary is generated'); **this_table.find(".generate-summary-box").click();** }, error: function(result) { alert( "Something went wrong and the request to generate the summary was not submitted." ); } }); }); {% endif %} {% if group.file_output_summary %} <div class="generate-summary-box" style="display:inline-block;"> <a href='{{ group.file_output_summary.url }}' class="btn btn-default pull-left pending-summary" download> Download Pending Offers Summary</a> </div> {% endif %} -
POST and PATCH operations in ArrayModelField using Django DRF
I am using Django 2.2, MongoDb with Djongo. I am facing issues in POST and PATCH API. I am facing three kinds of issues. When performing a POST operation to create a new entry, API fails with error: Array items must be Model instances. What is the correct way to refer an instance of Screenplay class in POST API. Is the id of the parent class sufficient? How to perform a update to a specific field in Scene model including a text field in comments? Following is the code snippet. Sample POST API data { "title": "intro1", "screenplay": "49423c83-0078-4de1-901c-f9176b51fd33", "comments": [ { "text": "hello world", "author": "director" } ] } models.py import uuid from djongo import models class Screenplay(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False) title = models.CharField(max_length=100) def __str__(self): return self.title class Comment(models.Model): text = models.TextField(); author = models.TextField(); def __str__(self): return self.author +self.text class Scene(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False) title = models.CharField(max_length=100) screenplay = models.ForeignKey(Screenplay, related_name='scenes', on_delete=models.CASCADE) comments = models.ArrayModelField( model_container = Comment, ); def __str__(self): return self.title serializers.py from rest_framework import serializers from planning.models import Scene, Comment class ScreenplaySerializer(serializers.ModelSerializer): class Meta: model = Screenplay fields = ('id', … -
Task Shuffling by a celery worker in Django
The Use case is, I have a service by a user that calls a set of people in batches, waits for their feedback and then calls the next set of people. So the flow goes, User triggers the task Celery takes over the task - - calls first 10 users - sleeps for 1 min - calls next 10 users - sleeps for 1 min ... and so on till a user performs a certain action. In this, a thread of celery is blocked until its task is completed (ie action taken by a user). How can I do the same (waiting for 1 min between batches of calling) without keeping the thread blocked and resuming the task where it was when the thread went to sleep. Catch is, all batches of people to be called are pre-determined even before the calling starts. -
No Way to add Custom fields in wagtailvideo package?
I Change DIrectly in the Code of wagtailvideo Package, Which is not a Good Practise, Then I Will create a new app by the name of videos and then inherit the AbstractVideo, and then class CustomVideo(AbstractVideo): category = models.ForeignKey(Category, blank=False, null=True, on_delete=models.CASCADE) slug = models.SlugField(null=True) access = models.CharField(default="PUBLIC", choices=ACCESS, max_length=50, blank=True, null=True) def save(self, *args, **kwarsg): self.slug = slugify(self.title) super(CustomVideo, self).save(**kwargs) admin_form_fields = ( 'title', 'file', 'collection', 'thumbnail', 'tags', 'category', 'slug', 'access' ) Nothing Added in the WagtailAdmin then I Add it into the admin.py then a new tab will create which will have all fields and my fields also Now the Question is What We should to do add custom fields in wagtailvideo package -
Python Django Dynamic Multiple Field Dict Not Save [closed]
Parent Form class ParentForm(forms.Form): def __init__(self, *args, **kwargs): self.child = kwargs.pop("child") super(self.__class__, self).__init__(*args, **kwargs) def save(self, commit = True): parent_dict = {} address_dict = {} for field_name, field_value in self.data.items(): if field_name.startswith("parent__"): kk, name, index = field_name.split("__") parent_dict[index] = parent_dict[index] if parent_dict and isinstance(parent_dict[index], dict) else {} if name == "appid": parent_dict[index][name] = int(field_value) if field_value.isdigit() else -1 elif name == "birthdate": parent_dict[index][name] = djtz.datetime.strptime(field_value, "%Y/%m/%d") elif name in ["is_usa", "is_reside", "has_paid"]: parent_dict[index][name] = field_value == 'true' elif name in ["first_name", "middle_name", "last_name", "suffix", "applicant", "email", "phone" , "nation","resp_observer", "resp_financial",]: parent_dict[index][name] = field_value for field_name, field_value in self.data.items(): if field_name.startswith("address__"): kk, name, index = field_name.split("__") if name in ["address", "city", "state", "zipcode", "country"]: address_dict[index] = address_dict[index] if address_dict and isinstance(address_dict[index], dict) else {} address_dict[index][name] = field_value addresses = [] persons = [] for index, parent in parent_dict.items(): address = Address.objects.create(**address_dict.get(index)) if index in address_dict else None person, created = Person.objects.get_or_create(child=self.child, appid=self.child.appid, **parent) person.address = address person.save() addresses.append(address.get_dict()) persons.append(person.get_dict()) return dict(addresses=addresses, persons=persons) -
Django TinyMCE image uploader
I have been stuck for a while regarding using tiny-mce-lite4 with django. I am unable to set it up so it uploads images directly into the editor while in the admin page. I have tried reading the docs, but as a beginner I can't understand what they are specifying needs to be done. At the moment I currently have one app set up called 'main' along with the initial file that came when starting the project. What I have done so far: 1) Install tiny-mce , grapelli and django filebrowser 2) Set up a static file and media file within the 'main' directory. 3) my urls.py looks like this from django.contrib import admin from django.urls import path, include from filebrowser.sites import site from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('main.urls')), path('tinymce/', include('tinymce.urls')), path('admin/filebrowser/',site.urls), path('grappelli/', include('grappelli.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If someone could give me a quick run down of how image uploads work in tinymce or another text editor, I would really appreciate it. Obviously, I would prefer something that will work easily when transitioning between development and production. -
How to deploy django site on a windows server [closed]
I made a simple django site, and now I want to publish it publicly, I wonder how to setup my project on windows server, and how to link it to my domain, thank you -
django-storages + factoryboy: TypeError: expected string or bytes-like object
I'm working on a Django project that is going to use AWS S3 to serve static/media files. To this end I've installed both boto3 and django-storages, using this post as an example. Our project also uses FactoryBoy to help with our tests. However, the new setup causes al factories with FileFields or ImageFields to fail with the following error: TypeError: expected string or bytes-like object The model is as follows: class AcademySettings(models.Model): (...) logo = models.ImageField( blank=True, null=True, storage=PublicMediaStorage(), ) Its using the PublicMediaStorage() object, inspired by the post linked above and which is defined as follows: class PublicMediaStorage(S3Boto3Storage): """ Public media """ location = settings.AWS_PUBLIC_MEDIA_LOCATION file_overwrite = False The model has the following factory: class AcademySettingsFactory(factory.DjangoModelFactory): class Meta: model = 'core.AcademySettings' (...) logo = factory.django.ImageField(color='red') The PublicMediaStorage class uses the AWS_PUBLIC_MEDIA_LOCATION variable, which is defined in the settings: AWS_STORAGE_BUCKET_NAME: str = 'project-name-hidden' AWS_STORAGE_BUCKET_NAME: str = 'project-name-hidden' AWS_S3_CUSTOM_DOMAIN: str = '{}.s3.amazonaws.com'.format( AWS_STORAGE_BUCKET_NAME ) AWS_LOCATION: str = 'backend' AWS_PUBLIC_MEDIA_LOCATION: str = AWS_LOCATION + '/public' And finally, this test itself - for the purposes of this post a simple init will suffice: class TestAcademySettingsModel(TestCase): def setUp(self) -> None: self.academy_settings = AcademySettingsFactory() def test_init(self) -> None: self.assertTrue(self.academy_settings) It seems that the values generated …