Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include PostgreSQL functions in Django migrations?
I've setup an API with Django REST Framework, and would like to include some Postgres functions as part of the database migration. The two ways I can see are: Editing the migrations file (generated by python manage.py makemigrations) Hooking post table creation The first seems easier, but laborious if the migration needs to be remade. What would you recommend the best way to go about it? Thank you. -
Django, getting data in different page from view
Hello I am new to Django, I am currently working on a project but I can`t figure out how I should do something. Right now I am at the page home/stats/ID/LANGUAGE but inside this page I want a "edit" button, once clicked I want to go to: home/stats/ID/LANGUAGE/edit/ I just want to get the same data from home/stats/ID/LANGUAGE again, but now in home/stats/ID/LANGUAGE/edit/ My view.py: class StatsView(TemplateView): template_name = 'home/stats.html' analytics = build('analyticsreporting', 'v4', credentials=credentials) def get(self, request, id, language): min_date = "2018-12-01" date01 = datetime.strptime(min_date, '%Y-%m-%d') max_date = "2018-12-31" date02 = datetime.strptime(max_date, '%Y-%m-%d') print(date01) print(date02) if request.GET.get('date1'): date1 = request.GET.get('date1') pol1 = datetime.strptime(date1, '%Y-%m-%d') date01 = pol1 print(date01) if request.GET.get('date2'): date2 = request.GET.get('date2') pol2 = datetime.strptime(date2, '%Y-%m-%d') date02 = pol2 print(date02) if request.user.is_authenticated: current_user = request.user.id result = BlablaAuth.objects.filter(user=request.user) if language == 'ALL': blabla = Blabla.objects.filter(blabla=id) prefix = '/blabla/' + id if result and blabla.count() > 0: analytics_result1 = self.analytics.reports().batchGet( body={ "Google analytics reporting stuff" analytics_result2 = self.analytics.reports().batchGet( body={ "Google Reporting stuff" return render(request, self.template_name, context={ "report1": analytics_result1.execute(), "report2": analytics_result2.execute() }) else: apple = Apple.objects.filter(video=id) prefix = '/apple/' + id if result and apple.count() > 0: analytics_result1 = self.analytics.reports().batchGet( body={ "Google reporting analytics stuff" analytics_result2 = self.analytics.reports().batchGet( body={ "Google … -
Django UpdateView: AttributeError: not able to access forms.Form data -> type object 'EventSingleAttendeeForm' has no attribute 'attendee_name'
views.py class EventUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Event form_class = EventUpdateForm second_form_class= EventSingleAttendeeForm template_name = 'events/event_update.html' def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) def test_func(self): event = self.get_object() if self.request.user == event.creator: return True return False def get_context_data(self, *args, **kwargs): context = super(EventUpdateView, self).get_context_data(*args, **kwargs) context['form2'] = self.second_form_class return context def post(self, request, *args, **kwargs): form = self.form_class(request.POST) form2 = self.second_form_class(request.POST) if form.is_valid() and form2.is_valid(): event_data = form.save(commit=False) # attendee_name = form2.attendee_name if form2.attendee_name != '' and form2.attendee_email != '' and form2.attendee_mobile: attendee = Attendee(name=form2.attendee_name, email=form2.attendee_email, mobile=form2.attendee_mobile) existing_attendee = Attendee.objects.filter(Q(email__exact=form2.attendee_email) | Q(mobile__exact=form2.attendee_mobile)) if existing_attendee: attendee = existing_attendee.first() else: attendee.save() form.attendees.add(attendee) form.save() return redirect('some') forms.py class EventSingleAttendeeForm(forms.Form): attendee_name = forms.CharField(max_length=50, required=False) attendee_mobile = forms.IntegerField(required=False) attendee_email = forms.EmailField(required=False) builtins.AttributeError AttributeError: type object 'EventSingleAttendeeForm' has no attribute 'attendee_name' I am getting this error I want to access the data in those fields but I am not able to. A little help will be appreciated. Thanks in advance.... -
How to represent a family relationship in Django using manyToMany and inlineformset?
I would like to create a update view where a Person model has their related FamilyMember as an inlineformset in my template. In my model.py, I have: class Person(models.Model): Name = models.CharField(max_length=50) class FamilyMember(models.Model): person = models.ManyToManyField(Person, through='UseCaseProfileRelatedUseCase') relationType= models.CharField(max_length=3, choices=FAMILYRELATION_CHOICE) class PersonFamilyMember(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) related = models.ForeignKey(FamilyMember, on_delete=models.CASCADE) In my form.py, I have: class PersonForm(ModelForm): class Meta: model = Person fields = '__all__' class FamilyMemberForm(ModelForm): class Meta: model = FamilyMember fields = '__all__' RelatedFMFormSet = inlineformset_factory(Person, PersonFamilyMember.useCase.through, form=FamilyMemberForm, can_delete=True, extra=1) In my view.py, I have: class PersonView(UpdateView): template_name = 'some.html' model = Person form_class = PersonForm def get_context_data(self, **kwargs): context = super(PersonView, self).get_context_data(**kwargs) if self.request.POST: context['familymember_form'] = RelatedFMFormSet(self.request.POST, self.request.FILES, instance=self.object, prefix='relatedMember') else: context['familymember_form'] = RelatedFMFormSet(instance=self.object, prefix='relatedMember') return context In my template, I have: <form method="POST" enctype="multipart/form-data" style="margin-left: 40px; margin-right: 40px"> {% for hidden_field in form.hidden_fields %} {% endfor %} {% csrf_token %} <fieldset> <legend>[Person Profile][1]</legend> {{ form.management_form }} {{ form.non_form_errors }} <div class="form-inline"> {% bootstrap_form form %} </div> </fieldset> <fieldset> <legend>Related Member(s)</legend> {{ familymember_form.management_form }} {{ familymember_form.non_form_errors }} <div class="formset-{{ relatedusecase_form.prefix }}"> {% for hidden_field in familymember_form.hidden_fields %} {% endfor %} {% for relatedform in familymember_form.forms %} <div class="form-inline"> {% if relatedform.instance.pk %} {{ relatedform.DELETE }} {% … -
Whyis my django project returning "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet" error
I am using django to try and create a website that allows usersubdomains. Something like john.stackoverflow.com. I'm currently trying to set up django tenant schamas and nothing seems to be working even though I'm following the documentation. I am trying to make the app 'main' a tenant app. So when a user goes to main it returns user.website.com. I keep getting this error though "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet". Here's my settings file: INSTALLED_APPS = [ 'tenant_schemas', 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TENANT_MODEL = "main.Client" MIDDLEWARE = [ 'tenant_schemas.middleware.TenantMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'main', # you must list the app where your tenant model resides in 'django.contrib.contenttypes', # everything below here is optional 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', ) TENANT_APPS = ( 'django.contrib.contenttypes', # your tenant-specific apps 'main', ) DATABASES = { 'default': { 'ENGINE': 'tenant_schemas.postgresql_backend', # .. } } DATABASE_ROUTERS = ( 'tenant_schemas.routers.TenantSyncRouter', ) -
Obey the testing goat - OperationalError
I am going through Obey the testing goat book and stumbled upon this error: django.db.utils.OperationalError: table lists_item has no column named list_id It only appears when I am on a dev server (when I am running tests it works like a charm). The book explains that it can happen here (http://www.obeythetestinggoat.com/book/chapter_prettification.html): If you spin up your dev server with manage.py runserver, you may run into a database error "table lists_item has no column named list_id". You need to update your local database to reflect the changes we made in models.py. Use manage.py migrate. If it gives you any grief about IntegrityErrors, just delete[1] the database file and try again. I am doing what it says, but error does not disappear. Maybe anyone can help me with this? -
How to acheive search in auditlog through Django auditlog package
In django auditlog Create,Update and Delete is working fine for me.For search I try to customize the given default package. In that package they are mentioned The valid actions are :py:attr:Action.CREATE, :py:attr:Action.UPDATE and :py:attr:Action.DELETE.though I have tried but I am unable to achieve the goal. Here I have mentioned code below Models.py: @python_2_unicode_compatible class LogEntry(models.Model): class Action: """ The actions that Auditlog distinguishes: creating, updating and deleting objects. Viewing objects is not logged. The values of the actions are numeric, a higher integer value means a more intrusive action. This may be useful in some cases when comparing actions because the ``__lt``, ``__lte``, ``__gt``, ``__gte`` lookup filters can be used in queries. The valid actions are :py:attr:`Action.CREATE`, :py:attr:`Action.UPDATE` and :py:attr:`Action.DELETE`. """ CREATE = 0 UPDATE = 1 DELETE = 2 choices = ( (CREATE, _("create")), (UPDATE, _("update")), (DELETE, _("delete")), ) content_type = models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE, related_name='+', verbose_name=_("content type")) object_pk = models.CharField(db_index=True, max_length=255, verbose_name=_("object pk")) object_id = models.BigIntegerField(blank=True, db_index=True, null=True, verbose_name=_("object id")) object_repr = models.TextField(verbose_name=_("object representation")) action = models.PositiveSmallIntegerField(choices=Action.choices, verbose_name=_("action")) changes = models.TextField(blank=True, verbose_name=_("change message")) actor = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True, related_name='+', verbose_name=_("actor")) # remote_addr = models.GenericIPAddressField(blank=True, null=True, verbose_name=_("remote address")) timestamp = models.DateTimeField(auto_now_add=True, verbose_name=_("timestamp")) # additional_data = JSONField(blank=True, null=True, verbose_name=_("additional data")) objects … -
'Image' object has no attribute '_committed'
I am trying to resize my picture into 124*124 size. I searched alot and find some solutions for related problem. But My problem is not solved even though. My model class MyUsers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') image = models.FileField(upload_to='static/photo', blank=True) name = models.CharFiled(max_length=150) def __str__(self): return self.name My view def change_user_photo(request, id): if request.method == "POST": new_pic = request.FILES['new'] if new_image: my_user = MyUser.objects.get(id=id) image = Image.open(new_pic) image = image.resize((124,124), Image.ANTIALIAS) my_user.image = image my_user.save() return HttpResponseRedirect(reverse('my_profile')) else: user = get_photo(id) return render(request, "photo/edit.html", {"users":user}) My Template: <form method="POST" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} <div class="form-group"> <label>New Photo:</label> <input type="file" name="new"/> </div> <hr/> <div class="form-group"> <button type="submit" class="btn btn-sm btn- success">Update</button> </div> </form> -
how to send email verification link in django
**this code has worked me before but its not working anymore.everything is running fine but its not sending email to the users after signup process done. is there any solutions for this code. this code has worked me before but its not working anymore.everything is running fine but its not sending email to the users after signup process done. is there any solutions for this code. this code has worked me before but its not working anymore.everything is running fine but its not sending email to the users after signup process done.** here is views.py def activate(req, uidb64, token): try: uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(id=uid) except(TypeError, ValueError): user = None if user and activation_token.check_token(user, token): user.is_active = True user.save() messages.info(req, 'Your Account activated. Now Login') return redirect("shop:users_signin") else: messages.error(req, "Activation link is Invalid.") def users_signup(req): if req.method == "POST": form = UserSignupForm(req.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() site = get_current_site(req) mail_subject = "Confirmation message" message = render_to_string('shop/activate_mail.html', { "user": user, 'domain': site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': activation_token.make_token(user) }) to_email = form.cleaned_data.get('email') to_list = [to_email] from_email = settings.EMAIL_HOST_USER send_mail(mail_subject, message, from_email, to_list, fail_silently=True) messages.success(req,"Thanks for your registration. A confirmation link has been sent to your email") else: … -
Default value missing from nested serializer's validated data during update
I'm trying to implement the update-method for nested representations in Django Rest Framework. from django.db import models from django.utils import timezone from rest_framework import serializers class Foo(models.Model): pass class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, null=False, related_name='bars') name = models.CharField(max_length=255) create_date = models.DateField(null=False) class BarSerializer(serializers.ModelSerializer): create_date = serializers.DateField(default=timezone.now) class Meta: model = Bar fields = ('name', 'create_date',) class FooSerializer(serializers.ModelSerializer): bars = BarSerializer(many=True, required=False) def create(self, validate_data): bars_data = validated_data.pop('bars', []) foo = Foo.objects.create(**validated_data) for bar_data in bars_data: Bar.objects.create(foo=foo, **bar_data) return foo def update(self, instance, validated_data): bars_data = validated_data.pop('bars', None) if bars_data is not None: Bar.objects.filter(foo=instance).delete() for bar_data in bars_data: Bar.objects.create(foo=instance, **bar_data) return super().update(instance, validated_data) class Meta: model = Foo fields = ('bars',) When creating an object I get the expected results, but whenever I want to update the bars list, without providing a create_date, I get an error saying that create_date cannot be None (which is correct): django.db.utils.IntegrityError: NOT NULL constraint failed: myapp_bar.create_date If I print bars_data inside update I can see that it doesn't get its default value from timezone.now. It isn't in the dictionary at all. How do I access the default value here? It should have gone through the validation of the serializer, why isn't the default value … -
How to use param from HTTP request to append a model in Django
I am new to Django and how it interacts with some of its internal components so I apologize in advance if this is obvious. I am working with html canvas and a particular javascript library (fabric.js) so that I can convert a canvas to a json object. I want to use an ajax request to send that json object so that I can attach it to a model in my db. How would I go about doing this. Here is the Javascript: function postData(input) { $.ajax({ type: "POST", url: window.location.href, data: { json: input }, success: callbackFunc }); } let canvasBefore = JSON.stringify(canvas); postData(canvasBefore); I assume there is an built in method for django to handel requests like this. Thank you for the help. Nicholas -
Django: Allow user to access further only if she has submitted a form or has saved the model
The user passes through some forms just after signing up. There is logout link below every form page. I want to give the user further access to the site only if each of those forms have been saved. Now, in my case I have these models: class Driving_plan(models.Model): plan = models.CharField (max_length=25, blank=False) duration = models.CharField(max_length=15) annual_fee = models.DecimalField(max_digits=4, decimal_places=2, default=50.00) .... class Payment_receipt(models.Model): driving_plans = models.ForeignKey(Driving_plan, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) When a user selects an instance of Driving_plan, this data is saved in the Payment_receipt model through this view: @login_required def passPlanPKView(request, pk): plan = Driving_plan.objects.get(pk = pk) Pay = Payment_receipt.objects.create( driving_plans=plan, user = request.user, start_date=datetime.date.today(), end_date= calcEnddate(plan), ) return redirect('add_user_profile') How do I apply this so that, if the user has got this model saved, redirect her to home. Otherwise, she must fill the form the next time she logs in? In my case, when a user has not filled all the forms, she still is getting access by logging out; and when logging in she is straight into the home page. And the forms are left unsaved. How do I do this? -
DRF browsable API is not working in "django-rest-passwordreset" package
I currently am using django-rest-passwordreset package but when I go to reset-password endpoint DRF browsable API is not working (package doc mentioned that browsable API support is available). urlpatterns = [ path('password-reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ] Is there any settings that I have to change? -
CrispyForms: FormHelper - to get the </form> in another place, save two forms from the same model
When using FormHelper and calling the Form with {% crispy form %} it delivers a Form enclosed within tags. However, on my Template, the page is divided into two columns. One column holds the crispy form Second column holds another form (all entries are from the same model, one part is more "dynamic" the other part is more "fixed"). I would like to be able to save both forms at the same time, suggestively by putting both forms within the same form tags. such as <form method="post"> {% csrf_token %} {% block col8_content %} {% crispy form %} {% endblock col8_content %} {% block col4_content %} <div class="form-group row"> ... </div> <input type="submit" value="Submit"> {% endblock col4_content %} </form> Current solution is more of a "hack". I generate the form with FormHelper then copying it in the browser's view-source, remove the form tags paste this within manual form tags. It works now, but later a drop-down will determine which form to use and need a quick way of generate it. Q: Is there a way to combine the ability to easily create forms programmatically (FormHelper) together with Manual elements? (I can skip Crispy if needed, but ideally stay out of … -
Find models that have only one particular related model
Consider the following models: class Product(models.Model): name = models.CharField(max_length=...) class Size(models.Model): name = models.CharField(max_length=...) products = models.ManyToManyField(Product, through=ProductXSize, related_name='sizes', related_query_name='size') class ProductXSize(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='productxsizes', related_query_name='productxsize') size = models.ForeignKey(Size, on_delete=models.CASCADE, related_name='productxsizes', related_query_name='productxsize') What I'd like to achieve is along the lines of: for p in Product.objects.filter(sizes=[Size.object.get(...)]): ... That is, find products that have one size, and a particular one at that. -
How to render from backend Django MarkdownX to html for Vue.js front-end?
I need to pass a field ‘description’ in admin Django with Markdownx to an HTML to show in the front of Vuejs. I don’t know how to do it and I didn’t find anything about that.. help please. -
How to populate an Android Spinner from a Json file URL
I have the following Json Format file: [ { "id": 1, "game_genre": "RPG" }, { "id": 2, "game_genre": "Action" } ] on a remote location: http://127.0.0.1:8000/genre/?format=json (Ddjango Format) and i want to populate an Android spinner with the respective id so that can perform a search later depending on the id of the genre. I read the other threads but since i am new into android i don't know where to start. i have the Json parser file included in my project -
Django post_save signal called before save done
When creating an object with a custom save method the post_save signal is called before the database object is really saved to the database. class Task(models.Model): date_last_state_change = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): print("SAVING TASK") print(self.date_last_state_change) super().save(*args, **kwargs) print("SAVING TASK 2") print(self.date_last_state_change) And following signals: @receiver(post_save, sender=Task) def create_initial_tag_for_task(instance, created, *args, **kwargs): if created: TagMapping.objects.create(content_object=instance, tag=TagMapping.add_and_return_tag("open")) @receiver(post_save, sender=TagMapping) def set_timestamp_for_mapped_task(instance, created, *args, **kwargs): task_type = ContentType.objects.get_for_model(Task) if instance.tag.is_state and instance.content_type.pk == task_type.pk: task = Task.objects.get(pk=instance.object_id) task.date_last_state_change = datetime.now() task.save() So when I create a Task I create a generic relation to that object and give it a tag. As soon as I created a state tag I want to set the property of the Task object. And this is the console output when creating a new Task: SAVING TASK None SAVING TASK 2019-03-05 14:12:25.958946 SAVING TASK 2 2019-03-05 14:12:25.958946 SAVING TASK 2 None With that the date in the database object is None. I really don't understand why. -
DRF Set OneToOneField to currently logged in user
I have a model which has a OneToOneField like this: class Customer(models.Model): """A Class to represent a Customer in System """ user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) The serializer for which looks like this: class CustomerSerializer(serializers.ModelSerializer): """A Serizlier class for customer """ class Meta: model = models.Customer fields = ('user', 'first_name', 'last_name', 'dob', 'gender') Right now the browsable api shows a dropdown list for user how can I set user to currently logged in user in CustomerSerializer and make it read_only ? i.e the field should not be a passable parameter to the endpoint and instead should be a read only field corresponding to currently logged in user. -
Dependant Dropdown Filter with Django and Ajax
I am trying to filter the database results from one table with multiple dependant dropdown menues. Here is what I have so far. <form method="POST" id = "form1"> {% csrf_token %} {{ filter.form }} <button name="filter_port" type="submit">Search</button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_gebaeudebereich").change(function () { var gebaeudebereich = $(this).val(); $.ajax({ data: { 'gebaeudebereich': gebaeudebereich }, success: function (data) { $('#id_gebaeudenummer').html(data); } }); }); </script> I am using the external library django_filter for filtering the database results. Here is my filters.py class CSVFilter(django_filters.FilterSet): entries = Excel3.objects.values_list('gebaeudebereich', flat = True).distinct() gebaeudebereich_auswahl = [(e, e) for e in entries] #print("e" , gebaeudebereich_auswahl) gebaeudebereich = django_filters.ChoiceFilter(choices = gebaeudebereich_auswahl) entries = Excel3.objects.values_list('gebaeudenummer', flat=True).distinct() gebaeudenummer_auswahl = [(e, e) for e in entries] gebaeudenummer = django_filters.ChoiceFilter(choices=gebaeudenummer_auswahl) entries = Excel3.objects.values_list('ebene', flat=True).distinct() ebene_auswahl = [(e, e) for e in entries] ebene = django_filters.ChoiceFilter(choices=ebene_auswahl) entries = Excel3.objects.values_list('raum', flat=True).distinct() raum_auswahl = [(e, e) for e in entries] raum = django_filters.ChoiceFilter(choices=raum_auswahl) And finally my views.py def filter(request): gb = request.GET.get("gebaeudebereich") gn = Excel3.objects.filter(gebaeudebereich=gb).values_list("gebaeudenummer", flat=True).distinct() instance = Excel3.objects.values() user_filter = CSVFilter(request.POST or None, queryset=instance) return render(request, 'music/filter.html', {'filter': user_filter, 'gn' : gn}) The change function in the template works so when I select a value of "id_gebaeudebereich" it changes something in the second dropdown … -
To call django function automatically
i'm new to django. In django i want to call my function automatically for every 3 hours. Is there any way to do it? or any packages is there for do this job? thanks -
AttributeError: type object 'Project' has no attribute '_meta'
Thanks in advance for taking the time to read my question. I am a complete beginner in the Django framework and I am a at a loss what causes my problem.I encountered the following in my django files when I attempt to use the class based view CreateView. AttributeError at /overview/new/ type object 'Project' has no attribute '_meta' I have no idea why the _meta attribute is not there. I inherited my model from models.Model as usual, but I can't find any questions that have the same problem. I posted my files down below, can somebody help me fix this problem? views.py: from django.shortcuts import render, redirect from django.contrib.auth import logout, authenticate, login from django.contrib import messages from django.views.generic import ListView, DetailView, CreateView from projects.models import Project, Task class CreateProject(CreateView): model = Project fields = ['title', 'description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py: from django.db import models from django.contrib.auth.models import User from .CustomIDConstructor import ID class Project(models.Model): title = models.CharField(max_length=100, default='No title') description = models.TextField(default='No description') author = models.ForeignKey(User, on_delete=models.CASCADE) customid = models.CharField(max_length=30, default=ID, editable=False, primary_key=True) def __str__(self): return self.title urls.py: from django.urls import path from . import views from projects.views import ProjectsOverview, Project, CreateProject from django.contrib.auth.decorators … -
Using Celery and Redis with my Django application
I would like to ask a question according to Celery and Redis with my Django application. As I will explain further in details, I get some random issues with these applications. My environment: I'm using : Django 1.11.20 django-redis 4.7.0 / redis >= 2.10.5 celery 4.2.1 My local context: (Ubuntu virtual machine) I have a celery task which send an email with export file when this file is larger than 70.000 objects. The process works fine and I get the expected email with link to download my file. Celery is started manually : celery -A main worker -l info My dev context: (FreeBSD server) I have exactly the same process. But celery is daemonized on my server. I can execute celery service with : service celeryd_app start When I launch my celery task, sometimes I need to click on the button some times before to see : Received task: app.tasks.get_xls_export[64d31ba5-73d9-4048-b19a-a4902fd904d7] But the main issue that I have is : My task send an email with a specific email template located in /templates/email/email.html. Sometimes it send this email template and sometimes it send an old template which doesn't exist in my project. My question: Is it possible that Celery/Redis has been … -
Run python script in Django website when clicking button submit
I want to run python script in Django website when clicking on button submit(html)! class GoogleForm(forms.ModelForm): class Meta: model = Google_crawl fields = ('name', 'employee_number', 'download_type', 'team_name', 'crawl_info', 'keyword', 'max_num') exclude = ('request_date', 'request_id') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() #self.helper.layout = Layout(Div(InlineRadios('download_type'))) self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Let\'s Crawl!')) This is my forms.py file. class RequestCreateView(CreateView): model = Google_crawl form_class = GoogleForm template_name = 'crawler/crawler_google.html' def form_valid(self, form): keyword = form.cleaned_data['keyword'] max_num = form.cleaned_data['max_num'] google_crawler_real(keyword, max_num) return super(RequestCreateView, self).form_valid(form) and this is my views.py file. I want to run function name google_crawler_real() and parameter that need to run this file is keyword, max_num. in my opinion, the problem is in views.py! plz help me. :) -
Django:ValueError: invalid literal for int() with base 10 in pre save signal
This are my models: class Stockdata(models.Model): Date = models.DateField(default=datetime.date.today,blank=False, null=True) stock_name = models.CharField(max_length=32) gst_rate = models.DecimalField(max_digits=4,decimal_places=2,default=5) hsn = models.PositiveIntegerField() class Stock_gst(models.Model): date = models.DateField(default=datetime.date.today) stock_item = models.ForeignKey(Stockdata,on_delete=models.CASCADE,related_name='stockgst') gst_rate = models.DecimalField(max_digits=4,decimal_places=2,default=5) hsn = models.PositiveIntegerField() My pre_save signal: @receiver(pre_save, sender=Stockdata) def user_created_stockdata_gst(sender,instance,*args,**kwargs): c = Stock_gst.objects.filter(User=instance.User, Company=instance.Company).count() + 1 Stock_gst.objects.update_or_create(date=instance.Date,stock_item=instance.stock_name,gst_rate=instance.gst_rate,hsn=instance.hsn) I want to create an instance of Stock_gst object whenever an object is created in Stockdata model. But it gives an ValueError in this line of code. stock_item=instance.stock_name It is in my signal. Do anyone have any idea how to solve this? Thank you