Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show two tables specific column data into one list?
I have two tables Customer and Subscription in which Customer has the list of customers and Subscription contains the Customer and Packages. In the customer list i want to show how many packages each customer has. Subscription Model class Subscription(models.Model): client = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True, related_name="subscriptions") package = models.ForeignKey(Package, on_delete=models.SET_NULL, blank=True, null=True) valid_start_date = models.DateTimeField() valid_end_date = models.DateTimeField() usage_count = models.IntegerField(null=True) status = models.CharField(max_length=20) transaction = models.BigIntegerField(blank=True, null=True, default=0) created_at = models.DateTimeField() updated_at = models.DateTimeField() Customer Model class Customer(AbstractBaseUser): first_name = models.CharField(max_length=250, blank=True, null=True) last_name = models.CharField(max_length=250, blank=True, null=True) email = models.EmailField(unique=True, blank=True, null=True) mobile_number = models.BigIntegerField(blank=True, null=True) password = models.CharField(max_length=1000, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True) address = models.CharField(max_length=500, blank=True, null=True) country = models.ForeignKey(Countries, on_delete=models.SET_NULL, blank=True, null=True) state = models.ForeignKey(States, on_delete=models.SET_NULL, blank=True, null=True) city = models.ForeignKey(Cities, on_delete=models.SET_NULL, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) number_of_logins = models.IntegerField(blank=True, null=True) is_active = models.BooleanField(default=True) gcm = models.CharField(max_length=250, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) USERNAME_FIELD = "email" Expected Result : I want to show the package field data from Subscription Model into the list of Customer model. Actual Result : Only Customer field data -
duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=() already exists
good day!A separate page was created to change the password, when you enter the password and repeat it and click on the "change password" button, a duplicate key value violates unique constraint "core_user_username_key" error appears DETAIL: key (username) = already exists how to solve this error? forms.py class CallcenterPasswordChange(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает', ) return self.cleaned_data class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') views.py class CallcenterPasswordChangeView(AbsCallcenterView): template_name = 'callcenter/password_change.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) patient_pk = kwargs.get('patient_pk') patient = get_object_or_404(Patient, pk=patient_pk) initial_data = model_to_dict(patient.user) context['form'] =CallcenterPasswordChange(initial=initial_data) context['patient_pk'] = patient_pk context['patient'] = patient return context def post(self, request, **kwargs): context = super().get_context_data(**kwargs) patient_pk = kwargs.get('patient_pk') patient = get_object_or_404(Patient, pk=patient_pk) form = CallcenterPasswordChange(request.POST) context['form_user'] = form context['patient'] = patient if form.is_valid(): form.save() else: return render(request, template_name=self.template_name, context=context) -
Exception at /openid/callback/login/ this login is not valid in this application in Django
I was trying to make an SSO using keycloak and Django application. My login is working fine as after logged into keycloak I've seen the user session is existed there. But the problem is that, it's not going to the secured page rather it's showing this error : raise Exception('this login is not valid in this application') Exception: this login is not valid in this application And if I reload this then it shows another error: OpenID Connect authentication has failed Error message is: Invalid response invalid_grant. Query content was: This is my code: settings.py INSTALLED_APPS = [ #....... 'bossoidc', 'djangooidc', 'test', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'bossoidc.backend.OpenIdConnectBackend', # ... ] auth_uri = "http://localhost:8080/auth/realms/test" client_id = "test" public_uri = "http://localhost:8000" from bossoidc.settings import * configure_oidc(auth_uri, client_id, public_uri) OIDC_PROVIDERS['KeyCloak']['behaviour']['scope'] = ['openid', 'profile', 'email'] test/views.py def index(request): return HttpResponse('index. <a href="/secure">Secure</a>') @login_required def secure(request): return HttpResponse('Secure page. <a href="/openid/logout">Logout</a>') urls.py urlpatterns = [ url(r'', include('test.urls')), url(r'^admin/', admin.site.urls), url(r'openid/', include('djangooidc.urls')) ] test/urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^secure$', views.secure, name='secure'), ] I'm using this plugin for open-id connection: boss-oidc . My python version is Python 3.6.8, Django But there is also some issues after i run this install command for bossoidc pip … -
Django Max count of foreign key set
class Blog(models.Model): pass class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) b = Blog.objects.filter(...) Given b, is it possible to find with a single query the highest count of associated articles? I could do that by iterating: max_count = 0 for blog in b: if b.article_set.count() > max_count: max_count = b.article_set.count() Is there a more efficient way that uses the ORM/SQL? -
Django database access optimization: Efficient creation of many-to-many relationships (between existing objects)
I'm using Django 2.2 with a PostgreSQL database. I have two models: Gene and Annotation and need to create and link (many-to-many) thousands of Genes and Annotations at the same time. class Gene(models.Model): identifier = models.CharField(max_length=50, primary_key=True) annotation = models.ManyToManyField(Annotation) class Annotation(models.Model): name = models.CharField(max_length=120, unique=True, primary_key=True) I already found a way to create the objects very efficiently: Gene.objects.bulk_create([Gene(identifier=identifier) for identifier in gene_id_set]) This is my Django-docs-inspired way to create relationships: relationships = { 'gene1': ['anno1', 'anno2'], 'gene2': ['anno3'], ... } for gene in relationships: gene = Annotation.objects.get(pk='gene1') gene.annotation_set.set([Annotation.objects.get(pk=anno) for anno in relationships[gene]) But this is very clumsy: It hits the database 4 times! Is there not a better way, using Django-built-in-tools or raw SQL queries? The many-to-many table (myapp_gene_annotation) looks like this: id gene_id annotation_id 1 gene1 anno1 2 gene1 anno2 3 gene2 anno3 ... -
How to validate template versioned form fields in django without using django forms?
I wrote a small authentication application where i used manual template rendering. I can fetch and update data from from forms but i just want to validate the fields. But i can't move forward as i didn't use any Django form models.Client side validation is going on but what about the Server side validation. Using python v3 and Django v2 -
How to order_by related field date with annotation?
i have this model : class Node(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') name = models.TextField(blank=True, null=True) which have this related model : class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) view_date = models.DateTimeField(default=timezone.now) What i am trying to do is to order a queryset of the first model by the view date of the second one, this is the view that i have tried : last_viewed_trees = Node.objects.filter(tree_type='root').order_by('-related_views__view_date') In that one the result is correct but i have a duplicate view_date of many users. I have tried also this one without success : last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Min('related_views__views_count') ).order_by('-time_of_views') last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Max('related_views__views_count') ).order_by('-time_of_views') Nothing have worked for me, there is something that i am missing, but i cannot identify it. -
Assigning several model instances of one Model to another Model, and then comparing them?
I have a model called Hero, which has about 500 different objects. I'm having the user select 4 instances of Hero in a form, and assigning them to a Match model to register what Heroes they played with. I've tried creating a Deck model, that could contain the 4 heroes and then assign that Deck model in Match model and form, but then the user can't select a new combination, only current Deck combinations. This works fine in the adminpanel, where I can add new combinations, but the user doesn't get that opportunity. It's not quite what I want and I can't wrap my head around, is how I can then later compare two instances of Deck or the selected Heroes in Match to see if the user selected the same Heroes in their Deck/Match and/or count how many times that specific combination of Hero is used in a deck/Match. In short: What I want is for the user to, through a form, select 4 Hero objects and save them to a Deck model. If their specific combination of selected Heroes is already in Deck, then it should register it under that. I know it's confusing, but that's owing to … -
How to empty Cart After checking out or making Order?Django
I have e commerce project,I need to empty cart after user checkout and order status is "shipped also if I empty cart manually also orders already made be empty! where is the problem in code and how to separate cart and orders made? def checkout_home(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect("cart:home") login_form = LoginForm() address_form = AddressForm() shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None if request.user.is_authenticated: address_qs = Address.objects.filter(user=request.user) order_obj, order_obj_created = Order.objects.new_or_get(cart_obj=cart_obj,user=request.user) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] order_obj.save() context = { "object": order_obj, # "billing_profile": billing_profile, "login_form": login_form, "address_form": address_form, "address_qs": address_qs,} return render(request, "carts/checkout.html", context) def checkout_done_view(request): Orders = Order.objects.filter(user=request.user) return render(request, "carts/checkout-done.html",{"orders":Orders}) orders.models.py class OrderManager(models.Manager): def new_or_get(self, user, cart_obj): created = False qs = self.get_queryset().filter( user=user, cart=cart_obj, active=True, status='created' ) if qs.count() == 0: obj = self.model.objects.create( user=user, cart=cart_obj) created = True else: obj = qs.first() return obj, created class Order(models.Model): user = models.ForeignKey(User,null=True, blank=True, on_delete=models.CASCADE) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) # shipping_address_final = models.TextField(blank=True, null=True) order_id = models.CharField(max_length=120, blank=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) date_posted = models.DateTimeField(default=timezone.now) objects … -
Login with jwt authentication not working
I have tried creating a user login api with jwt authentication but instead of returning the token it is always returning not authorised. This code seemed to work earlier in the initial phase but now it is just not working. I have no idea what is wrong. I have added the jWT_AUTH and Authentication classes in settings.py . Please Help serializer class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField() password = serializers.CharField() class Meta : model = User fields = ('username','password') class TokenSerializer(serializers.Serializer): token = serializers.CharField(max_length=255) views from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from rest_framework_jwt.settings import api_settings jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER class LoginView(generics.CreateAPIView): permission_classes = (permissions.AllowAny,) serializer_class = UserLoginSerializer queryset = User.objects.all() def post(self, request, *args, **kwargs): username = request.data.get("username", "") password = request.data.get("password", "") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) serializer = TokenSerializer(data={ "token": jwt_encode_handler( jwt_payload_handler(user) )}) if serializer.is_valid(): return Response(serializer.data['token']) return Response("Not Authorized",status=status.HTTP_401_UNAUTHORIZED) I cannot login even when I am using correct username and password. -
Django list of files returns an empty array
I'm starting with Django, so I'm pretty new to this. I'm sending a file to the Django server, saving it, trying to get the last file (the one I just send) from the saved folder and then I want to perform some processes on that file, after that I want to delete the original file. I already managed to upload and save the file to the filesystem, but I'm having trouble selecting this file from the folder. I'm trying select and remove it this way: @api_view(['POST', 'GET']) def geojson_to_shape_view(request): if request.method == 'POST': serializer = FileSerializer(data=request.data) if serializer.is_valid(): # serializer.save() calls .create() in serializers.py file = serializer.save() # Get last saved file print("Analyzing last posted file...") list_of_files = glob.glob('../media/temp_files/*') print(list_of_files) if list_of_files: latest_file = max(list_of_files, key=os.path.getctime) print("Deleting last posted file...") try: os.remove(latest_file) pass except: print("Can't remove the file") return Response(FileSerializer(file).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And this code returns: Analyzing last posted file... [] I tried to run a script in the same folder with these file interactions and it run with no problems, so I thinking is some django permission issue. I also tried to change the path to settings.MEDIA_ROOT + 'temp_files/*', but the problem persists. -
Django: Query with foreign key
I have two models called Thread and Post. A Thread has 0..* posts. Now, I need a query that gets all threads sorted by the datetime of the latest post in the thread. In case there is no post yet in the thread, the datetime of the thread creation is important. Honestly, I am a bit overwhelmed with the database query. Thread: created_at = DateTimeField() Post thread = ForeignKey(Thread) My current approach does not work: newest = Post.objects.filter(thread=OuterRef('pk')).order_by('-created_at') threads = Thread.objects.annotate( latest_post=Case( When(Exists(Subquery(newest.values_list('created_at')[:1])), then=Value(Subquery( newest.values_list('created_at')[:1]), ), default=Value(Thread.created_at)))).order_by('-latest_post') Can someone help me? -
Inconsistency between test and django: :int() argument must be a string but also TypeError: string indices must be integers
I have an API view that receives a request and creates some data. It works fine. When I am running my test I wrote with pytest I receive this error: node_name = (data_node['name']) TypeError: string indices must be integers When I change my code to be an integer like this: node_name = int((data_node['name'])) my django view gives me this error: :int() argument must be a string And I am like... whuat?! This is my view (shortened for brevity): @api_view(['POST']) def CreateGraphView(request): for data_node in nodes: print(type(data_node)) node_name = (data_node['name']) print(node_name) print(type(node_name)) new_node = Node.objects.create(name=node_name) status_code = HttpResponse.status_code return Response(status_code) The data (request) I am sending looks like this: {'project': 'project1', 'name': 'Graph1', 'description': 'test', 'nodes': [{'name': '25', 'graph': 3}], 'edges': [{'name': 'EdgeForGraph1', 'graph': 3, 'source': '25', 'target': '25'}]} And finally, if it helps my test (I send the same data): def test_aut_user_can_create_graph(self, client): data = data url = api_reverse('nameofurl') response = client.post(url, data) assert response.status_code == 201 I am very confused why my test wouldn't accept the code and my code wouldn't accept my test. Especially because when debugging and printing out the type of data_node it tells me it is a dict. So that should be correct. Can someone … -
Django-filter, how to make multiple fields search? (with django-filter!)
How can I make multiple fields search with Django-filter from model like: class Location(models.Model): loc = models.CharField(max_length=100, blank=True) loc_mansioned = models.CharField(max_length=100, blank=True) loc_country = models.CharField(max_length=100, blank=True) loc_modern = models.CharField(max_length=100, blank=True) I need one input field on my website, that can search over all fields of Location model -
Cancel the POST when the page is refreshed
My problem is : When an user refresh the Form the data in the Form is sent. I have a Form with request POST. The user write his name, mail and message. If the mail is correct the message is sent. In my view if the Form is valid, I add the message in my model Message. After that I disable the button "Send". But if the user refresh the page. My view is called and an other row is added in my model. I would like, when the user refresh the page, block the POST. My View: def contact(request): form = MessageForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] message = form.cleaned_data['message'] mail = form.cleaned_data['mail'] new_message = Message() new_message.name = name new_message.message = message new_message.mail = mail new_message.save() envoi = True return render(request, 'vautmieux/contact.html', locals()) My url: path('contact/', views.contact, name='contact'), My HTML: <form action="{% url "contact" %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6"> {{ form.name }} {{ form.mail }} </div> <div class="col-md-6" > {{ form.message }} </div> <button id="sendMessageButton" type="submit">ENVOYER LE MESSAGE !</button> </div> {% if envoi %}Votre message a bien été envoyé !{% endif %} </form> -
How to create invite code only registration app in Django 2.2?
How do i create invite code only registration app in Django 2.2 using "alllauth". Can't find any updated repository -
Avoid non-specified attributes on model creation
I want to create an object in Python but, since I'm using Django, I don't want to save those attributes with None or null value. When I create an object passing a couple of arguments, those attributes passed are assigned correctly; but the rest, which I wish were not created, are assigned the value "None" models.py: from djongo import models from mongoengine import * class MyClass(Document): _id = StringField(max_length=20, primary_key = True) atr1 = StringField() atr2 = StringField(max_length=300) atr3 = EmbeddedDocumentField(AdministrativeOptions) atr4 = EmbeddedDocumentField(CancelationPolicy) atr5 = StringField(max_length=50) atr6 = IntField() views.py: def index(request): a = MyClass( _id = 'TestID', atr1 = 'Xxxx' ) for key in a: print(str(key) + " = " + str(a[key])) a.save() What I get from the print loop is: _id = TestID atr1 = Xxxx atr2 = None atr3 = None atr4 = None atr5 = None atr6 = None Which means I am saving an object full of empty data. I would like to save a MyClass object with just the specified attributes in order to save space in memory. -
How to have another text input in django form in admin user page?
I am trying to add another user input but when I added it in forms.py, it didn't show me anything in admin page. Although it is showing in browser page. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id'] -
Repeat command in while loop or similar until not existing result is found
i need to repeat a cmd which always generated a new random string, after that i need to make sure that this specific string has not been generated before. I never did while loops before and im not able to figure out how to repate the cmd until a result has been found which is not already part of the database. I can't be to specific as this source is closed all this is packed into a celery task tasks.py @app.task def allocate_new_string(user_pk): user = User.objects.get(pk=user_pk) new_string = subprocess.Popen("$get_new_string_cmd", shell=True, stdout=subprocess.PIPE).communicate()[ 0].decode('utf-8').strip() try: while True: if Used_String.objects.filter(string=new_string, atom=0).exists(): new_string << how to repeat the command from above here until a new random string has been found? else: used_string = Used_String.objects.create(user=user, string=new_string, atom=0) used_string.save() logger.info(str("New String has been set) except: logger.info(str("Something went wrong while processing the task")) The function i want to have here is: Search for a none existing sting until one has found that has never been generated before or is at least not part of the database. the cmd im using isn't openSSL or something like that and it's quite likly that i hit two times the same random generated string. Thanks in advance -
duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=(patient1) already exists
On the change password page, when you enter a new password and repeat it, get out such an error, how to fix it? Request Method: POST Request URL: http://0.0.0.0:8010/callcenter/patient/2/password_change Django Version: 2.1.5 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=(patient1) already exists. Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 85 Python Executable: /usr/local/bin/python Python Version: 3.7.2 Python Path: ['/opt/project', '/opt/project', '/opt/.pycharm_helpers/pycharm_display', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages', '/opt/.pycharm_helpers/pycharm_matplotlib_backend'] I tried to add forms.py class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') but it did not help forms.py class CallcenterPasswordChange(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает',) return self.cleaned_data def save(self, commit=True): user = super(CallcenterPasswordChange, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class Meta: model = User fields = ('password1', 'password2') password_cahnge.html {% extends 'callcenter/base.html' %} {% load static %} {% block inside_content %} <h1>Введите новый пароль</h1> <form action="{% url 'callcenter:password_change' patient_pk %}" method="post" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Изменить пароль"></p> </form> {% endblock %} views.py class CallcenterPasswordChangeView(AbsCallcenterView): template_name = 'callcenter/password_change.html' … -
Is it possible to force a website input to be in English?
I'm creating a website in 2 languages - English and Hebrew. I have an input field (the slug/username) which must be in English. When I enter the website from my mobile phone, I can write text in Hebrew. Is it possible to force the keyboard to be in English in this input field? I noticed that for the email address (email input) the keyboard is already in English. -
TypeError: quote_from_bytes() expected bytes after redirect
I wrote a function which after execution returns the user to the anchor page. But I'm getting an error. TypeError: quote_from_bytes() expected bytes view.py class CourseEditView(AuthorizedMixin, UpdateView): """ Edit course instances """ model = Courses form_class = CoursesEditForm template_name = 'additional_info_edit.html' def get_success_url(self): pk = self.object.employee.pk return redirect('{}#education'.format(reverse('profile', kwargs={'pk': pk}))) How to avoid a mistake? -
Based on the side nav load data in the main template
this is img I have a side nav, on selection from side nav that particular html must load in the index.html page. How do I go about implementing in django. views.py class IndexView(TemplateView): template_name = 'index.html' def get(self, request, *args, **kwargs): associate_id = id_to_numeric(request.user.username) user_details = usr_model.objects.using('users').filter(associate_nbr=associate_id) assoc_data = AssocDetailsTb.objects.filter(associate_nbr=associate_id) if assoc_data.exists(): details = AssocDetailsTb.objects.get(associate_nbr=associate_id) return render(request, 'index.html', {'details': details}) else: name ='' nbr ='' client ='' lob='' img ='' for i in user_details: name = i.associate_name nbr = i.associate_nbr client = i.client lob =i.lob img = i.associate_image print(client,lob) cli = ClientTb.objects.get(client_name = client) print(cli.id) lo = LobTb.objects.get(lob_name=lob) data = AssocDetailsTb() data.associate_name = name data.associate_nbr = nbr data.client = cli data.lob = lo data.associate_image = img data.save() return render(request, 'index.html') def page1(request): associate_id = id_to_numeric(request.user.username) details = AssocDetailsTb.objects.get(associate_nbr=associate_id) return render(request,'page1.html',{'details':details}) html <ul class="sub-menu children dropdown-menu"> <li><i class="fa fa-hospital-o"></i><a href="{% url 'qual:page1'%}">Accounts Receivable</a></li> I want to load all the templates in the same page -
how to start a task at a specific time with django & celery
I'm using Celery and it work for async but i need to setup an opertion to a specific datetime for example "the 30 of august 2019 at 11 and 35 min do this" my celery.py is very easy now but it work: import time from datetime import datetime, timedelta from datetime import date from celery import shared_task,current_task, task from celery import Celery app = Celery() @app.task def test(): print ('1') todaynow = datetime.now() print todaynow i call it from view and run print on rabbit any idea for program a task? ty -
If you see valid patterns in the file then the issue is pro bably caused by a circular import
I tried to import pyrebase in my views.py, but I've got an error arisen: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'yerekshe.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is pro bably caused by a circular import. here is my views.py: from django.shortcuts import …