Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error creating new content types when Uwsgi kills aworker
I am Running a django application with uwsgi, I am observing a case Sometimes, when uwsgi kills it's worker and and respawns a worker. Thu Aug 8 11:02:33 2019 - worker 1 killed successfully (pid: 25499) Thu Aug 8 11:02:33 2019 - Respawned uWSGI worker 1 (new pid: 4192) And then the next request received by the django application returns 500 error with Exception: RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually. at line content_type = ContentType.objects.get_for_model(Coupon) -
Python/Django logging: logger lets through log records below its' level?
I use Python 3.7.3 and Django 2.2.4. I wanted to extend the Django's default logging config to achieve the following: myproject emits some WARNING-s that I want to be logged to stderr using logging.StreamHandler. I want 5xx ERROR-s with stack traces also be logged to stderr the same way (but not WARNING-s about 4xx error codes!) What I tried to do first: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'myproject-console': { 'level': 'WARNING', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'myproject': { 'handlers': ['myproject-console'], 'level': 'WARNING', 'propagate': False, }, '': { 'handlers': ['myproject-console'], 'level': 'ERROR', 'propagate': False, }, } } It worked. But catch-all '' logger having the level of ERROR ended up forwarding Django's propagated WARNINGs about 400s (like Unauthorized: <url> for every 401) to the stderr too! Even though the respective logger is clearly of ERROR level, it seems to let through messages of a lower WARNING level to a WARNING handler. What I ended up doing and what worked as I wanted was to create a separate ERROR-level handler and forward catch-all ERROR logger output to it: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'myproject-console': { 'level': 'WARNING', 'class': 'logging.StreamHandler', }, 'myproject-console-error': { 'level': … -
Django html how to override css
I have a button like so .btn--primary { height: 45px; width: 300px; border: none; border-radius: 100px; background-color: #00A87E; color: #FFFFFF; font-family: Averta, sans-serif; font-size: 16px; font-weight: 600; line-height: 19px; } In my django template, I want to override some attributes of this button. Specifically, I want it to be aligned to the centre I have got this so far: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static "css/main.css" %}"/> <meta charset="UTF-8"> <title>My centre button</title> </head> <body> </body> </html> How do I accomplish this? :) -
Is there a way to modify downloaded / cloned github code?
I have cloned the following github app: https://github.com/tomwalker/django_quiz, however I would like to tweak it slightly by using my own base.html and modifying the models to fit the purpose of my site. The problem is that even if I make changes to the code it doesn't appear on the site. It's as if the code I'm editing doesn't have any influence to the app. I'm new to Django so I guess there are a simple answer for this problem? When I clone the project the app works as it should, but I can't make any changes. I therefore tried to copy the code from each file one by one into my project. This didn't work either, receiving errors like: "No module named 'quiz'" (which is an app that's included in the link above). The directory structure of my project is displayed below: mysite | |-app_1 |-app_2 |-django_quiz | | | |-essay | |-migrations | |-multichoice | |-quiz | |-true_false |-mysite I would obviously like to be able to modify the code. At the moment I could do any changes to the code in django_quiz and nothing changes on the site. -
Error loading MySQLdb module. Did you install mysqlclient? on MacOS
Am Trying to connect to my mysql db from django app. I get the below error during migratation: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I've already installed mysqlclient as below: Requirement already satisfied: mysqlclient in /usr/local/lib/python3.7/site-packages (1.4.2.post1) I've also tried with pymysql and adding below code to ini.py file: import pymysql pymysql.install_as_MySQLdb() Gives me some other errors. What could be wrong? Python 3.7 , mysql 5.7 and Django 2.2 are my setup versions. -
Setup Emacs for Django development
I am trying to set up emacs for django development. I already have elpy, jedi and flycheck set up and working with my venvs, but when I go to look for extending my setup for django development, I find too many related modes that seem to be doing similar things. Specifically package-list-packages gives me the following options: django-commands django-manage django-mode djangonaught pony-mode python-django Searching the web for comparisons doesn't seem to yield much result and I can't find anything relevant or recent here. Now I can certainly try each and every one of these for a day or two and evaluate them one by one, but I was wondering if somebody can at least help me eliminate some of the options or give me some advice on the matter. Thank you. -
How to add registration record in mongodb database?
I am working on a project in django and using mongodb. I am new in this field. I have a question that how to add registration record in mongodb using django. Just like User in django admin page. I want it to save all the users who register in my website in mongodb. How to do this? -
How to add different model to ModelForm as extra field?
So I'm trying to add an extra field to a ModelForm class in the init func, so that on the Create/Update class views I could grab this model and create a new model. Since the Model doesn't have this field, how could I add it in the init func or is there some other way I could add this field? I've tried overriding init method to include this field in the ModelForm class, but this still throws me an error that the argument is unexpected class MeterInstallationForm(ModelForm): class Meta: model = MeterInstallation fields = METER_INSTALLATION_DEFAULT_FIELDS def __init__(self, *args, **kwargs): instance = kwargs.get("instance") super(MeterInstallationForm, self).__init__(*args, **kwargs) if instance: # get tariff info in the form # self.fields["tariff"] = instance.tariff self.fields["tariff"] = TariffApplication.objects.filter(meter_installation__pk=instance.meter_installation.pk).values_list("tariff", flat=True) I would love to know how to make this work, so that in my CreateView I could start creating a third model by the given Tariff -
Django email templates rendering generate invalid html | Django Authentication. user signup emails
Django 2, Python 3. Django default authentication send email containing corrupted html. contains 3D with each attribute's equal sign. style=3D" contains = with each starting new line. padd= ing-top:20px; Sample Code: <div style=3D"padding: 40px; background: #fff;"> <table style=3D"width: 100%;" cellspacing=3D"0" cellpadding= =3D"0" border=3D"0"> <tbody> <tr> <td style=3D"border-bottom:1px solid #f6f6f6;"> <h1 style=3D"font-size:14px; font-family:ar= ial; margin:0px; font-weight:bold;">Greetings!,</h1> <p style=3D"margin-top:0px; color:#bbbbbb;"= >Here are your account activation instructions.</p> </td> </tr> <tr> <td style=3D"padding:10px 0 30px 0;"> <p>Thank you for joining us.</p> <p>To activate your profile, please follow = this link:</p> <center> <a href=3D"http://localhost:8000/accoun= ts/activate/uyi90WsYyvLKmn4wwwqq/" style=3D"display: inline-block; padding:= 11px 30px; margin: 20px 0px 30px; font-size: 15px; color: #fff; background= : #4fc3f7; border-radius: 60px; text-decoration:none;">Activate Profile</a> </center> <b>- Thanks (project team)</b> </td> </tr> <tr> <td style=3D"border-top:1px solid #f6f6f6; padd= ing-top:20px; color:#777">If the button above does not work, try copying an= d pasting the URL into your browser. If you continue to have problems, plea= se feel free to contact us at info@project.com</td> </tr> </tbody> </table> </div> Please help resolve/identify the issue. -
Is it a simple conversion or a creation of a new object?
Here are my models, pretty straightforward: class Entity(BaseModel): is_physical = models.BooleanField(default=True) class Address(BaseModel): description = models.TextField(default=None, blank=False, null=False) class EntityAddress(BaseModel): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, blank=False, null=False) address_type = models.ForeignKey(AddressType, models.CASCADE, blank=False, null=False) address = models.ForeignKey(Address, on_delete=models.CASCADE, blank=False, null=False) From there I've created the model Person which is a physical entity: class PersonManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_physical=True) class Person(Entity): objects = PersonManager() user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) Then I generate tons of addresses, tons of Persons, it works. When I try to create a "person address" like this: EntityAddress.objects.create(entity=person, address_type=choice(address_types), address=address, comment=None))) I get "EntityAddress.entity" must be a "Entity" instance. The solution is : EntityAddress.objects.create(entity=Entity(person), address_type=choice(address_types), address=address, comment=None))) Hence my question: does Entity(person) create a new object in memory, or it just does a simple conversion? -
Search Engine in Django
When I search the files I uploaded using the upload functionality of the website, the search engine finds the files. However, when I try to search for the files that were uploaded using ftp, the search engine is unable to find the files. -
how to make a modal show using bootstrap in django
i have a modal that contains a list and on the click button it must show the problem is that once i click the button the modal doesn't show instead it display a shadow i know that by default the modal is hidden and i need jquery in order to make it show and display its content. update2.html <div class="modal fade" id="modalCart" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <!--Header--> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Your Result</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <!--Body--> <div class="modal-body"> <table class="table table-hover"> <thead> <tr> <th>ID</th> <th>Number</th> <th>Title</th> <th>Type</th> <th>Content</th> <th>User</th> </tr> </thead> <tbody> {% for folder in FilterRecords %} <tr align="center"> <td>{{ folder.id }}</td> <td>{{ folder.FolderNum }}</td> <td>{{ folder.FolderTitle }}</td> <td>{{ folder.Type }}</td> <td>{{ folder.Content }}</td> <td>{{ folder.user}}</td> </tr> {% endfor %} </tbody> </table> </div> <!--Footer--> <div class="modal-footer"> <button type="button" class="btn btn-outline-primary" data-dismiss="modal">Close</button> <button class="btn btn-primary">Checkout</button> </div> </div> </div> </div> base.html <form class="form-inline" id = "folderSearch" method="GET" action="{% url 'search_folder' %}"> <input class="form-control mr-sm-2" type="text" placeholder="عما تبحث؟" name="searchFolder" value="{{request.GET.searchFolder}}"> {%include 'blog/update2.html' %} <a href="{% url 'update2'%}" class=" btn btn-danger confirm-search" title="Search" data-toggle="modal" data-target="#modalCart" id="searchButton">search </a> </form> <script type="text/javascript"> $(document).ready(function(){ $(document).on('click', '.confirm-search', function () { $('#modalCart').modal('show'); }); }) </script> -
Can't connect to MySQL while building docker-compose image
I have a next configuration of docker-compose, and on duiling db step,django management says next: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") I think - the docker refusing connections. Configuration by socket simillar not working (Says "error connection by socket") docker-compose.yml version: '3' services: db: image: mariadb:5.5 restart: always environment: MYSQL_ROOT_PASSWORD: "root" MYSQL_DATABASE: "bh" MYSQL_USER: "root" MYSQL_PASSWORD: "root" ports: - "3302:3306" behealthy_dev: build: . container_name: behealthy_dev expose: - "86" command: python manage.py runserver 0.0.0.0:80 volumes: - /behealthy_dev/ ports: - "86:86" depends_on: - db Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /behealthy_dev WORKDIR /behealthy_dev ADD requirements.txt /behealthy_dev/ RUN pip install -r requirements.txt ADD . /behealthy_dev/ RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py collectstatic --noinput Database settings (settings): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bh', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root', 'OPTIONS': { 'sql_mode': 'traditional', 'init_command': 'SET innodb_strict_mode=1', 'charset': 'utf8mb4', }, }, } Have any solutions? i tryna to resolve from other stack ansver it's not working for me. -
Django: Should I use protected method _meta in Django?
Lately I've been facing several requirements of getting object data. They can easily be found by accessing protected method _meta. This method has been widely used across the community, but to me it's against the idea of protected method. Even Jetbrains is complaining about using it. I'm working with Django admin. So here are my questions: Is it still the case to use it or is it better to not use it? Without _meta, how do we have equivalent methods such as get_field? I'm trying these on Django 2.0 with Python 3.6 -
'list' object has no attribute 'select_related' error when using LabelWidget in ModelForm for ModelAdmin
I have problem when trying to override the 'tags' field displaying. I am using django-taggit and django-taggit-labels. Here is the code: # models.py class Cat(models.Model): name = models.CharField(max_length=30) tags = TaggableManager() def __str__(self): return self.name # admin.py from django import forms from taggit_labels.widgets import LabelWidget class ProductAdminForm(forms.ModelForm): class Meta: model = Cat fields = ['name','tags'] widgets = { 'tags': LabelWidget(), } @admin.register(Cat) class CatAdmin(admin.ModelAdmin): form = ProductAdminForm I've taken the approach from https://github.com/bennylope/django-taggit-labels/issues/16 But that doens't work because of error in http://127.0.0.1:8000/admin/exp/cat/1/change/ page. And the page was talking 'list' object has no attribute 'select_related' Here is also one more error information. -
Django: AccessToken matching query does not exist
I am trying to add orders using token authentication but it gives the following error. @csrf_exempt def add_order(request): if request.method == "POST": access_token = AccessToken.objects.get(token=request.POST.get('access_token'), expires__gt=timezone.now()) customer = access_token.user.customer if Order.objects.filter(customer=customer).exclude(status=Order.DELIVERED): return JsonResponse({ 'status': 'failed', 'error': 'Your last order must be completed' }) if not request.POST["address"]: return JsonResponse({ 'status': 'fail', 'error': 'Address is required' }) order_details = json.loads(request.POST['order_details']) order_total = 0 for meal in order_details: order_total += Meal.objects.get(id=meal["meal_id"]).price * meal["quantity"] if len(order_total) > 0: order = Order.objects.create( customer=customer, restaurant_id=request.POST['restaurant_id'], total=order_total, status=Order.COOKING, address=request.POST['address'] ) for meal in order_details: OrderDetails.objects.create( order=order, meal_id=meal['meal_id'], quantity=meal['quantity'], sub_total=Meal.objects.get(id=meal['meal_id']).price * meal['quantity'] ) return JsonResponse({ 'status': 'success' }) -
Django Elasticsearch-dsl Nested Filter
trying to apply nested filter using elasticsearch-dsl in django Here is code i am trying booking_client_email = Document.search().filter(Q("nested", path='company', query=Q("term", company__id=company))).query() I have also tried this Document.search().filter('term', company__id=company).query() And also tried with dot notation -
how to run exsisting django project in docker?
I'm trying to containerize my existing django project, which works just fine in my local machine. dockerfile is as follows: FROM django ADD . / WORKDIR /site RUN pip install django-elasticsearch-dsl==0.5.1 RUN pip install tika==1.19 CMD python manage.py runserver 0.0.0.0:8000 i was able to create an image using : docker build -t test1 . and was able to create a container using the image by command : docker run -d --name test1 -p 8000:8000 test1 as a result, i can see that the container test1 is up and running Now, my understanding is if i do localhost:8000 in my browser, i should be able to see the view the required pages. However, I don't see it. I've have tried similar solutions available in stackoverflow, yet no success. -
Make extra parameters passed in URL as optional
I have this URL path('user/delete/<int:pk>/', views.UserDeleteView.as_view(), name='delete_user'), to delete a selected user via passing the pk of the user to be accessed by the DeleteView . However, I want to delete multiple users by using a form with checkboxes. For that, I have used a separate view. my question is that is there any way that I can make this <int:pk> as optional parameter so that I can use the same view for POST as well as GET requests. Just in case I want to use the POST method for the same URL. Can this be done? Someone said it can be done optional in Ruby on Rails. Is there any way to do this here in Django? -
Make a step form dependent on each other with Django
I am learning to use Django, and I am trying to make a registration form, but I only find how to do it the simple way, with just one step. Two questions: 1 °) How to make a form of three or more steps, where each step depends on the previous to be completed. I cannot fill part two until part one has all the fields filled. 2 °) How to use information from one step in another step? For example: In step 2, according to a field filled in in step 1, the user will be shown different information. If you can give me at least one "way" where I should go, thank you! -
update_or_create causing invalid literal for int() with base 10:
I wrote the following code: def parse_match_data(self, match_data, statistics_data): data = {"all_advanced_fields_populated": True} if(match_data["match_hometeam_halftime_score"] == "" or match_data["match_hometeam_halftime_score"] == ""): data["all_fields_populated"] = False data["home_fh_goals"] = 0 data["home_sh_goals"] = 0 data["away_fh_goals"] = 0 data["away_sh_goals"] = 0 else: data["all_fields_populated"] = True data["home_sh_goals"] = 0 if int(match_data["match_hometeam_score"]) - int(match_data["match_hometeam_halftime_score"]) < 0 else int(match_data["match_hometeam_score"]) - int(match_data["match_hometeam_halftime_score"]) data["away_sh_goals"] = 0 if int(match_data["match_awayteam_score"]) - int(match_data["match_awayteam_halftime_score"]) < 0 else int(match_data["match_awayteam_score"]) - int(match_data["match_awayteam_halftime_score"]) data["home_fh_goals"] = int(match_data["match_hometeam_halftime_score"]) data["away_fh_goals"] = int(match_data["match_awayteam_halftime_score"]) required_keys = ["Ball Possession", "Goal Attempts", "Shots on Goal"] if(statistics_data): for statistic in statistics_data: if(statistic["type"] in required_keys): data["home_" + statistic["type"].lower().replace(" ", "_")] = statistic["home"].strip('%') data["away_" + statistic["type"].lower().replace(" ", "_")] = statistic["away"].strip('%') for key in required_keys: if("home_" + key.lower().replace(" ", "_") not in data): data["home_" + key.lower().replace(" ", "_")] = 0 data["all_advanced_fields_populated"] = False if("away_" + key.lower().replace(" ", "_") not in data): data["away_" + key.lower().replace(" ", "_")] = 0 data["all_advanced_fields_populated"] = False return data def statistics(self, match, fixtures, type): for fixture in fixtures: existing_fixture = Fixture.objects.filter(external_id=fixture["match_id"]) if(not existing_fixture.exists() or (existing_fixture.exists() and existing_fixture.first().total_goals == 0)): home_id = fixture["match_hometeam_id"] away_id = fixture["match_awayteam_id"] league_id = fixture["league_id"] country_id = fixture["country_id"] date = fixture["match_date"] + " " + fixture["match_time"] home_name = fixture["match_hometeam_name"].split(" (")[0] away_name = fixture["match_awayteam_name"].split(" (")[0] league_name = fixture["league_name"] country_name = fixture["country_name"] url = … -
What is the simplest way to handle M2M through fields in wagtail FieldPanel?
I recently added a "through" model to allow sorting connected objects. In the example below, a Stage has an ordered list of Blocks linked through StageBlock (with the StageBlock.order field) @register_snippet class Block(index.Indexed, models.Model): title = models.CharField(max_length=100, verbose_name=_("Block Name")) @register_snippet class Stage(index.Indexed, models.Model): title = models.CharField(max_length=100, verbose_name=_("Stage Name")) blocks = models.ManyToManyField( to="app.Block", blank=True, help_text=_("Blocks associated to this stage"), related_name="stages", verbose_name=_("Blocks"), through="StageBlock", ) panels = [ FieldPanel("title", classname="title full"), FieldPanel( "blocks", widget=autocomplete.ModelSelect2Multiple( url="block-autocomplete", attrs={"data-maximum-selection-length": 3}, ), ), class StageBlock(models.Model): block = models.ForeignKey("app.Block", on_delete=models.CASCADE) stage = models.ForeignKey("app.Stage", on_delete=models.CASCADE) order = models.PositiveSmallIntegerField() The problem is that the related Wagtail admin form breaks, since it tries to associate Block objects to Stage, without providing the "through" model "order" field value. I'm wondering what is the cleanest/least effort solution to allow an ordered selection of elements in the admin panel, then to properly save the Stage instance with its blocks and related stageblocks. For the moment, I will add a custom form to the snippet, and auto-assign the order from the position of blocks in the form data (hoping that it always matches the order of blocks as selected in the fieldpanel). It feels like this use-case could be auto-handled, either by the wagtail-autocomplete plugin, … -
Migrating data from SQLite3 to Postgresql using DBeaver
My project use an SQLite3 DB but now I need to do a migration from SQLite3 to PostgreSQL. I've used DBeaver for do this using the "Import Data" option. At the end of the importation of all the tables from SQLite3 to PostgreSQL I noticed this error when I try to add a new content: IntegrityError at /engine/kernel/keyconcept/add/ duplicate key value violates unique constraint "kernel_keyconcept_pkey" DETAIL: Key (id)=(4) already exists. If I add a new model, into this project, that use the new DB(PostgreSQL) there aren't problems to add contents, but if I use the old models I see the IntegrityError above. I've do a test with a model that have only two rows: with the first attempt I received a same error but for key id 1, with the second attempt I received a same error but for key id 2. When I've tried for the third time I was be able to add the content and the same think happens for the next attempts. So I think that the row counter of the every tables after the migrations never start from the last content but from zero. It strange because previous I've do the same migrations but from … -
Using Django rest framework, How can i get only changed data from table from last API call?
I want to get only those data which is changes in table scene last API call. -
How to store pdf file from the view.py to database
i'm created a html file where i am getting the pdf file using input tag i can't store the pdf file which was post to the view.py from the view.py i need to store the file to the database def home(request): if request.method == 'POST': link_pdf = request.POST.get('pdf_link') file_pdf = request.FILES.getlist('document') I expect to store the pdf file from the view.py to database