Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django pagination with multiple lists
I am using Django pagination.There are 2 scenarios When user lands on this page the result set returns pre-filtered results so I don't necessarily need to paginate the results. When user turns off filters,I need to show all results( this is when I need to paginate,10000 s of records) Those records come to view in form of different lists And I send the result as a zipped format. I am not able to paginate through more than 1 list/result set. -
django python DateTimeField different from admin input and database
I have django app that submit date from the admin.py. here my models.py class Attendance(models.Model): datetimes = models.DateTimeField('Tanggal') uid = models.ForeignKey(Employee, related_name='employeeattedance') here the result: there are different from the admin (local time) and my database. why this happen?... -
django with mysql model string array field
I need to design a model Card that should expect a request like following: {"thing":"Book","responsibilities":["Name","ISBN"],"collaborators":[""]} So far I designed my model like following: class Responsibility(models.Model): name = models.CharField(max_length=50, blank=True, null = True, ) class Collaborator(models.Model): name = models.CharField(max_length=50, blank=True, null = True, ) class Card(models.Model): thing = models.CharField(max_length=50, blank=True, null = True, ) responsibilities = models.ForeignKey(Responsibility, related_name='res_cards', blank=True, ) collaborators = models.ForeignKey(Collaborator, related_name='col_cards', blank=True, ) but somehow having name attribute on other two models seems unnecessary for such a simple case. Can I design my model better to accept request like above? -
How to test the result of catching an exception in python / django view
Given a view that creates an object from a model that has a "unique_together" for two fields using the following code: def form_valid(self, form): field1 = form.cleaned_data['field1'] field2 = form.cleaned_data['field2'] try: TheModel.objects.create(org=self.request.org, field1=field1, field2=field2) except IntegrityError as e: if 'UNIQUE constraint' in e.message: messages.error(self.request, _('field1 already exists.')) return super(ModelFormMixin, self).form_valid(form) messages.success(self.request, _('Fields have been successfully updated.')) return super(ModelFormMixin, self).form_valid(form) How might I unit test that the error message gets displayed when the 'unique_together' throws an error? My current test throws a TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. Here is the current test: @patch.object(messages, 'error') def test_error_handling(self, error_mock): TheModel.objects.create(org=self.org, field1='somepath', field2='anotherpath2') with transaction.atomic(): response = self.client.post(reverse('configurations.create_amodel', args=(self.org.slug,)), {'field1': 'somepath', 'field2': 'anotherpath'}, follow=True) self.assertTrue(error_mock.called) I cannot figure out how to make the test work (testing the code that is run when the exception is caught) -
Docker error with pipenv on django app: Warning: --system is intended to be used for pre-existing Pipfile
When I was trying to dockerize my django app, I followed a tutorial telling me to structure my Dockerfile like this FROM python:3.6 ENV PYTHONUNBUFFERED 1 COPY . /code/ WORKDIR /code/ RUN pip install pipenv RUN pipenv install --system EXPOSE 8000 After I saved that and run docker build . the system threw me this error Warning: --system is intended to be used for pre-existing Pipfile installation,not installation of specific packages. Aborting. I think it is complaining about the --system suffix above but the tutorial says it's crucial to have it so that my packages are applied in the entire docker container. I'm new to docker and even pipenv because I took over a previous person's code and isn't sure where their pipfile is or even if they have a pipfile. If you have any insights on how to fix this error thank you in advance. -
Django load word2vec model in a django view
I have a pre -trained Word2Vec model and I 'd like to use it in a django view so i have to load it in cache in order to use it in a view but i dont know how !! what i'm tryning to do is to find similair words corresponding to a query given by user in a form then rise searchusing with the resulting similair words in a data base index . -
Panzoom on django with jquery
I have a really basic django app that displays .png images and ask the user to vote on different choices. Now I need to make it interactive so that the user can also zoom and pan the image. I have never done web apps before and I am not used to javascripts. The only thing I understood is that I should download this package https://github.com/timmywil/jquery.panzoom which I did with npm and now I have a folder with /node_modules/jquery.panzoom/ with folders 'dist', 'src'... in it containing the js files. Now I should load the js in my html templates right? But I think I've missed something since It seems to simple and doesn't work. I've red that I have to initialize with some script code but I don't understand where to put this: $(".panzoom-elements").panzoom(); // Pass options $("a.panzoom-elements").panzoom({ minScale: 0, $zoomRange: $("input[type='range']") }); Thanks in advance for your help. -
Group by object's field and return list of object or object's id for each group
class Ticket(models.Model): booked_at = models.DateTimeField(default=timezone.now) bought = models.BooleanField(default=False) I would like to group tickets by booked day to get list of ticket or ticket's id for each day. Something like this: [ { 'day': datetime.datetime(2018, 5, 6, 0, 0, ...>), 'ticket_list': [1, 2, 3, 4], }, { 'day': datetime.datetime(2018, 5, 7, 0, 0, ...>), 'ticket_list': [5, 6, 7, 8, 9], } ] I could group tickets by day this way and count total tickets per day, Ticket.objects.filter(bought=True).annotate(day=TruncDay('booked_at')).values('day').annotate(c=Count('id')).order_by() But I cannot figure out how to group by day and return ticket objects for that day. Could you please help me solve this. Thank you -
Django Rest Framework, Swagger and CORS
I'm working on a project in Django 1.6 with integrated Django Rest Swagger. When developing on local machine or running project from docker container Swagger displays endpoint descriptions properly, but when opening project on a remote server I'm receiving: Can't read from server. It may not have the appropriate access-control-origin settings. From questions with similar problem I've found out that this problem may be solved by installing django-cors-headers. I've added corsheaders to INSTALLED APPS and 'corsheaders.middleware.CorsMiddleware' to MIDDLEWARE_CLASSES, but I'm still receiving the same message as before, how should I configure corsheaders to resolve this issue? -
ForeignKey Inline dropdown menu in Django admin
I have a project with the following models class Recipe(models.Model): title = models.CharField("Title", max_length = 200, blank=False) content = RichTextUploadingField("Content") class Tag(models.Model): name = models.CharField("Tag", max_length = 50) recipe = models.ForeignKey(Recipe) and the following admin.py class TagInline (admin.StackedInline): model = Tag class RecipePage(admin.ModelAdmin): list_display = ('title') list_display_links = ('title') fields = ('title', 'content') list_per_page = 25 inlines = (TagInline) For each inline, I would like Django's admin to show a list of tag names as a drop-down menu, based on the tags that have already been entered. Of course, users must be able to add a new tag name, as a tag object, if no suitable tag exists already. I can achieve this quite easily without inline, but with it, I'm not able to. Any ideas? -
Django ORM: Get distinct related objects from queryset
I have models: class Profile(models.Model): pass class Category(models.Model): pass class Course(models.Model): categories = models.ManyToManyField('Category', blank=True) students = models.ManyToManyField(Profile, related_name='subscribed_courses', blank=True) I want to get unique categories as QuerySet object from courses on which student is subscribed I tried: Categories.objects.filter(course__in=student_obj.course_set.all()).distinct() and got empty queryset. How can I get these categories ? -
Reverse relationship for OneToOneField Django?
I am using User model from django.contrib.auth.models import User UserProfile model extends User model class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofiles') avatar = models.FileField('img',upload_to='./static/image/') I need to take user's avatar, I am doing something like user = User.objects.get(pk=1) user.userprofile But it throws me error RelatedObjectDoesNotExist: User has no userprofile. Please correct me if i am wrong. Thank you in advance !!! -
Login Validation - error messages - always the same
I use last version of Django 2.05. I created a custom user model: class User(AbstractBaseUser, MermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=False) # can't login class ULoginForm(AuthenticationForm): # we declared this way to override the AuthenticationForm fields username = UsernameField(max_length=254, widget=TextWidget(attrs={'autofocus': True, 'placeholder': 'Email*'})) password = forms.CharField(strip=False, widget=PasswordWidget(attrs={'placeholder': 'Password*'})) The problem is that I always get the same error message in case of validation error: Please enter a correct email and password. Note that both fields may be case-sensitives. If the user/password are correct an account not active I expect to receive 'invalid account' but I receive the above message. -
How can i make my own scraping website with Django and scrapy?
i began making a website using DJango girls tutorial ,, just like this website ,, replacing title with" URL how can i click on scrape ,i launch my spider and save the data in other page ? this is my spider : import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://quotes.toscrape.com/page/1', ] def parse(self, response): for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').extract(), 'author': quote.css('small.author::text').extract(), 'tags': quote.css('div.tags a.tag::text').extract(), } for a in response.css('li.item a'): yield response.follow(a, callback=self.parse) and how can i make the url a variable ,, the one i enter in the website is the one in the spider "starts_url" ?? -
How to integrate postgREST with Django
I am fairly new to Django and looking for an API to access postres DB in Django. I tried to find the solution for integrating postgREST in my Django project, but couldn't find any solution. I would like to have some direction on how to integrate postgREST in Django, or if i can use some other API. Thanks in advance. -
type="datetime-local" in Django form
I want to understand Django form. <div class="form-group"> <label for="deadline">Deadline</label> <input type="datetime-local" class="form-control" id="deadline" aria-describedby="deadlineHelp" placeholder="Enter when deadline"> </div> I want to create this field with Django. But < form action = "" method = "post" > { % csrf_token %} {{form.as_p}} < / form > to create a simple lines. And if I fix forms.py like class Create(forms.ModelForm): class Meta: model = Task fields = ('deadline_task',) widgets = { 'deadline_task': forms.DateTimeInput(), } It not working. <p><label for="id_deadline_task">Deadline task:</label> <input type="text" name="deadline_task" id="id_deadline_task"></p> I just want <input type="datetime-local" - It convenient to select a date. Thank you. P.S. Django 1.11 -
TypeError: delete() missing 1 required positional argument: 'pk' django
i have a view in my django app which looks like following class DeployedContractsList(APIView): def get_Contract(self, address): contracts = DeployedContracts.objects.all() if address: contracts = contracts.filter( Q(deployed_contract_address__iexact=address) ) return contracts def get(self, request, email, format=None): service_providers = self.get_queryset(email) serializer = DeployedContractsSerializer(service_providers, many=True) return Response(data=serializer.data) def delete(self, request, pk, format=None): item = self.get_Contract(address=pk) item.delete() return Response(status=status.HTTP_204_NO_CONTENT) and i have configured my app urls in following way router = DefaultRouter() urlpatterns = [ url(r'^(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', views.DeployedContractsList.as_view()), url(r'^(?P<pk>)/$', views.DeployedContractsList.as_view()), url(r'^', views.DeployedContractsList.as_view()) ] and project's urls.py i have following configurations urlpatterns = [ path('admin/', admin.site.urls), url(r'^deployedcontracts', include('deployedcontracts.urls')), ] but upon making a delete request by http://127.0.0.1:8000/deployedcontracts/0xe9114368611e9f20cf46b76aa33319fc0ce0b585/ i am getting following error despite the fact i have attached pk in request url i.e 0xe9114368611e9f20cf46b76aa33319fc0ce0b585 as it can be seen in my url. Any help is appreciated. -
DRF Custom Serializer Error Fomat
I am new to Django/ Django Rest Framework. I want custom message i.e "staus" along with custom error message. Error message can be. Email not found Wrong password Required Output format #status_code 200 ok { "status":"failure", "status_message":"Email not found" } View.py class UserLogin(APIView): permissions_class = [AllowAny] serializer_class=UserLoginSerailizer def post(self, request, *args, **kwargs): mydata = request.data serializer=UserLoginSerailizer(data=mydata) if serializer.is_valid(): new_data=serializer.data return Response({"status":"success","message":"success","result":new_data},status=status.HTTP_200_OK) return Response({"status":"failure","message":serializer.errors},status=status.HTTP_200_OK) Serializer.py class UserLoginSerailizer(ModelSerializer): email_id=EmailField(required=True) password=CharField(required=True,error_messages={'required':'Password field is required.'}) jwt_token=CharField(allow_blank=True,read_only=True) class Meta: model=User fields = [ 'email_id', 'password', 'jwt_token', ] extra_kwargs ={"password":{"write_only":True}} def validate(self,data): user_obj=None email_id=data.get("email_id") password=data["password"] user=User.objects.filter(email=email_id) if user.exists(): user_obj =user.first() else: raise ValidationError({"error_message":"Email not found"}) if user_obj: if not user_obj.check_password(password): raise ValidationError({"error_message":"Wrong password"}) jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user_obj) data["jwt_token"]=jwt_encode_handler(payload) return data Current Output { "status": "failure", "status_message": { "error_message": [ "Email not found" ] } } I tried this other way customizing ValidationError but instead of giving 200 status code it used to give 400 bad request and i was not able to add custom message also. i am not sure what the best way to achieve this so i tried like this. Please let me what the best way to achieve my requirement -
Try to Upload Several Pictures, but only 1 is getting saved
I am trying to allow user to upload several pictures, but only one picture is saving to the database. This is my Model from django.db import models from django.contrib.auth.models import User class File(models.Model): files = models.FileField(upload_to='images/') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='files') next, the form for the upload looks like this: from django import forms from .models import File class FileForm(forms.ModelForm): class Meta: model=File fields=('files',) widgets={'files':forms.FileInput(attrs={'id':'files','required':True,'multiple':True})} finally, the view 'upload pics' is the following: def upload_pics(request, user_id): if request.method == "POST": form = FileForm(request.POST, request.FILES) files = request.FILES.getlist('file_field') if form.is_valid(): pics = form.save(commit=False) pics.user = request.user pics.files = request.FILES[files] return redirect("groups:index") else: form = FileForm() render(request, 'accounts/account_form.html', {'form':form}) return render(request, 'accounts/account_form.html', {'form':form}) the problem is that only 1 picture is being saved. any help is really appreciated! -
Connecting Vertica as Django backend
I want to connect Vertica as the database backend for my Django application. Officially no support is provided by Django to it. I googled this problem and found this: https://github.com/rutube/django_vertica_backend The code which is written in this git hub returning following error: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/rksharma/ccChatBot/django_vertica_backend/vertica/base.py", line 8, in <module> from django.db.backends.creation import BaseDatabaseCreation ModuleNotFoundError: No module named 'django.db.backends.creation' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in … -
Soft deleting objects in django
I am trying to implement a general soft deletion pattern for Django models. Models are given a is_deleted field, which keeps deleted objects in DB, but hides them for all practical purposes: all normal rules for cascading etc. should be followed, except for actual removal. The admin app, however, should still be able to work with deleted objects, for the purpose of either erasing (definitely throw them out) o restoring them. (See code below) Problem: this breaks cascading. What I had expected to happen was cascading to occur through the methods I overrode on models and custom queryset. What actually happens is that they are instead bypassed by the default queryset/manager which also happens to be using a fast _raw_delete internal API. So either cascaded delete does not happen, or if I call the super().delete() method on my model (and save() after that), standard delete is performed on related objects. I have tried what is suggested in Cascading Delete w/ Custom Model Delete Method, but this breaks things horribly - besides it advocates usage of the deprecated use_for_related_fields manager attribute. I am beginning to think that what I want to achieve is not possible without effecting major dismemeberments of Django's … -
Stripe charge after subscription, get metadata from subscription
When I'm creating a subscription, I set some metadata to identify my order on the database. When I receive the webhook charge.succeeded, the metadata from subscription, is not passed in this event and I can't identify the order related to this payment. How can I send the metadata on every webhook related to subscription. -
Group by day and then again group by user to get list of object or object's id
class Ticket(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) booked_at = models.DateTimeField(default=timezone.now) bought = models.BooleanField(default=False) I would like to group tickets by day, and then again group each day's ticket list by ticket's user (admin / customer) i.e., user is_admin or not, finally to get list of ticket or ticket's id. [ { 'day': datetime.datetime(2018, 5, 6, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>), 'booked_by_admin': [1, 2, 5], 'booked_by_customer': [3, 4] }, { 'day': datetime.datetime(2018, 5, 7, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>), 'booked_by_admin': [11, 12, 16], 'booked_by_customer': [10, 13, 14, 15] } ] I could group tickets by day this way, Ticket.objects.filter(bought=True).annotate(day=TruncDay('booked_at')).values('day').annotate(c=Count('id')).order_by() But I cannot figure out how to again group it by admin user and non admin user to get list of ticket objects. Could you help me please. -
Handling optional Parameters in Python
I'm trying to solve an issue related to my api and want to refactor my code to work backward, i mean if the front-end doesn't send me the data i want, the request should go through , and if the front-end does send, it would still work as usual. So roughly my create function works fine however , when the front end team sent data without what the server expects it does break with a 500 Internal Server Error, but i want to make it optional, even though the data expected is not sent , i want to get a 200 Http response, here is where the code breaks because of the key error on the job_invoice.I've tried to use in my for loop the break to bypass it .. but still. job_invoice_data = inv_data['job_invoice'] job_invoice = JobInvoice.objects.create(job=job_instance, **job_invoice_data) obj.job_invoice = job_invoice # Create an InvoiceLineItem for each element in invoice_line_item for invoice_line_item in inv_data['invoice_line_item']: invoice_line_item['job_invoice'] = job_invoice.id if invoice_line_item['job_invoice'] is None: break invoice_line_item_serializer = InvoiceLineItemSerializer(data=invoice_line_item) if invoice_line_item_serializer.is_valid(): invoice_line_item_obj = invoice_line_item_serializer.save() else: logger.debug("Couldn't create invoice line item: {}".format(invoice_line_item)) -
Django listening to an specific port and redirect to a view
I have a django application, It has a list of urls and views. right now it listens to port 8000 I want to add one more url to current application but it listens to port 8001 is it even possible?If yes please give me some keywords or examples thanks