Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why static files and images are not working on my django s3 bucket project?
while trying to use s3 bucket on my local django project it does not work, after moving the static files and images to the s3 bucket it is not rendering any of them. my project structure goes like this Project |-> app-name |-> static | |-> img "folder of png images" | |-> app-name | |-> css "folder contain all css files" | |-> js "folder contains all js files" | |-> img "contains images used for styling" |-> project name |-> manage.py in settings.py "media, static and s3 bucket settings are set like this" STATIC_URL = '/static/' MEDIA_URL = '/img/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img') AWS_ACCESS_KEY_ID = '***************' AWS_SECRET_ACCESS_KEY = '***************' AWS_STORAGE_BUCKET_NAME = 'bucket-name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_HOST = 's3.us-east-2.amazonaws.com' AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' when I try to inspect element to see the src in images or links for css I can see them like this "https://bucket-name.s3.amazonaws.com/gallery/css/bootstrap.min.css" or for image "https://bucket-name.s3.amazonaws.com/stockholm_Samit.jpg" could you please help me with this? -
I am getting a response error in my tests.py file
I am getting an error in my tests.py file when testing my Inspection class. It is located in tests.py and it says that the syntax is invalid on line 30. class HomeTests(TestCase): def setUp(self): Inspection.objects.create(workOrderNum='123DER', partNumber='sd', customerName="RYANTRONICS", qtyInspected=10,qtyRejected=3) url = reverse('home') self.response = self.client.get(url) def test_home_view_status_code(self): self.assertEquals(self.response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_view_contains_link_to_topics_page(self): inspection_topics_url = reverse(inspection_topics, kwargs={'pk': self.inspection.pk} self.assertContains(self.response, 'href="{0}"'.format(inspection_topics_url)) -> this line is the problem, invalid syntax. Can someone show me what this error means, and how to fix it? I never got this error before when I made the Board class on a tutorial site. -
Issue with deploying Django on Heroku
Hi Guys I tried deploying my first django on heroku and i am frequently facing issues with the deployment. I think this is something to do with my settings.py file. I am clearly unaware with this issue python manage.py collectstatic--noinput , but i have written everything . Thanks in Advance for help and ideas. $ python manage.py collectstatic--noinput Traceback(most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_6613795b_/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this … -
Fetch data from Server using Jquery AJAX and then trying to make a url using Jinja 2 format
Hello Everyone i am Trying to Get Data Using Api from the Server and Then Render it in Jinja2 Template Page but i dont know how to pass the item.id in it. the Code is bellow kindly help me with this $.get("http://127.0.0.1:8000/api/product",function(data){ $.each(data,function(index,item){ var obj="<div class='col-lg-3'>"+ "<div class='card shop-hover'>"+ "<img src="+item.image[0]+" style='height:250px;' alt='wrapkit' class='img-fluid' />"+ "<div class='card-img-overlay align-items-center'>"+ "<a href='{% url 'Checkout' item.id %}' class='btn btn-md btn-info-gradiant'>Buy Now</a>"+ "</div>"+ "<span class='label label-rounded label-success'>Sale</span>"+"</div>"+ "<div class='card'>"+ "<h6><a href='#' class='link'>"+item.Name+"</a></h6>"+ "<h6 class='subtitle'>"+item.BottomHeading+"</h6>"+ "<h5 class='font-medium m-b-30'>"+item.UnitPrice+" / <del class='text-muted line-through'>$225</del></h5>"+ "</div>"+ "</div>"; $(".shop-listing").append(obj); }); }); And this is the line of Code Where i am getting Trouble "<a href='{% url 'Checkout' item.id %}' class='btn btn-md btn-info-gradiant'>Buy Now</a>" Thanks in Advance! -
resolve the metaclass conflict
Actually I got the following error and honestly, I'm a newbie with the metaclass errors if anyone could help me to solve the following error. view.py class EditView(CustomizedRequiredMixin(account_type=Account.SELLER_ACCOUNT), UpdateView): pass decorators.py class CustomizedRequiredMixin(AccessMixin): def __init__(self, account_type=None): self.account_type = account_type def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() if self.user_has_permissions(request, self.account_type): return super().dispatch(request, *args, **kwargs) raise Http404 def user_has_permissions(self, request, account_type): account = request.user.account if account_type == Account.SELLER_ACCOUNT: return account and account.account_type == Account.SELLER_ACCOUNT if account_type == Account.BUYER_ACCOUNT: return account and account.account_type == Account.SELLER_ACCOUNT got the following error: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases -
How to create superuser in django using Unix Environment
when I'm using Visual Studio Code for the Django project in windows Environment, for creating a superuser I'm using the below command. (test) C:\Users\SAHEB\projects\project>python manage.py runserver this same Django project is deployed in Unix server, below is the path where whole project is deployed. /apps/sample/python but python manage.py runserver this command is not working in Unix server from this path, what's the solution -
For Update operation how can you only update some data Django and not all?
I want to update only some of the data in a model. Suppose a Django model is as such: class Test(model.models): name = models.CharField(max_length=10) desc = models.CharField(max_length=100) When I want to update the data using a view in Django Rest Framework, how can I update only name and not description. Right now if I send a PUT request it throws an error that desc is a required field. Here is my view? class Test_ListView(APIView): def get(self, request, format=None): db_data = Test.objects.all() serializer = Test_Serializer(db_data, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = Test_Serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Test_DetailView(APIView): def get_object(self, pk): db_data = Test.objects.get(pk=pk) try: return db_data except Test.DoesNotExist: raise Http404 def get(self, request, pk, format=None): db_data = self.get_object(pk) serializer = Test_Serializer(db_data) return Response(serializer.data) def put(self, request, pk, format=None): db_data = self.get_object(pk) serializer = Test_Serializer(db_data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): db_data = self.get_object(pk) db_data.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
How can I filter django queryset with the gap between different date field?
Say there's a table to collect spend value: class AccountsInsightsHourly(models.Model): account_id = models.CharField(max_length=32, blank=True, null=True) account_name = models.CharField(max_length=255, blank=True, null=True) account_create_time = models.DateTimeField(blank=True, null=True) account_status = models.IntegerField(blank=True, null=True) spend_cap = models.BigIntegerField(blank=True, null=True) balance = models.BigIntegerField(blank=True, null=True) spend = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) vertical = models.CharField(max_length=32, blank=True, null=True) date = models.IntegerField(blank=True, null=True) hour = models.IntegerField(blank=True, null=True) created_time = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'accounts_insights_hourly' unique_together = (('account_id', 'date', 'hour'),) ordering = ["account_id", "-hour"] The data saved as id account_id spend ... hour date 1 1233222 1000 10 20200819 2 1233222 2000 18 20200819 3 1233222 3000 10 20200820 4 1233222 4000 18 20200820 ... My question is how can I filter all data whose spend is more than yesterday (the final spend for yesterday should be same with lastest hour 18) # for account 1233222 # the lastest spend for yesterday is 2000 # Then if the spend for today (3000) is over 2000 , then this account 1233222 should be filtered. How can I use a queryset filter condition to get the expected result. Great Thanks. -
Save formset in Django returns None model
I've a problem with my formset. When I submit the formset, the models are not saved and displayed as None. I don't understand why, can somebody light me ? There is no problem in the template nor the urls.py. I get this within my log console: See image Here is my code: // views.py def classroom_call_the_roll(request, class_id): classroom = Classroom.objects.get(pk=class_id) students = classroom.students.all() queryset = Attendance.objects.none() AttendanceFormset = modelformset_factory( model=Attendance, form=AttendanceForm, can_delete=False, extra=len(students) ) if request.method == 'POST': formset = AttendanceFormset( request.POST, queryset=queryset, initial=[{'student': student} for student in students] ) for form in formset.forms: instance = form.save(commit=False) print(instance) else: formset = AttendanceFormset( queryset=queryset, initial=[{'student': student} for student in students] ) return render( request, 'highschool/attendance/classroom_attendance_create.html', { 'formset': formset } ) -
Django update GenericForeignKey after object creation
Even if I am an experienced developper, I am pretty new in Python/Django, I probably missed to do something or perhaps I am trying to make something impossible... I'm using Django 3 with Python 3.7 Summary: I have a model A with a GenericForeignKey to a model B or a model C. When I set the link, the object A might already exist in the database, so I call a "get_or_create" method to reatreive the object if it is already exist or create a new one if it doesn't existe yet. Just after the "get_or_create", I set the link to an another object. I tried to set the link with many ways from instance of object A to an instance of object B but every time I have an error, I looked for some examples to know how to set the GenericForeignKey link when the model is already instanciate but I didn't found it. What I tried: The last version of my code : For class A : from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class A(models.Model): # ... number = models.IntegerField( 'Number', editable=False, default='-1' ) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) object_id = models.PositiveIntegerField(null=True) object_srce … -
How do I use the existing tables in Postgre DB and use them in Django
I'm new to Django and i'm trying to build a web console for the users who can view, insert/update/delete data to PostgreSQL DB. I have couple of tables already created which i want to use. I have used below command to inspect the tables and use them in Django models $ python manage.py inspectdb bkp_fulfilment_product_provider > models.py When I run the above command I get a error as below: Error: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each `ForeignKey` and `OneToOneField` has `on_delete` set to the desired behaviour # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from `django.db` import models # Unable to inspect table bkp_fulfilment_product_provider # The error was: syntax error at or near `WITH ORDINALITY` LINE 6: FROM `unnest(c.conkey)` WITH ORDINALITY co... Thanks Kiran Thota -
Connect data (collected before user is logged in) to user account (after user logs in) - Django
I am working on a Django project where a quiz is taken when someone visits the website. The visitor answers all the questions and then the result is generated. But the user needs to log-in/signup to see the result. When the user submits the quiz, data is stored in the quiz table which has a foreign key of the user model. My question is how can I link that quiz table object to the user account when they log in or register to see the result? """ quiz model class Quiz(models.Model): ques2 = models.CharField(max_length=1000, choices=choices, default="", verbose_name = "I've always dreamed of") ques3 = models.CharField(max_length=1000, choices=choices, default="", verbose_name = "I prefer to") ques4 = models.CharField(max_length=1000, default="", verbose_name = "I want to earn") ques9 = models.CharField(max_length=1000, default="", blank=True, verbose_name = "How would you describe your personality?") ques10 = models.CharField(max_length=1000, default="", blank=True, verbose_name = "What are your goals?") result = models.ForeignKey(Moneymaker, on_delete= models.CASCADE, blank=True, null=True, default="", related_name='result') user = models.ForeignKey(User, on_delete= models.CASCADE, blank=True, null=True) """ -
How to list all users to the template in Django?
I want to display all users nicknames to the template, but i am not sure, how to work with django build-in views. Can someone help me to figure out. views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post class UsersView(TemplateView): template_name = 'blog/user_search.html' def get_context_data(self,**kwargs): context = super(UsersView,self).get_context_data(**kwargs) context['object_list'] = User.objects.all() return context template {% extends "blog/base.html" %} {% block content %} <h1>Search page</h1> {% for user in object_list %} <li class="user">{{ user }}</li> {% endfor %} {% endblock content %} models.py class Post(models.Model): #users = [str(user) for user in User.objects.all()] field_choices=(('art','art'), ('producing','producing')) title = models.CharField(max_length=100) content = models.TextField() field=models.CharField(max_length=100, choices=field_choices, default='general') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Code works but it does not show anything to the template, I supposed that i should combine Templateview with ListView but i am not sure how to do it correctly. Tahnk you in advance! -
unable solve this installation error in django?
How to solve this error while installing Django in a virtual environment? enter image description here -
Python- Django (def was_published_recently(self):) [closed]
n How can I check it's true or not? def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) -
Unable to launch Jupyter Note from Anaconda Navigator(Windows)
I launch anaconda from the command prompt using this code anaconda-navigator However, when I try to launch Jupyter Notebook from Anaconda, I receive this error code. Could someone help, please? C:\Users\mxixq\anaconda3\lib\site-packages\setuptools\distutils_patch.py:25: UserWarning: Distutils was imported before Setuptools. This usage is discouraged and may exhibit undesirable behaviors or errors. Please use Setuptools' objects directly or at least import Setuptools first. warnings.warn( Traceback (most recent call last): File "C:\Users\mxixq\anaconda3\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\mxixq\anaconda3\lib\site-packages\notebook\notebookapp.py", line 49, in from zmq.eventloop import ioloop File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq_init_.py", line 50, in from zmq import backend File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 40, in reraise(*exc_info) File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise raise value File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 27, in ns = select_backend(first) File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend\select.py", line 28, in select_backend mod = import(name, fromlist=public_api) File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init.py", line 6, in from . import (constants, error, message, context, ImportError: cannot import name 'constants' from partially initialized module 'zmq.backend.cython' (most likely due to a circular import) (C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init_.py) -
Django admin default autocomplete filter not working
Django 2.* admin default autocomplete field not working with filter. Is there are any temporary fix until django fix this issue? Thanks -
How to add tinymce to django form
I want to add tinymce to a user form and not the admin site, how can I make it? here is a variable of my model that shows tinymce only in the admin page: text = HTMLField('body',max_length=4000) -
TypeError: User() got an unexpected keyword argument 'confirm_password'
I want to add password field and confirm_password field to my UserSerializer. I wrote a function called create to create a hashes password for my password field but before it can create the hashes password I want it to make sure that confirm_password and password are matched. The code works fine if I remove the confirm_password field. What is the problem? My serializers.py # serializer define the API representation class UserSerializer(serializers.HyperlinkedModelSerializer): # password field password = serializers.CharField( write_only = True, required = True, help_text = 'Enter password', style = {'input_type': 'password'} ) # confirm password field confirm_password = serializers.CharField( write_only = True, required = True, help_text = 'Enter confirm password', style = {'input_type': 'password'} ) class Meta: model = User fields = [ 'url', 'first_name', 'last_name', 'email', 'password', 'confirm_password', 'is_staff' ] def create(self, validated_data): if validated_data.get('password') != validated_data.get('confirm_password'): raise serializers.ValidationError("Those password don't match") elif validated_data.get('password') == validated_data.get('confirm_password'): validated_data['password'] = make_password( validated_data.get('password') ) return super(UserSerializer, self).create(validated_data) error I got TypeError: User() got an unexpected keyword argument 'confirm_password' [20/Aug/2020 16:15:44] "POST /users/ HTTP/1.1" 500 168152 I can edit the question if you need more detail. Ty! -
Django - How to do scoring in a quiz app with multiple attempts
I am making a quiz app in Django and struggling with the scoring. This is my model setup: class Quiz(models.Model): song = models.ForeignKey(Song, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=15) slug = models.SlugField(unique=True, max_length=250) questions_count = models.IntegerField(default=0) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) label = models.CharField(max_length=1000, help_text="Enter the question text that you want displayed") class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=100) is_correct = models.BooleanField('Correct answer', default=False) class QuizTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) correct_answers = models.IntegerField(default=0) completed = models.BooleanField(default=False) attempt_number = models.AutoField(primary_key=True) In my html, the quiz is displayed as follows: {% for q in question_list %} {{q}} <br> {% for choice in q.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.answer }}"> <label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br> {% endfor %} <a class='btn btn-warning save_ans' href="#">Save answer</a> The answer to every question is handled via an ajax call and sent to the following view: ans_given = [] def save_ans(request): ans = request.GET['ans'] ans_given.append(ans) return HttpResponse(ans) I've approached the scoring as follows: ans_correct = [] answers = models.Choice.objects.filter(is_correct=True) for i in answers: scoring['ans_correct'].append(i.answer) def quiz_results(request, pk): score = 0 quiz = models.Quiz.objects.get(song__pk=pk) count = quiz.questions_count questions = models.Question.objects.filter(quiz=quiz) for i in range(len(questions)): if ans_given[i] == ans_correct[i]: … -
Django rss media content parsing
Need help please. I am trying to build an rss-based feed in django. But I am finding media:content (url, medium, height and width) to be tricky. I have looked and looked, and ended up with this: class CustomFeed(Rss201rev2Feed): def add_item_elements(self, handler, item): super().add_item_elements(handler, item) handler.addQuickElement("image", item["image"]) class Rss(Feed): feed_type = CustomFeed title = "#Title to the item" link = "/feeds/" description = "#Description to the item" def item_extra_kwargs(self, item): img_url = item.image.medium.url request_url = self.request.build_absolute_uri('/')[:-1] image_url_abs = f"{request_url}{img_url}" return { 'image': image_url_abs } But this gives me the image as standalone in the rss feed: <image>https://www.url.com/image.jpg</image> i badly need the code to return this: <media:content url="https://www.url.com/image.jpg" medium="image" height="640" width="362"/> please help. -
Django When conditional expression with Exists subquery in django 2 raise: TypeError: cannot unpack non-iterable Exists object
models.py class PersonPhoneQuerySet(models.QuerySet): def with_bill_sums(self, bill_date_from: datetime.date, bill_date_till: datetime.date): return self.annotate( sum_all=Coalesce( Sum('telephone__bill__value', filter=Q( telephone__bill__dt__gte=bill_date_from, telephone__bill__dt__lte=bill_date_till, )), Value(0) ), sum_service=Coalesce( Sum( Case( When( Q( Q(Exists(Telephone.objects.filter(num=OuterRef('telephone__bill__call_to')))) | Q(telephone__bill__bill_type=BillType.INTERNET) | Q(telephone__bill__bill_type=BillType.PAYMENT) | Q(telephone__bill__call_to=BILL_IN_ROAMING_AON_TEXT), telephone__bill__dt__gte=bill_date_from, telephone__bill__dt__lte=bill_date_till, ), then='telephone__bill__value'), default=0, output_field=models.DecimalField() )), Value(0) ), ) class Telephone(models.Model): num = models.CharField('Номер', max_length=50, unique=True) sim = models.CharField('SIM карта', max_length=50, blank=True) class Person(models.Model): fio = models.CharField('ФИО', max_length=50) email = models.EmailField('Email', null=True, blank=True) class PersonPhone(models.Model): BIG_DATE = datetime.date(3333, 1, 1) objects = PersonPhoneQuerySet.as_manager() telephone = models.ForeignKey(Telephone, models.CASCADE, verbose_name='Телефон') person = models.ForeignKey(Person, models.CASCADE, verbose_name='Сотрудник') date_from = models.DateField('Начало периода привязки') date_till = models.DateField('Конец периода привязки', default=BIG_DATE) limit = models.IntegerField('Лимит', default=0) tariff = models.CharField('Тариф', max_length=20, blank=True, default='') class Bill(models.Model): telephone = models.ForeignKey(Telephone, models.CASCADE, verbose_name='Телефон') bill_type = models.DecimalField('Тип соединения', choices=BillType.choices, db_index=True, max_digits=1, decimal_places=0) dt = models.DateTimeField('Дата и время звонка') value = models.DecimalField('Стоимость', max_digits=10, decimal_places=4, default=0) call_to = models.CharField('Вызываемый абонент', max_length=32, blank=True, default='', db_index=True) duration = models.DecimalField('Продолжительность, сек', max_digits=8, decimal_places=0, null=True, blank=True) call_direction = models.CharField('Направление соединения', choices=CallDirection.choices, max_length=1, default=CallDirection.UNDEFINED) Run: from apps.mobile import models, consts from common_tools.date import last_day_of_month date_from = datetime.datetime(2020, 5, 1) date_till = last_day_of_month(date_from) qs = models.PersonPhone.objects.filter( person__fio__icontains='SomeMan', telephone__num__icontains='+79655171234', date_from__lte=date_from, date_till__gte=date_till, ).with_bill_sums(date_from, date_till) for i in qs: print( i, '\n sum_all: {}'.format(i.sum_all), '\n sum_service: {}'.format(i.sum_service), ) It works on django … -
Figuring out problematic brackets
Hi I have the following scenario: import queryString from 'query-string'; data = {key: ['a', 'b']} axios.get('url', { params: data, paramsSerializer: function(params) { return queryString.stringyfy(params, {arrayFormat: 'brackets'}) }, headers: headers } On my django end when i get this: request.GET = <QueryDict: {'key[]': ['a', 'b']} > I am not sure how the mysterious '[]' came about and when i followed online solutions to use queryString, it does not seem to work. Thanks -
COPY .tar.gz needed in Dockefile or not?
Docker newbie here, quick question about the COPY command while dockerizing Django. I thought the COPY command is used to copy over a local file into the Docker container/context or else, as far as Docker is concerned, during the build the file does not exist. The development Dockerfile from the tutorial I'm following had this section: # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt So I understood that without that COPY command during the build the second RUN command would fail because it has no idea what requirements.txt is. Therefore, since I wanted to install my django-polls app tarball, I added a COPY and tacked on the phrase to the second RUN: # install dependencies COPY ./requirements.txt . COPY ./django-polls-0.1.tar.gz . RUN pip install --upgrade pip && pip install -r requirements.txt && pip install django-polls-0.1.tar.gz As you can see, I combined the two RUN commands, added the COPY .tar.gz line, and tacked the .tar.gz installation on to the end of the RUN command. So I have 2 questions, the second one being more of the focus of this post: Was it necessary to move the pip install --upgrade pip into the final … -
Django keeps recreating foreign key field for legacy database with migrations command
I,m quite new to Django development. I,m working with a legacy database created with MySQL. Now I,m facing a problems with Django migrations. I have few tables that are using foreign keys for the reference to another table. Now if I allow Django to manage those tables with foreign keys, then Django tries to recreate the foreign key fields during make-migrations and migrate command. Even when the fields are already there. Besides this Django is working perfectly with the database if I don't allow Django to manage those table. My Code is for table facing error Models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.db.models.signals import pre_save from chooseright.utils import unique_slug_generator class StoreTable(models.Model): store_id = models.AutoField(primary_key=True) name = models.CharField(max_length=45, blank=True, null=True) slug = models.SlugField(max_length=45, blank=True, null=True) catagory = models.ForeignKey(CatagoryTable, on_delete=models.CASCADE, blank=True, null=True) brand = models.ForeignKey(BrandTable, models.DO_NOTHING, blank=True, null=True) class Meta: managed = True db_table = 'store_table' verbose_name = _("Store") verbose_name_plural = _("Stores") def __str__(self): return self.name Migration Code from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0009_auto_20200820_1258'), ] operations = [ migrations.RenameField( model_name='storetable', old_name='store_name', new_name='name', ), migrations.AddField( model_name='storetable', name='brand', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='core.BrandTable'), ), migrations.AddField( model_name='storetable', name='catagory', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.CatagoryTable'), …