Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i have faced problem with django runserver command on cmd
hi guys i have facing problem with python python manage.py runserver it doesn't work on command line it opening the python IDLE -
How to validate and save a django form which lacks a required field?
This is my model: class MyModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) field1 = models.CharField(max_length=3, blank=True) field2 = models.CharField(max_length=3, blank=True) and this is my form: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ['field1','field2'] when I want to save my form instance I get an error like this: {'user': [u'This field cannot be null.']} I have a user field in MyModel which is not presented in the form's field list. So how can I set user in the form without changing the form itself. I need something like this which doesn't work: user = User.objects.first() data = {'field1':'123','field2':'456', 'user': user} form1 = MyForm(data) form1.save() -
NoReverseMatch on Django project when uploaded to a server
Now at the time of teleworking (I'm not a django professional) I tried to make a web app to help my department a bit. I built it and reached at the point where it was ready to be uploaded on my linode server (ubuntu with nginx). While EVERYTHING works fine locally, on the server I get a NoReverseMatch error.. specifically: Reverse for 'delete' not found. 'delete' is not a valid view function or pattern name. The erros is in the html (of course) on the line: <a href="{% url 'delete' shift_id=shift.id mo='m_mo08' %}" onclick="del()">{{ shift.m_mo08 }}</a> The view is: def delete(request, shift_id, mo): Shift.objects.filter(pk=shift_id).update(**{mo: ""}) return HttpResponseRedirect("/") and from the urls: path('delete/<int:shift_id>/<str:mo>/', delete, name="delete") As I said locally everything works fine, but not on the server.. I deleted and uploaded the whole thing again but the error is still there. Has anyone any ideas? -
Handling multiple users concurrently populating a PostgreSQL database
I'm currently trying to build a web app that would allow many users to query an external API (I cannot retrieve all the data served by this API at regular intervals to populate my PostgreSQL database for various reasons). I've read several thing about ACID and MVCC but still, I'm not sure there won't be any problem if several users are populating/reading my PostgreSQL database at the very same time. So here I'm asking for advice (I'm very new to this field)! Let's say my users query the external API to retrieve articles. They make their search via a form, the back end gets it, queries the api, populates the database, then query the database to return some data to the front end. Would it be okay to simply create a unique table to store the articles returned by the API when users are querying it ? Shall I rather store the articles returned by the API and associate each of them to the user that requested it (the Article model will contain a foreign key mapping to a User model)? Or shall I give each user a table (data isolation would be good but that sounds very inefficient)? Thanks … -
no such table (makemigrations not fixing)
I am getting an error in my admin panel. I have created instances of PaintOption but when I open a ProductModel I get no such table: main_productmodel_paint_options. I've tried running python manage.py makemigrations main and python manage.py migrate with no luck. models.py class PaintOption(models.Model): title = models.CharField(max_length=50) thumbnail = models.ImageField(upload_to='paint-options/') class Meta: verbose_name_plural = "Paint Options" def __str__(self): return self.title class ProductModel(models.Model): def image_dir(self, filename): modeldir = slugify(self.title) return "models/" + osjoin(modeldir, filename) title = models.CharField(max_length=80) category = models.ManyToManyField(ProductCategory) featured_image = models.ImageField(upload_to=image_dir) paint_options = models.ManyToManyField(PaintOption) model_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Product Models" def __str__(self): return self.title admin.py class ProductModelAdmin(admin.ModelAdmin): ordering = ["title"] fieldsets = [ ("Title/Featured Image", {'fields': ["title", "category", "featured_image", "image_tag", "featured"]}), ("Paint Options", {'fields': ["paint_options"]}), ] -
Django elasticsearch-dsl updating M2M on pre_save
I am using the django-elasticsearch-dsl package and am having a little bit of a dilemma. Here is my code: models.py class Source(models.model): name = models.CharField(max_length=50) class Posting(models.Model): title = models.CharField(max_length=250) sources = models.ManyToMany(Sources, related_name="postings", through="PostingSource") class PostingSource(models.Model): posting = models.ForeignKey(Posting, related_name="posting_sources", on_delete=models.CASCADE) source = models.ForeignKey(Source, related_name="posting_sources", on_delete=models.CASCADE) documents.py class PostingDocument(Document): sources = fields.ObjectField(properties={"name": fields.KeywordField()}) class Index: name = "posting" settings = {"all the settings stuff"} class Django: model = Posting fields = ["title"] related_models = [PostingSource] def get_queryset(self): return super().get_queryset().select_related("sources") def get_instance_from_related(self, related_instance): if isinstance(related_instance, PostingSource): return related_instance.posting My issue is, when I update the sources on the posting, for some reason, the elasticsearch index is updated pre_save and not post_save. I basically have to do a put request 2 times with the same sources in order for the changes to reflect in my index. I added a def prepare_sources(self, instance): as part of my document and it seems to work, but it feels like it will cause performance issues later. Any help or guidance will be greatly appreciated. -
Django - accessing the pk/id of Post module that is inside a Comment model
So i have this post module: class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) date_pub = models.DateTimeField(timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home') and this comment module: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) comment_author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=255) def get_absolute_url(self): return reverse('blog-home') and this is my view for the comment: class CreateComment(LoginRequiredMixin, CreateView): model = Comment template_name = 'my_blog/create_post.html' fields = ['content'] def form_valid(self, form): form.instance.comment_author = self.request.user # form.instance.post_id = return super().form_valid(form) as for the urls: /post/1 ===> will be post number 1 /post/1/comment ===> is the form the to post a new comment I want the form.instance.post_id to be the post id that the comment belongs to. How do I do that ? -
How to make HTML5 <video> work on Safari?
I looked at a lot of articles about this problem and nothing helped. What should I add to the code below to make it work in Safari? <video muted playsinline autoplay loop width="100"> <source src="{% static 'dc/video/loader_dc_fix_r.mp4' %}" type='video/mp4'> </video> -
keep getting the Fatal Python error with mod_wsgi and apache
Current thread 0x00007f5aa48af880 (most recent call first): no Python frame Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = /var/www/project/venu/bin/python isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = /var/www/project/venu/bin/python sys.base_prefix = '/opt/python3.8.2' sys.base_exec_prefix = '/opt/python3.8.2' sys.executable = '/var/www/project/venu/bin/python sys.prefix = '/opt/python3.8.2' sys.exec_prefix = '/opt/python3.8.2' sys.path = [ '/opt/python3.8.2/lib/python38.zip', '/opt/python3.8.2/lib/python3.8', '/opt/python3.8.2/lib/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named encodings Current thread (most recent call first) I have complied python 3.8.2 with django 2.2. it run locally fine but when i try to deploy it with Apache and mod_wsgi 4.7.1 and getting the above error. Any suggestions ? -
How to serialize a list of objects in Django rest framework
class ChildRegistrationSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=100) last_name = serializers.CharField(max_length=100) class ParentRegistrationSerializer(serializers.Serializer): id_number = serializers.CharField(max_length=100) children = ChildRegistrationSerializer(source="*", read_only=True, many=True) def test_register_children_success(client): registration_data = { "id_number":"123645", "children": [ { "first_name": "Test" "last_name": "Last",, }, ], } url = reverse("add_child") response = client.post(url, registration_data) The serialized data does not have children it come back as blank -
Change Django template loop behavior based on browser window size
my web app uses a Django template for loop to display 52 weeks of a year on one line. Once 52 weeks have been displayed, I use a <br> tag to break line and start the weeks of the next year. This works great on large screens, but when I reduce screen size less than 1200px (Bootstrap xl setting) the nice-looking line breaks and then the overflow fills the next line, creating an uneven break. For browser window size greater than 1200px, I would like to continue displaying 52 weeks as denoted by a monotype character (in this case "X" and "O"). For browser window semi less than 1200px, I would like to display each line with only 13 weeks (52 divided by 4) such that one "year" takes up four rows. Here is the code I have: {% extends 'base.html' %} {% block content %} <p class="text-monospace"> {% for week in week_list %} {% if week.is_current_week %} <a href="{% url 'week_view' week.week_number %}">H</a> {% elif week.is_past %} <a href="{% url 'week_view' week.week_number %}">X</a> {% else %} <a href="{% url 'week_view' week.week_number %}">O</a> {% endif %} {% if week.week_number|divisibleby:"52" %} <br> {% endif %} {% endfor %} </p> {% endblock … -
What backend should I use to serve multiple websites, e.g. wordpress, web apps and mobile apps?
I am just starting to learn back end development, recently learned php and wordpress development, and I don't know what I should learn next. The image below shows what I want to set up, and the software I think, but don't know if, I can use to achieve this. Can I use a droplet on digitalocean and with django, nginx and uWSGI use that to host multiple static websites, wordpress websites and web apps. Can I also use the same server to communicate with mobile apps (created with flutter)? Is this even possible, and what software do I need to use? -
Is it possible to dump a python fixture in runtime?
I have this test case: def test_ingest_projects(self): file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'projects.csv') with open(file_path, 'r', encoding='utf-8-sig') as csvfile: reader = csv.DictReader(csvfile) projects = [] for row in reader: row['effort'] = float(row['effort']) projects.append(Project(**row)) Project.objects.bulk_create(projects) print(Project.objects.all()) After running it I want to dump a json fixture of the Project table, is this possible on runtime? -
Scrapy get norofication when all spiders are closed
I'm using django to start scrapy crawls with scrapyd = ScrapydAPI('http://localhost:6800') spiders = scrapyd.list_spiders("default") for spider in spiders: scrapyd.schedule("default", spider, list_id=list.id, spiders_number=3) Do I'm able to connect all spiders related to single request based on list_id. I wish to get an information when all spiders finished their work. It is simple to send that information from spider to django (I can get an instance of django model and update it). But I do not know if current spider is the last one, which was running. Is it possible to exchange data between spiders? Is there any well known approach to do that? -
Django import-export: adding multiple child model instances when uploading a csv?
I want to add multiple Brands to a Store from the parent model admin view but i keep getting error: Line number: 4 - get() returned more than one Brands -- it returned 2! models.py class Store(models.Model): store = models.IntegerField(primary_key=True) state = models.CharField(max_length=250, blank=True) # pylint: disable=R0903 def __str__(self): return '{}'.format(self.store) class Brand(models.Model): store = models.ForeignKey('Store', on_delete=models.CASCADE, blank=True, null=True) company = models.CharField(max_length=250, blank=True) # top selling rank rank = models.IntegerField(blank=True, default='') # pylint: disable=R0903 def __str__(self): return '{}'.format(self.store) admin.py class StoreInline(admin.StackedInline): model = Brand class StoreResource(resources.ModelResource): store = fields.Field(attribute='store', column_name='Store') state = fields.Field(attribute='state', column_name='State') company = fields.Field(attribute='company', column_name='Company', widget=ForeignKeyWidget(Brand, 'company')) rank = fields.Field(attribute='rank', column_name='Rank', widget=ForeignKeyWidget(Brand, 'rank')) class Meta: model = Store import_id_fields = ('store', 'state',) fields = ('store', 'state', 'company', 'rank') def before_import_row(self, row, **kwargs): company = row.get('Company') rank = row.get('Rank') company = Brand.objects.get_or_create(company=company, rank=rank) class StoreAdmin(ImportExportModelAdmin): inlines = [BrandInline] resource_class = StoreResource list_display = ['store', 'state'] class Meta: model = Store admin.site.register(Store, StoreAdmin) But when I upload a csv through the child model it adds the data with no issues. code for that below. For readability reasons id rather upload it through the parent. code for child admin below class StoreResource(resources.ModelResource): store = fields.Field(attribute='store', column_name='Store', widget=ForeignKeyWidget(Store, 'store')) state = … -
django pk doesn't work for pk value above 9
Hi i m new in django and i m trying to figure out now for hour , why does primary key(pk) doesn't work correctly to update my form for value above 9. Its say that The current path, tache_app/TacheUpdate/15, didn't match any of these. I have check numerous time the id 15 and it does exist. My guess is that primary key (pk) doesn't work for value above 9. Here is my code please help to figure it out. Appologies for my english it isn't so good. i live in france. in my urls.py file """Mettre les urls pour la tache app etc etc etc """ from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('tache_ajouter/' , views.tache_ajouter , name='tache_ajouter' ), url(r'^TacheCreate$', views.TacheCreate.as_view(), name='TacheCreate'), url(r'^TacheUpdate/(?P<pk>\d)$', views.TacheUpdate.as_view(), name='TacheUpdate'), url(r'^TacheDelete/(?P<pk>\d)$', views.TacheDelete.as_view(), name='TacheDelete'), ] class TacheUpdate(UpdateView): """ Creation d une view afin de modifier les d une tache """ model = Tache template_name = "tache_app/edition.html" fields = "__all__" from_class = TacheForm success_url = reverse_lazy('tache') if you need anything please ask me. -
In Django Rest Framework how to serialize a list of strings from a One to Many
I have the following model. (Simplified for Readability here) class Widget(models.Model): name = models.CharField() class FooString(models.Model): class Meta: unique_together = ["widget", "value"] widget = models.ForeignKey("Widget") value = models.CharField() In this model, the value field for a FooString is unique for a given Widget, but the value filed is not globally unique among all FooString objects. I also have the following start of a serializer for Widget class WidgetSerializer(serializers.ModelSerializer): class Meta: model = models.Widget fields = ["name", "foos"] What I"m looking for is JSON in the form of something like { "name": "Blah, Blah", "foos": [ "foo1", "foo2" ] } The foos list needs to be read/write. -
Django iterate paginated object and render as a table in HTML template
I am struggling to show a paginated table as the Django admin page did but without success yet. The goal is to paginate the table to reduce the rows in the view, and display the data in each row. While since the HTML template will serve more than one table, it is not good to specify the field name of the specific model. Here is the view: def my_view(request): model_list = Model.objects.all() field_names = [f.name for f in Model._meta.get_fields()][1:] # drop the id # object_values = [] # for object in model_list: # object_values.append([]) # for field in field_names: # object_values[-1].append(getattr(object, field)) paginator = Paginator(model_list, 10) page = request.GET.get('page', 1) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) return render(request, 'my_folder/my_view.html', {'paginator': paginator, 'filter': model_list, 'table': data, 'field_names': field_names}) Here is my HTML template: <table> <thead> <tr> <th class="action-checkbox"> <div> <span> <input type="checkbox"> </span> </div> </th> {% for header in field_names %} <th class="sortable-column-name">{{header}}</th> {% endfor %} </tr> </thead> <tbody> {% for rowval in table %} <tr> <th class="action-checkbox"> <div> <span> <input type="checkbox"> </span> </div> </th> {% for val in rowval %} {% if forloop.counter == 2 %} <th>{{val}}</th> {% else %} <td>{{val}}</td> {% … -
How to write something with a mustache in Django
I'm trying to implement a website with AMP using Django technology, everything was okay just I want to make the change pagination without load the whole page so I need to use amp-list, the problem is when I start using it I get a problem. I will explain a little bit about amp-list, to fetch data using amp-list we need to use some tag like the tags that exist on Django like {{#posts}} and {{slug}}, so the problem Django thinks those are variables. a small example: <amp-list width="auto" height="100" layout="fixed-height" src="myUrl" [src]="myUrl + pageNumber"> <template type="amp-mustache"> {{#posts}} <div> <h1>{{title}}</h1> <p>{{content}}</p> </div> {{/posts}} </template> </amp-list> I have tried with some ways like put these in a variable and call it on the template but I get the same error. I wonder if there is a way that I can use those tags, I think there is something that let you write mustache in the Django template. -
Browser back button from Django page to React page renders raw JSON
I have an app with one single page react app but other pages are Django templates. For example I have a react dashboard which has buttons that take you to different django templates (pages) This works fine until I use the browser back button to go to react dashboard and it just gives me raw json data. But as soon as I hit refresh it loads the DOM So first I though I ll use performance.navigation.type === 2 in the useEffect and just reload from there but the useEffect is not even getting called. I did try some stack overflow answers but most of them answer how to handle back button when you are routing with in a react app. Any solution would be appreciated. Ty -
Page with forms for multiple foreign keys
Given the following (simplified) models: class Person(models.Model): name = models.CharField(max_length=64) class Weight(models.Model): person = models.ForeignKey(Person, verbose_name="Person") date = models.DateField("Date") weight = models.DecimalField("Weight", max_digits=4, decimal_places=1) I'm looking for a way to add weight information for a certain group of Persons at once, which I specify through e.g. GET params. The length of the list of Persons and the Persons in the list can vary. So I'm looking to generate a page like: Person 1 Date: <pick date> Weight: <enter weight> Person 2 Date: <pick date> Weight: <enter weight> Person 3 Date: <pick date> Weight: <enter weight> Person 4 Date: <pick date> Weight: <enter weight> Person 5 Date: <pick date> Weight: <enter weight> <Save> This would then save weight information 5 times, once for each (different) Person. I had a look at the formsets and related documentation, but it looks like these are more for identical items and to on-the-fly generate more (e.g. creating multiple books under one author). In my case, each weight is bound to a certain Person, but the Person differs from line to line in the table. I thought the prefix option on a formset (to use different formsets on one page) might be of help here, but … -
Startproject command gives back no python found even though I do have python
I'm trying to create a project, at first I got the error that django-admin wasn't recognized as a internal or external command. After trying some stuff with my path in the environmental variables,I now get the following error when executing 'Django-admin startproject': D:\Development\python>django-admin startproject djangoblog No Python at 'C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe' -
Django Admin Lazy Self-Referencing Dropdown
I have a self-referencing model of schedule tasks that refer to other rows in the same table for task predecessor relationships. class ScheduleTemplateTasks(models.Model): schedule_template_id = models.ForeignKey(ScheduleTemplate) task = models.CharField(max_length=50, db_index=True) duration = models.PositiveIntegerField() pred1id = models.IntegerField(null=True, blank=True, db_index=True) pred1lag = models.IntegerField(null=True, blank=True) pred2id = models.IntegerField(null=True, blank=True, db_index=True) pred2lag = models.IntegerField(null=True, blank=True) pred3id = models.IntegerField(null=True, blank=True, db_index=True) pred3lag = models.IntegerField(null=True, blank=True) pred4id = models.IntegerField(null=True, blank=True, db_index=True) pred4lag = models.IntegerField(null=True, blank=True) pred5id = models.IntegerField(null=True, blank=True, db_index=True) pred5lag = models.IntegerField(null=True, blank=True) class JobScheduleTasks(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) task = models.CharField(max_length=50, db_index=True) duration = models.PositiveIntegerField() pred1id = models.IntegerField(null=True, blank=True, db_index=True) pred1lag = models.IntegerField(null=True, blank=True) pred2id = models.IntegerField(null=True, blank=True, db_index=True) pred2lag = models.IntegerField(null=True, blank=True) pred3id = models.IntegerField(null=True, blank=True, db_index=True) pred3lag = models.IntegerField(null=True, blank=True) pred4id = models.IntegerField(null=True, blank=True, db_index=True) pred4lag = models.IntegerField(null=True, blank=True) pred5id = models.IntegerField(null=True, blank=True, db_index=True) pred5lag = models.IntegerField(null=True, blank=True) baseline_start_date = models.DateField(null=True, blank=True) planned_start_date = models.DateField(null=True, blank=True, db_index=True) actual_start_date = models.DateField(null=True, blank=True, db_index=True) baseline_end_date = models.DateField(null=True, blank=True) planned_end_date = models.DateField(null=True, blank=True, db_index=True) actual_end_date = models.DateField(null=True, blank=True, db_index=True) During creation of the actual job schedule I copy row-by-row ScheduleTemplateTasks saving a list of original task ids and the newly create ids for the JobScheduleTask. Once all rows are in the JobScheduleTasks model, I spin … -
How can I place images (variable number of them) relatively to each other and also scale jumbotron they are in accordingly? Django
I wanted to ask you for your help. I fought with it for quite a long time but I couldn't come up with good solutions. This is my first project in django and html/css/js so I am sorry in advance :P I created two images that will help me explain my problem: In this case I have three images, pngs with alpha. Actual image is in red "I-1". Darker border is actual image size. By default they of course stack like that. And yellow is other stuff. When I place them ether by position relative or absolute it looks like that: And it is also quite logical why this happens. This is kinda what I want to achieve. But there are two/three problems: 1.1 - Other stuff for website is way down, this looks weird and I don't like that. 1.2 - My jumbotron also is stretched way down. 2 - I have different amount of images in various cases. Sometimes there are 3 of them and sometimes 5 of them. And each one of them I need to place a little bit different. That is a big problem for me. I managed to create three types of them, when … -
Bulk Update Objects in Django Rest Framework
I would like to bulk update some model objects with validation. I am sending a PUT request with the following request body: [{ "id": 1, "is_passed": true }, { "id": 2, "is_passed": true }] My view to handle this request currently looks like: class BulkUpdateAPIView(UpdateAPIView): permission_classes = [AllowAny] serializer_class = BulkUpdateSerializer queryset = Example.objects.filter(is_active=True) def put(self, request, *args, **kwargs): data = self.request.data ids = list() for item in data: ids.append(item['id']) instances = self.queryset.filter(pk__in=ids) serializer = BulkUpdateSerializer(data=data, instance=instances, many=True) serializer.is_valid(raise_exception=True) if serializer.is_valid(): # do something return Response(status=HTTP_200_OK) and the BulkUpdateSerializer looks like: class BulkUpdateSerializer(ModelSerializer): class Meta: model = Example fields = [ 'id', 'is_passed', ] def validate_is_passed(self, value): for item in self.instance: if item.verified_by is not None: raise ValidationError('%s has already been verified.' %(item.name)) I am having several issues here: The put method expects a list in the request body, if a user sends a wrong data type or a wrong format of data how can return an error message mentioning what is wrong with the request? The ValidationError in validate_is_passed is being called twice. Therefore, the same error is returning twice. How can I make sure that it is being called only once? Is it possible to add an update …