Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Direct assignment to the reverse side of a related set is prohibited. Use addresses.set() instead
I am going to create and update nested relationships but it is not working as expected I have a three models User, Profile and Address. Profile model is a FK in Address model profiles/models.py class Address(models.Model): profile = models.ForeignKey(Profile, related_name='addresses', on_delete=models.CASCADE) country = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=100) zip_code = models.CharField(max_length=50) address = models.CharField(max_length=1000) profiels/serializers.py class ProfileSerializer(serializers.ModelSerializer): addresses = AddressSerializer(many=True) class Meta: model = Profile fields = ['gender', 'date_of_birth', 'hometown', 'phone', 'addresses'] def create(self, validated_data): addresses_data = validated_data.pop('addresses') profile = Profile.objects.create(**validated_data) for address_data in addresses_data: Address.objects.create(profile=profile, **address_data) return profile users/serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = User fields = ['id', 'url', 'first_name', 'last_name', 'email', 'password', 'profile'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() Profile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.save() profile.gender = profile_data.get('gender', profile.gender) profile.date_of_birth = profile_data.get('date_of_birth', profile.date_of_birth) profile.hometown = profile_data.get('hometown', profile.hometown) profile.phone = profile_data.get('phone', profile.phone) profile.addresses = profile_data.get('addresses', profile.addresses) profile.save() It is working very well with user and profile I can create and update but when I add addresses it gives me … -
is there any plugin for implement drag and drop image upload?
I wish to implement image upload using drag and drop, may somebody already implemented it. $echo -
Can't load second Highcharts diagram from my Django View
Can't seem the load my second chart diagram on my another carousel page. I'm doing it via response/request from views.py. I was able to display my first diagram but not the second. No errors were displayed when loaded Looked at "How to integrate Django and Highcharts" doc but i don't know how to implement two charts on one page class dashboard_view(View): template_name = 'accounts/dashboard.html' def get(self, request, *args, **kwargs): dataset = Profile.objects \ .values('is_active') \ .annotate(is_active_count=Count('is_active', filter=Q(is_active=True)), not_is_active_count=Count('is_active', filter=Q(is_active=False))) \ .order_by('is_active') categories = list() is_active_series_data = list() not_is_active_series_data = list() for entry in dataset: categories.append('%s Active' % entry['is_active']) is_active_series_data.append(entry['is_active_count']) not_is_active_series_data.append(entry['not_is_active_count']) is_active_series = { 'name': 'Active user', 'data': is_active_series_data, 'color': 'green' } not_is_active_series = { 'name': 'Inactive user', 'data': not_is_active_series_data, 'color': 'red' } chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Active user on Current Platform'}, 'xAxis': {'categories': categories}, 'yAxis': { 'title': { 'text': 'No.of users'}, 'tickInterval': 1 }, 'plotOptions': { 'column': { 'pointPadding': 0.2, 'borderWidth': 0 } }, 'series': [is_active_series, not_is_active_series] } dump = json.dumps(chart) return render(request, self.template_name, {'chart': dump}) def post(self, request, *args, **kwargs): dataset = Department.objects \ .values('department') \ .annotate(IT_count=Count('department', filter=Q(department="IT")), Sales_count=Count('department', filter=Q(department="Sales")), Admin_count=Count('department', filter=Q(department="Admin")), HR_count=Count('department', filter=Q(department="HR"))) \ .order_by('department') categories = list() IT_series_data = list() Sales_series_data = list() … -
Django how to implement pagination if I have data only for a page and total pages num
In my app I have data only for current page and total pages num. I can request data from any page but only for one. How to implement Django pagination in that case? -
Django : IndexError: list index out of range
Getting exception : IndexError django.db.models.sql.compiler in apply_converters IndexError: list index out of range in djagno queryset I am doing this object =Info.objects.get(is_active=False,device_id=device_id) here device_id is long text type in database schema and it is indexed object =Info.objects.get(is_active=False,device_id=device_id) -
My download function saves a file with fixed name
I'm using Django 1.8 with Python 3.6. When I use my download function below, it saves the file with a name fixed to local download directory. But I really want to keep the original name. I can change the browser to open a download manager, but I want to know how to fix this filename to the original one. def download(request): path = "test.jpg" # Original filename that I intend to give. file_path = os.path.join(settings.MEDIA_ROOT,path) print("file_path :", file_path) if os.path.exists(file_path): readFile = open(file_path,"rb") response = HttpResponse(readFile.read()) response['Content-Disposition'] ='attachment; filename'+os.path.basename(file_path) response['Content-type'] = 'image/jpg' return response When I download the file, it is autosaved with a name 'Download.jpg', which is the browser's default directory name. -
Reverse for 'add-subject' with arguments '('',)' not found. 1 pattern(s) tried: ['result\\/add\\-subject$']
i try to show book list of a register class, but i found error. views.py files def subject_list(request): form = ClassSelectForm(request.GET or None) select_class = request.GET.get('select_class', None) if select_class: cls = ClassRegistration.objects.get(id=select_class) subjects = SubjectRegistration.objects.filter(select_class=cls) print('subjects=', subjects) context = {'subjects': subjects} return render(request, 'result/subject-list.html', context) context = {'form': form} return render(request, 'result/subject-list.html', context) models.py files class SubjectRegistration(models.Model): select_class = models.ForeignKey(ClassRegistration, on_delete=models.CASCADE, null=True) subject_name = models.CharField(max_length=45) subject_code = models.IntegerField(unique=True) marks = models.IntegerField() pass_mark = models.IntegerField() add_date = models.DateField(auto_now_add=True) def __str__(self): return self.subject_name -
Django-m2m-using through filter only existing objects
I have two model, Route, Point. between these models I have many-to-many relationship and also for sequencing points on route, I have also another model RoutePointSequence then I could have a m2m with "through". I want restricte this "through" available items to that points, which already exists on a route Second question: Also I need to describe some information about a single part of a route between two point, e.g. distance-btn-points; I made another model for that, but any chance to mix these two "trough" models? -
How to migrate existing django database model(SQLite3) to MYSQL?
How can I migrate my existing database data from default django db - SQLite3 to MYSQL. I'm currently using SQLyog and I want to display all my current data in it. I tried following this solution from What's the best way to migrate a Django DB from SQLite to MySQL?: 1) python manage.py dumpdata > datadump.json 2) Change settings.py to your mysql 3) Make sure you can connect on your mysql (permissions,etc) 4) python manage.py migrate --run-syncdb 5) Exclude contentype data with this snippet in shell python manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() 6) python manage.py loaddata datadump.json ....but this doesnt seem to work. Any suggestions? Im getting this error as well: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") -
Docker/Python/Django astimezone seems to be using DST from past year
I'm converting UTC datetimes to America/Santiago tz using dt.astimezone(my_tz) through a Django manage.py command, but it seems to be using DST from past year. This code shows that DST changes at 12/08/2019, from -4 to -3, but this year this should be happening at 08/09/2019 (https://www.timeanddate.com/time/zone/chile/santiago) import pytz import datetime tz = pytz.timezone("America/Santiago") dt4offset = datetime.datetime.strptime(''.join('2019-08- 10T10:00:00+00:00'.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z') dt3offset = datetime.datetime.strptime(''.join('2019-08- 12T10:00:00+00:00'.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z') now = datetime.datetime.now() print('Now %s' % now) print('UTC: %s -> America/Santiago: %s' % (dt4offset, dt4offset.astimezone(tz))) print('UTC: %s -> America/Santiago: %s' % (dt3offset, dt3offset.astimezone(tz))) It prints: Now 2019-08-08 05:46:27.102422 UTC: 2019-08-10 10:00:00+00:00 -> America/Santiago: 2019-08-10 06:00:00-04:00 UTC: 2019-08-12 10:00:00+00:00 -> America/Santiago: 2019-08-12 07:00:00-03:00 Both of the tz convertions should have an offset of -4, but the second one changes acoording to the DST from 2018. I've coded this in Repl.it and it works as its supposed to: https://repl.it/@alejandrocarrasco/LightcyanHideousFlatassembler I'm running this script from docker-compose exec command. I thought my docker container was outdated but it is ok: docker-compose exec container date Prints 'Thu Aug 8 05:52:25 UTC 2019' (and now() from the code above is also ok). So, I think there is a problem with my server/django config. Both Ubuntu and Docker container have correct dates. … -
How to display username at login link in navbar after user has logged in
I want the login link in navbar to change and display the username of the logged user, Please help how would I achieve that views.py def login_request(request): if request.method == "POST": user_form = AuthenticationForm(request, data=request.POST) if user_form.is_valid(): username = user_form.cleaned_data.get("username") password = user_form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("loststuffapp:IndexView") else: messages.error(request, "Invalid username or password") user_form = AuthenticationForm() return render(request, "loststuffapp/login.html", {"user_form":user_form} ) login.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <p><button class="btn" type="submit" >Login</button></p> <p>If you don't have an account, <a href="/register <strong>register</strong></a> instead</p> {% endblock %} -
Error with "input file" in Django. Does not recognize the file
I have problems working with django images, when selecting an image in the django manager everything works correctly, but when creating my own form it does not work. That is, filling the entire form correctly, selecting the file normally, at the time of submitting the form, does not send it and deselects the file you select, and tells me that said field is required. It makes no sense, I select the image, send the form and tell me that the field is required, and the image I chose is deselected. Here my model: class Course(models.Model): instructor = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200) image = models.ImageField(upload_to = 'course') description = models.TextField() users = models.ManyToManyField(User, related_name = 'get_users') created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['title', 'created'] Here my view: class CourseCreateView(CreateView): model = Course fields = '__all__' template_name = 'courses/course_form.html' success_url = reverse_lazy('home') More explicit example of the problem: Fill in the form correctly: I click on the "Crear"/Create button, and the following happens: It tells me that the field is required and appears in the "I don't choose the file" input, what is happening?