Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When does it make sense to use Django with Dash?
I'm doing a web based project where I am required to use Django as a Web Framework, and Dash as the "front-end" library. The project consists of building an analytics web page. It also does not require scalability. Now, from what I've read Dash is based on Flask, which is already a Web Framework. I've researched this a bit and there's this library that enables the Dash - Django link. Here's my question, I guess; Is there a use case where using the Dash and Django link is better suited than just using Dash? Does it even make sense, since Dash is already based on another Web Framework, Flask? -
Django: Media for Views?
I know the Media class for django forms. I like the simple way to include JS/CSS: class CalendarWidget(forms.TextInput): class Media: css = { 'all': ('pretty.css',) } js = ('animations.js', 'actions.js') Is there a way to use the Mediaclass for class based views, too? -
Django distinct related querying
I have two models: Model A is an AbstractUserModel and Model B class ModelB: user = ForeignKey(User, related_name='modelsb') timestamp = DateTimeField(auto_now_add=True) What I want to find is how many users have at least one ModelB object created at least in 3 of the 7 past days. So far, I have found a way to do it but I know for sure there is a better one and that is why I am posting this question. I basically split the query into 2 parts. Part1: I added a foo method inside the User Model that checks if a user meets the above conditions def foo(self): past_limit = starting_date - timedelta(days=7) return self.modelsb.filter(timestamp__gte=past_limit).order_by('timestamp__day').distinct('timestamp__day').count() > 2 Part 2: In the Custom User Manager, I find the users that have more than 2 modelsb objects in the last 7 days and iterate through them applying the foo method for each one of them. By doing this I narrow down the iterations of the required for loop. However, I want to know if there is a more efficient way to do this, that is without the for loop. -
Django - null value in column "genre" violates not-null constraint
I receive this message when I add new story in django-admin null value in column "genre" violates not-null constraint class Genre(models.Model): name = models.CharField(max_length=255) class Story(models.Model): ... genre = models.ManyToManyField(Genre) -
redirect ftp to html download
I'm writing an interface in django for controlling video hardware. The hardware provides file download over ftp. For django I found an ftp-client , which I customize to my needs. By default the client transfer the files in background directly over python, but I would like redirect the file transfer to html to make it possible to download the file with the browser. Is this possible? At the moment the file transfer looks like: f = open(os.path.join(local_dir_to, item_name), 'wb') try: self._connection.retrbinary('RETR %s' % item_name, f.write) f.close() except ftplib.Error as e: # Remove empty file if `try` block raise error os.remove(os.path.join(local_dir_to, item_name)) -
Assigning django user_groups to the users not working?
Here I am assigning some group to the users and the group has certain permissions.Creating and assigning group to the users works fine. For example I have a group name called developer and inside this group i have set permission for the function below but even after this permission is in developer group and the user has developer role ,the user is getting permission denied 403. How can handle this? views.py I created a new group like this and which works fine permissions = request.POST.getlist('user_permissions') new_group = Group.objects.create(name=group_name) new_group.permissions.set(permissions) messages.success(request, 'New group added.') return redirect('organization:view_user_groups') I assigned group to the users like this: checked_groups = request.POST.getlist('groups') user.save() user.groups.set(checked_groups) I assigned permissions using the permission_required_decorator like this in my functions. @permission_required('organization.view_organizations', raise_exception=True) def view_organizations(request): organizations = Organization.objects.all() return render(request, 'organization/view_organizations.html', {'organizations': organizations}) -
Django search_fields foreign key not working !! please help me
I am using django_rest_api_framework. I need to search foreignkey. My search field is "customer_id" views.py file class DebtListAPIView(ListAPIView): serializer_class = DebtCreateSerializer permission_classes = [IsOwner] filter_backends = [SearchFilter] list_display = ('customer_id',) search_fields = ["customer_id__id"] def get_queryset(self): queryset = Debt.objects.filter() return queryset serializers.py file class DebtCreateSerializer(serializers.ModelSerializer): class Meta: model = Debt fields = ['id', 'user', 'customer', 'debtKey', 'created_userKey', 'total_Debt', 'received_Amount', 'payment_Date', 'description', ] models.py class Debt(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=0, blank=False) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=False, related_name='customer') debtKey = models.UUIDField(editable=False, default=uuid.uuid4, blank=False) created_userKey = models.UUIDField(editable=False, default=uuid.uuid4) total_Debt = models.CharField(max_length=50, blank=False) received_Amount = models.CharField(max_length=50, blank=True) payment_Date = models.DateField(blank=True) description = models.CharField(max_length=500, blank=True) created_Date = models.DateTimeField(auto_now=True) modified_Date = models.DateTimeField(auto_now=True) -
Destination path '/home/matms/django_project/media_root/xxx.jpg' already exists
Everything works on my computer. I uploaded files on server and go from error to error. Proccess stops at first image downloaded. Destination path '/home/matms/django_project/media_root/xxx.jpg' already exists def scrape(request): filelist = glob.glob(os.path.join("/home/matms/django_project/media_root", "*.jpg")) for f in filelist: os.remove(f) old_articles = Weather.objects.all() old_articles.delete() user_prof = UserProfile.objects.filter(user=request.user).first() if user_prof is not None: user_prof.last_scrape = datetime.now(timezone.utc) user_prof.save() session = requests.Session() session.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/"} url = 'https://www.onet.pl/' content = session.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") posts = soup.find_all('div', {'class': 'sectionLine'}) for post in posts: title = post.find('span', {'class': 'title'}).get_text() link = post.find("a")['href'] image_source = post.find('img')['src'] image_source_solved = "http:{}".format(image_source) media_root = '/home/matms/django_project/media_root' if not image_source_solved.startswith(("data:image", "javascript")): #exists = os.path.isfile(media_root+image_source_solved) exists = 1 if exists == 2: pass else: local_filename = image_source_solved.split('/')[-1].split("?")[0]+".jpg" r = session.get(image_source_solved, stream=True, verify=False) with open(os.path.join(settings.MEDIA_ROOT, local_filename), 'wb') as f: for chunk in r.iter_content(chunk_size=1024): f.write(chunk) current_image_absolute_path = os.path.abspath(local_filename) shutil.move(current_image_absolute_path, media_root) new_headline = Headline() new_headline.title = title new_headline.url = link new_headline.image = local_filename new_headline.save() sleep(1) -
How can I import multiple fields from one model to a serializer using onetoonefield relation?
I am trying to access some fields from a model into a serialized using a one to one field relation. I've tried writing multiple onetoone relations inside my model so I can have multiple fields imported using the related names Here is my model class PackageKeywordTracking(models.Model): max_groups = models.PositiveIntegerField(default=1) max_products = models.PositiveIntegerField(default=1) max_competitors = models.PositiveIntegerField(default=3) max_keywords = models.PositiveIntegerField(default=250) package = models.OneToOneField(Package, related_name='package_keywords', null=True, on_delete=models.SET_NULL) And here is my serialized class PackageSerializer(serializers.ModelSerializer ): package_keywords = serializers.SlugRelatedField( read_only=True, slug_field='max_keywords' ) package_competitors = serializers.SlugRelatedField( read_only=True, slug_field='max_competitors' ) class Meta: model = Package fields = ('name', 'title', 'package_keywords', 'slug', 'marketplace', 'package_competitors','price', 'period', 'type_subscription_price', 'currency', 'tranzaction_mode', 'start_date_offer', 'end_date_offer') How can I access the max_competitors and max_keywords fields of the PackageKeywordTracking model in the same time in my PackageSerializer? -
Django - CSV Reader not working if csv file contains a blank line
I have a function in a view that I am using to upload CSV data and write to a DB. The function works properly if the CSV file does not have any blank lines. However, if the CSV file has any blank lines, the function does not read any data at all. Below is the extract of the code: data_set = csv_file.read().decode('utf-8') io_string = io.StringIO(data_set) next(io_string) created = None created_records = 0 for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = GrowerMaster.objects.update_or_create( grower_no =column[0], surname =column[1], name =column[2], initials =column[3], area =column[11], national_id =column[15], contractor =column[21] ) if created: created_records+=1 if created is None: messages.warning(request, "No records were read from file. Please check the file and try again") if created_records > 0: messages.success(request, f"{created_records} new records have been imported successfully") else: messages.warning(request, "No new records were imported.") Where and how can I fix this problem such that a csv file with a blank line can still be processed successfully -
Can header and footer be called from the base?
Currently my dilemma is I want the div in my base.html to be in my home_page.html but I need it around my header, main and footer. This is my base.html <div class="cover-container d-flex h-100 p-3 mx-auto flex-column"> {# header #} {# /header #} {% block content %}{% endblock %} {# footer #} {# footer #} </div> And this is my home_page that extends base. {% extends "../base.html" %} {% load static %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}Home{% endblock %} {% block extra_css %} {# Override this in templates to add extra stylesheets #} {% endblock %} {% block extra_js %} {# Override this in templates to add extra javascript #} {% endblock %} {% block content %} {# html stuff sits in here#} <main role="main" class="inner cover"> {% endblock %} Is there a way to call on the header and footer specifically in the homepage.html? -
Post Multiple Row and return in 1 ID (DJango)
How to post multiple Row in HTML in 1 Day What I've done is the last row in table will the one will post to DB.Pos -
How to format dates and datetime in graphene
I want graphene to output normal date/datetime formats. By default it returns this: `"createdAt": "2019-06-11T05:48:11.023255+00:00",` And I want it to return this: `"createdAt": "11.06.2019 11:48:11",` It seems there is no such option in graphene dictionary, but still I want to use graphene_django.DjangoObjectType to use its Meta class, instead rewrite all fields w/ graphene.ObjectType -
How get an exception if {% url 'some-url-name' as the_url %} fails?
According to the docs of url the_url is empty if the reverse of the url fails: {% url 'some-url-name' as the_url %} In my case I would like to get an exception, since I want my tests to fail if my code is broken. How to store the result of reverse to a variable (and get an exception if the reverse failed)? -
Combining HTML Form to Datatables ajax request
Hi I'm working with djangorestframework-datatables and datatables' JQuery plugin. I'm loading a large table (about 15000 entries, paginated) with the serverSide option enabled. I enabled this option because client side processing was taking too long to load the table (even with deferLoading). I want to retrieve data from the following URL: /api/device_input/?format=datatables&device_id=something // device_id can be 1, 2, 3 and so on. The problem is, I can't figure out how I can dynamically change the device_id parameter. That parameter is definitely user input. Here's how I was previously doing it (with client side processing): 1) User enters device ID into a form. Form gets submitted. 2) Django view takes the POST request and returns the filtered queryset to the template. 3) The queryset populates the HTML table values and datatables handles the rest (pagination etc) But now with server side processing, I don't need the django view to return any querysets. I can just get data through ajax. The behaviour I want is: 1) User opens page, an empty datatable is displayed, with a prompt to enter device ID. 2) User enters device ID, and the datatable is loaded with records for that device id. But the datatables ajax request … -
modify a listview queryset to summarize a table containing columns with same value
I have 2 models; one is for material definition and the other is for stocks tracking. I need a stocks table because there will be same materials with different expiry date. I m using a django generic listview and want to modify queryset to display a summary list of materials quantities will be summed. for expample : stocks_table: name packing_details expiry_date quantity milk 1lt boxes 11/11/2019 30 milk 1lt boxes 12/12/2019 40 after modifiying the queryset : name packing_details quantity milk 1lt boxes 70 is it possible with the generic listview or shoulde i prepare a function based view ? class Material(models.Model): name = models.CharField(max_length=500) packing_details = models.CharField(max_length=500) material_unit = models.CharField(max_length=3) class Stock(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE) expiry_date = models.DateField() quantity = models.DecimalField(max_digits=10, decimal_places=2) price = models.DecimalField(max_digits=10, decimal_places=2) date_created = models.DateField(default=timezone.now) created_by = models.ForeignKey(User, on_delete=models.CASCADE, default=1) class StocksListView(LoginRequiredMixin, ListView): model = Stock context_object_name = 'stocks' -
django.core.signing.BadSignature: Signature is not valid
I have a newsletter feature on my project and when I logged in on the admin and checked the newsletter signups, it returned BadSignature at /admin/sendemail/newsletteruser/ Signature is not valid This is the whole traceback on the CLI Internal Server Error: /admin/sendemail/newsletteruser/ Traceback (most recent call last): File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django_cryptography/core/signing.py", line 223, in unsign version, timestamp, value, sig = struct.unpack(fmt, signed_value) struct.error: bad char in struct format During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/contrib/admin/options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1790, in changelist_view 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/db/models/query.py", line 256, in __len__ self._fetch_all() File "/Users/user/Dev/AML/env/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = … -
Load pandas dataframe in bootstrap table (python -> jquery) through django
I am not sure what is wrong here - I have tried all combinations but can't get it to work ... I have the following. 1/ A view created in Python with a data context variable (django framework) def index(request): # Sim df df = pd.DataFrame() df = df.append({'col1': 'col1', 'col2': 'col2'}, ignore_index=True) # Context context = { 'data': df.to_json(orient='records'), } return render(request, 'index.html', context) 2/ A loader for my dataframe table using "bootstrap-table" (part of index.html) $(function() { $('#datatable').bootstrapTable({ columns: [{ field: 'col1', title: 'col1' }, { field: 'col2', title: 'col2' }], data: [{col1: '1', col2: 'Item1'}] }); }); 3/ Above works just fine with two columns displayed and one row. However, if I replace and use the following it just does not anymore. No specific error but it does not display anything ... $(function() { $('#datatable').bootstrapTable({ columns: [{ field: 'col1', title: 'col1' }, { field: 'col2', title: 'col2' }], data: '{{data}}', // loading from context }); }); -
How to parse the CSV data in HTML page in Django Server?
I have used the following function in views.py def getdata(request): with open('./studata.csv', 'r') as csvfile: csv_file_reader = csv.DictReader(csvfile) records = list(csv_file_reader) count = len(records) return render(request,'showdata.html',{'records':records}) Here is the csv file - Roll,Name,Stream 11,Bedanta Borah,Non-Medical, 1,Varsha Sharma,Non-Medical, 3,Nancy,Commerce, 4,Akshita,Humanities, This data should be displayed in showdata.html. How do I traverse through the data in the HTML page ? -
Managing or creating multiple databases in django
First let me state that I am intermediate in programming and beginner in django. I am trying to create a web application with python using django framework which will be provided to multiple companies. My app will require multiple databases. In this case I am thinking of creating a sign up system where for every primary account a different database will be created (automatically), under that primary account several accounts can be created with different roles. Want to know if it is possible and if it is how should I approach? If anyone can provide any better solution than what I'm thinking, it will be much appreciated. -
Django REST EmailAddress matching query does not exist
I am using django rest-auth and allauth to authenticate users. After successful signup and email verification, I implemented a login view which subclasses rest-auth.views.LoginView like below: class ThLoginView(LoginView): def get(self, request): form = CustomUserLoginForm() return render(request, "users/login.html", context={"form": form}) with my own form: class CustomUserLoginForm(AuthenticationForm): class Meta: model = CustomUser fields = ('email',) The problem is that when I login I get this error: DoesNotExist at /users/login/ EmailAddress matching query does not exist. Another important thing that I have changed is that I am using email as the signup/login rather than the username: Settings.py ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_UNIQUE_EMAIL = True and my user model overwrites AbstractBaseUser like so: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) username = models.CharField(max_length=254, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email The error seems to suggest that the search algorithm is not looking in the right place for the emails. The user's email is definitely entered since I can oversee this in the admin page. why … -
django channels private chat
i am creating a django private chat application using django channels. i am facing the problem about redis. someone told me that redis is not supported in windows OS. can any one have alternate.. settings.py Channel_layer CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } and error shown is connected {'type': 'websocket.connect'} WebSocket CONNECT /chat/abdullah/ [127.0.0.1:55869] Exception inside application: ERR unknown command 'EVAL' File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\utils.py", line 59, in await_many_dispatch await task File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch result = task.result() File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels_redis\core.py", line 429, in receive real_channel File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels_redis\core.py", line 484, in receive_single index, channel_key, timeout=self.brpop_timeout File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels_redis\core.py", line 327, in _brpop_with_clean await connection.eval(cleanup_script, keys=[], args=[channel, backup_queue]) ERR unknown command 'EVAL' WebSocket DISCONNECT /chat/abdullah/ [127.0.0.1:55869] -
Load/dump fixture from/to json string in django unittest
I have a custom model in django with overriden to_python() and get_db_prep_save() methods. I discovered a bug: when dumping and reloading data it was inconsistent. The bug is fixed but I want to unittest it with simple json string. My question is: how can I call loaddata / dumpdata inside unittest. I want to to create following scenarios: from django.test import TestCase class CustomModelTest(TestCase): def test_load_fixture(self): mydata = '[{"model": "some_app.custommodel", "pk": 1, "fields": {"custom_field": "some correct value"}}]' django.some_interface_to_load_fixture.loaddata(mydata) // data could be as json string, file, stream make some assertions on database model custommodel def test_dump_fixture(self): mymodel = create model object with some data result = django.some_interface_to_dump_fixture.dumpdata() make some assertions on result I know there is fixture=[] field which can be used in django unittests, it could solve loading fixtures scenarios. But if someone could point me to some interface to load or dump fixture data on demand it would be great. -
How to call view for Form in Html template
I want to make a html template in which i want to make three form.(A,B,C) 'A' form should load as default and having two button to open form B and C. A form should call view.A and grab data. Now on button click Form B should be load and Fetch data from view.B as same for C <form name='A' > //should call view.A button B <-- should call Form B and form B grab data from B button C <-- should call Form c and form C grab data from C I do not know this is possible or not !! Help!!!! -
Date' value has an invalid date format. It must be in YYYY-MM-DD format
I am using 3 Date-Fields in models.py and after makemigrations, I did migrate and turned into error. Error: django.core.exceptions.ValidationError: ["'Date' value has an invalid date format. It must be in YYYY-MM-DD format."] Even I removed all the model fields on models.py file and then migrated, but still giving the error. Please anyone who know the best solution?