Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot filter a query once slice has been taken django
Follow up onto: AutoField should be present but it's not (django)? related to: "Cannot update a query once a slice has been taken". Best practices? I don't need to filter objects, only order by date and select the most recent one: def get_latest_currency(self): """ Return most up to date value """ up_to_date_currency = Currency.objects.order_by('-currency_value_in_dollars_date')[:1] if not up_to_date_currency.exists(): # No objects yet; fetch currencies update_coins_table() return Currency.objects.order_by('-currency_value_in_dollars_date')[:1] up_to_date_currency is initialized correctly; the last line gives: assert not self.query.is_sliced, \ AssertionError: Cannot filter a query once a slice has been taken. This code represents a view (I want to return a plain JSON object (this is a REST endpoint)). Why is django complaining about a filter when only a slice was used? -
How do i handle an OSError?
I am getting an OSError in my python code as soon as I run the command: "(env) C:\Users\AFFAN QADRI\PROJECT>python manage.py runserver" The error message I get is as follows: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
How to solve autocomplete error "NoReverseMatch at /"? I am making django project can anybody help me
model.py class Mobile(models.Model): mobile_id = models.AutoField mobile_name = models.CharField(max_length=100) views.py def autosuggest(request): print(request.GET) query_original = request.GET.get('term') queryset = Mobile.objects.filter(mobile_name__icontains=query_original) mylist=[] mylist += [x.mobile_name for x in queryset] return JsonResponse(mylist,safe=False) urls.py path("autosuggest/", views.autosuggest, name="Autosuggest"), basic.html <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#search" ).autocomplete({ source: '{% url 'autosuggest' %}' }); } ); </script> I am also doing source: '{% url 'my_app_name:autosuggest' %}' in basic.html and in urls.py app_name = 'my_app_name' but it is not work. I am trying to href and another code but not working it show me NoReverseMatch at /. Reverse for 'autosuggest' not found. 'autosuggest' is not a valid view function or pattern name. -
Django Serializer - How to know which parameters was input wrongly
I always put serializers in an try statement that returns false when have invalid format. Like this: Sample model: from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Sample code: try: testSerializer(data = b).is_valid() except: return HttpResponse("Invalid data type input) Now, I want to return parameters was input incorrectly like this: Parameters: Name, Email was input in wrong type -
AutoField should be present but it's not (django)?
Looking at: https://docs.djangoproject.com/en/3.1/ref/models/instances/#django.db.models.Model.save For convenience, each model has an AutoField named id by default unless you explicitly specify primary_key=True on a field in your model. See the documentation for AutoField for more details. and https://docs.djangoproject.com/en/3.1/topics/db/models/ it seems clear that an object always has an id. I have a model: class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateField() def __str__(self): return self.currency_name that I've migrated as: operations = [ migrations.CreateModel( name='Currency', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('currency_name', models.CharField(max_length=100)), ('currency_value_in_dollars', models.FloatField()), ('currency_value_in_dollars_date', models.DateField()), ], ), and when trying to add entries to the db like: def update_coins_table(): if not do_greeting(): print("Gecko crypto board not reachable. Db setup") return crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd') timezone_now = timezone.now() for coin_key in crypto_coins_prices: coin = Currency(coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) coin.save() the line: coin = Currency(coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) gives: unable to get repr for <class 'manage_crypto_currency.models.Transaction'> and coin.save() fails. If I replace the line in question with: coin = Currency(1, coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) it works. Shouldn't the id auto increment? The last line always overwrites the previous and only one entry gets stored in the end. -
How to authorize my API requests with django google-auth?
I have implemented google-auth in my Django project, using allauth, and it works perfectly. After successful verification, I get some key from this view. from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter { "key": "12b6e1696cdd73ddede1334f683003f63426f423" } At this point how can I authorize my other API requests by this key to identify a user on my server? Or what else I need to do ? How to use this key in my other requests ? -
send a list of items in list in json
im trying to send a list of numbers in a json.. how can i do that? im using django serializer to serialize my db model and output is this : { "id": 9, "original_code": "1144", "factory_code": "4411", "length_m": "2", "width_cm": "2", "g_m2": "5", "shrinkage_length": "12", "shrinkage_width": "15", "group": 1, "color": [ 1, 2 ] } i want to use seralizer for my input too...but the issue is seralizer accept 1 value(and when i print the result value is saved in a list) for color but when im trying to add another one i receive error... can you hellp me please? -
Django | Generate Total Price from Price per Item and Amount?
im new to Django and im playing a bit around. So i want to create a Model Field that is dynamicly showing the total price generated from the Amount and Item Price given by the User. Is there a way to do this easy? I would love to find out how that works. -
my application running both django and react when i call api cors error is occure like here
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/accounts/update. (Reason: CORS request did not succeed). XHRGEThttp://localhost:8000/api/accounts/update my django settings is CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] and installed 'corsheaders' also bt i getting this error please help -
Profile page is showing error under postlist href since pk number is increasing?
in blog page, i have made profile pages link for every user. there is also a view for userlist where users linked to their own profile page. here is my blog/models.py: class Post(models.Model): title = models.CharField(max_length=255) body=RichTextField(blank=True,null=True) image=models.FileField(upload_to="mediaphoto",validators=[validate_file_size]) topImage=ImageSpecField(source='image',processors=[ResizeToFill(750,300)],format='PNG',options={'quality':60}) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) category=models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) blog/views.py: class CustomContentMixin: def get_context_data(self, **kwargs): context = super(CustomContentMixin, self).get_context_data(**kwargs) context['user_list']= Profile.objects.all() context['category_list']=Category.objects.all() return context class BlogappListView(CustomContentMixin,ListView): model = Category,Profile template_name = 'home.html' context_object_name='post_list' queryset=Post.objects.all() paginate_by=7 class BlogappUpdateView(CustomContentMixin,UpdateView,LoginRequiredMixin,UserPassesTestMixin): model=Post template_name='post_edit.html' fields=('title','body','image','category') login_url='login' def test_func(self): obj = self.get_object() return obj.author == self.request.user class BlogappDetailView(DetailView,LoginRequiredMixin,FormMixin): model=Post template_name='post_detail.html' login_url='login' form_class=CommentForm def get_success_url(self): return reverse_lazy('post_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(BlogappDetailView, self).get_context_data(**kwargs) context['comments']=Comment.objects.filter(post=self.object) context['comment_form']=CommentForm() context['user_list']= Profile.objects.all() context['category_list']=Category.objects.all() return context def post(self, request, *args, **kwargs): self.object = self.get_object() comment_form = self.get_form() if comment_form.is_valid(): return self.form_valid(comment_form) else: return self.form_invalid(comment_form) def form_valid(self, comment_form): comment_form.instance.post = self.object comment_form.instance.author=self.request.user comment_form.save() return super().form_valid(comment_form) class BlogappDeleteView(CustomContentMixin,DeleteView,LoginRequiredMixin,UserPassesTestMixin): model=Post template_name='post_delete.html' success_url=reverse_lazy('home') login_url='login' def test_func(self): obj = self.get_object() return obj.author == self.request.user class BlogappCreateView(CustomContentMixin,CreateView,LoginRequiredMixin): model=Post template_name='post_new.html' login_url='login' fields=('title','body','image','category') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) acounts/models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) name=models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) def … -
how do I post a foreign key by some other field rather than primary key in django rest framework
I am developing a pet management api and this is what I post to the body when assigning a day of the week to a pet : { "day": "Sunday", "pet_name": 2 <-- how to add pet name (rather than the primary key)(this is a foreign key) } How do I pass in the pet name which is the foreign key's field rather than the primary key field. -
updating an user's object in django
i have a problem in updating an exsited object in my models ,when i update and change the user object its gonna save and everything is looked ok but i guess its just save ,because when i change the user and i want to login ,beside of login view this user dosnt authenticated and dosnt login. here my code def profile_edit(request): user = request.user profile = request.user.profile context = { 'user': user } if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') user.profile.address = request.POST.get('address') user.profile.phone = request.POST.get('phone') user.set_password('password') user.username = username user.save() user.profile.save() authenticate(user) context = { 'profile': profile } return render(request, 'helpdesk/profile.html', context) return render(request, 'helpdesk/profile_edit.html', context) and login view def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) profile = request.user.profile context = { 'profile': profile } return render(request, 'helpdesk/user_desk.html', context) else: context = { 'username': username, 'error': 'user not find!' } else: context = {} return render(request, 'helpdesk/login.html', context) -
Django calendar clickable days
I'm implementing an events calendar and i'm trying to make clickable days that automatically fill in day field in my models is there a way to pass selected day to the day field in models.py or is there any widget that i can use instead of this one? Here is my models.py models.py class Event(models.Model): day = models.DateField() start_time = models.TimeField(u'Starting time', help_text=u'Starting time') end_time = models.TimeField(u'Final time', help_text=u'Final time') notes = models.TextField(u'Textual Notes', help_text=u'Textual Notes', blank=True, null=True) class Meta: verbose_name = u'Scheduling' verbose_name_plural = u'Scheduling' def check_overlap(self, fixed_start, fixed_end, new_start, new_end): overlap = False if new_start == fixed_end or new_end == fixed_start: #edge case overlap = False elif (new_start >= fixed_start and new_start <= fixed_end) or (new_end >= fixed_start and new_end <= fixed_end): #innner limits overlap = True elif new_start <= fixed_start and new_end >= fixed_end: #outter limits overlap = True return overlap def get_absolute_url(self): url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.id]) return u'<a href="%s">%s</a>' % (url, str(self.start_time)) def clean(self): if self.end_time <= self.start_time: raise ValidationError('Ending hour must be after the starting hour') events = Event.objects.filter(day=self.day) if events.exists(): for event in events: if self.check_overlap(event.start_time, event.end_time, self.start_time, self.end_time): raise ValidationError( 'There is an overlap with another event: ' + str(event.day) … -
Unable to Create with OneToOneField Django
I'm stuck with this issue for a while now and couldn't find a solution. Here is the issue: Background: I have CustomUser(AbstractUser) model and HeroesUser which has OneToOneField relationship with CustomUser model. (Hero user is a user type, later on I'll have more fields but at the moment I just put in "city" to be simple) I want to be able to create a hero user for each custom user, but unable to do so with this OneToOneRelationship. So please please if you have experience, please help me!!! Here are my codes: models.py from django.contrib.auth.models import AbstractUser import datetime class CustomUser(AbstractUser): is_hero = models.BooleanField(default=False) is_host = models.BooleanField(default=False) want_newsletter = models.BooleanField(default=False) def __str__(self): return self.username class HeroesUser(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) city = models.CharField(max_length=50, default="") serializers.py from .models import CustomUser, HeroesUser from django.utils import timezone class CustomUserSerializer(serializers.Serializer): id = serializers.ReadOnlyField() username = serializers.CharField(max_length=200) email = serializers.CharField(max_length=200) password = serializers.CharField(write_only=True) first_name = serializers.CharField(max_length=200) last_name = serializers.CharField(max_length=200) is_hero = serializers.BooleanField(default=False) is_host = serializers.BooleanField(default=False) is_staff = serializers.BooleanField(default=False) def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) class CustomUserDetailSerializer(CustomUserSerializer): def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.is_hero = validated_data.get('is_hero', instance.is_hero) instance.is_host = validated_data.get('is_host', instance.is_host) instance.is_staff = validated_data.get('is_staff', instance.is_staff) instance.save() … -
Is there a way to get the columns from a joined table in the model instance dict object?
t = PurchaseHeader.objects.first() t.__dict__ { '_state': <django.db.models.base.ModelState object at 0x7f4b34aa7fa0>, 'id': 3, 'ref': 'jhkh', 'goods': Decimal('-100.00'), 'discount': Decimal('0.00'), 'vat': Decimal('-20.00'), 'total': Decimal('-120.00'), 'paid': Decimal('-120.00'), 'due': Decimal('0.00'), 'date': datetime.date(2020, 11, 7), 'due_date': datetime.date(2020, 11, 14), 'period': '202007', 'status': 'c', 'created': datetime.datetime(2020, 11, 7, 15, 46, 48, 191772, tzinfo=<UTC>), 'cash_book_id': None, 'supplier_id': 1128, 'type': 'pc' } When I joined the supplier table I was disappointed to find that the columns are not included in the dict. Below, t.__dict__ is the same as above. I noticed that the Supplier model instance is cached inside of t._state so I guess I could create my own method which all models inherit from which does what i want - all the columns from all tables inside a dict. But I wondered if anybody knew a way of doing this sort of thing out of the box? t = PurchaseHeader.objects.select_related("supplier").first() t.__dict__ -
Ckeditor texteditor not appearing in django admin where RichTextfield is applied
I have tried everything but the texteditor is not appearing in the admin page in the richtextfield type. I installed django ckeditor and have the following in the settings.py: Richtextfield pic CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" #ckeditor configs #todo CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'width': 1000, 'height': 400 }, } DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') My urls is as follows: urlpatterns = [ path('admin/', admin.site.urls), path('', admin.site.urls), path('', include('apps.accounts.urls')), path('', include('apps.blogs.urls')), path('', include('apps.enquiry.urls')), path('', include('apps.packages.urls')), path('', include('apps.booking.urls')), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have even tried collectstatic and every files are collected but still the richtextfield appears blank. How to solve this?? -
Django enum named groups
I want a listing to be able to have a specific category, so the seller will choose a general category and then onto a more specific one, for example: Men's Wear: Jeans: Skinny Fit Slim Fit Regular Fit Pants: Slim Fit Formal Casual Women's Apparel: Tops: Tunics Denim: Jeans I tried the named groups like in django docs: https://docs.djangoproject.com/en/3.0/ref/models/fields/#field-choices-named-groups MEDIA_CHOICES = [ ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ] But when I tried, it gives the error product.Listing.category: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. here is my code: class Listing(models.Model): CATEGORY = [ ('Women\'s Apparel', ( ('Dresses', ( ('party_dresses', 'Party Dresses'), ) ), ), ), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) description = models.CharField(max_length=255) new_condition = models.BooleanField() category = models.CharField(choices=CATEGORY, max_length=255) why is it showing error ? is it because the enum groups cant be nested more than 1 level ? thank you -
Is there a way to send a form class as parameter to a function in a template in django?
I'm creating a website that has multiple pages that each has one form. This one form on each page has an "add", "modify" and "delete" button. I need to create a lot functions to process all this because they are on different pages working with different form classes and model classes. To create a more general approach it would be usefull if I could just pass the form class and/or model class as a parameter in a template to a view (se example below). When writing a capture pattern for this in the urls.py file I cant find anything to capture a reference to an object though like a form class or model class... I only see that you can capture strings, integers and so on. What im thinking about is something like this: {% url '' id form_class %} where id and form class are the parameters to the view. Is there any way to actually do this ? I want to do this so I dont have to write add, modify and delete view functions for every form on every page and instead have one add, modify and delete for every form without having if loops and checking … -
Delete an object with a large number of CASCADE models on Django
I am running into an issue where I cannot delete user accounts with Django. The problem is that there are several other models in code that have the field: user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) These models themselves have other models that are set to be deleted with on_delete=models.CASCADE when they are deleted. So when I try to delete a user that had a lot of activity on my website, it can quickly become tens of thousands of items to delete. This causes the delete operation to never end and the account to not get deleted. Worse, only some of the content gets deleted as the operation is interrupted. How should I handle deleting a model with many CASCADE delete linked to it? I am using Django 3.1 with a MySQL db. -
Django: posting information to multiple models with one html form
I'm building my first solo django project right now so I'm learning a lot. I've run into a problem that I can't think how to fix. For a fantasy football app project, I've represented each type of player position with their own model. Like this... class Quarterback(models.Model): name = models.CharField(max_length=20) class Runningback(models.Model): name = models.CharField(max_length=20) class Widereceiver(models.Model): name = models.CharField(max_length=20) class Tightend(models.Model): name = models.CharField(max_length=20) class Kicker(models.Model): name = models.CharField(max_length=20) I have a "choose player" page that uses javascript to fill in model forms that I've made for each player model. This is my forms.py class Quarterbackform(forms.ModelForm): class Meta: model = Quarterback fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'QB_name'}) } class Runningbackform(forms.ModelForm): class Meta: model = Runningback fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'RB_name'}) } class Widereceiverform(forms.ModelForm): class Meta: model = Widereceiver fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'WR_name'}) } class Tightendform(forms.ModelForm): class Meta: model = Tightend fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'TE_name'}) } class Kickerform(forms.ModelForm): class Meta: model = Kicker fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'K_name'}) } My views.py has this function to save player selections to their respective model. def emp(request): url = 'hidden' r = requests.get(url.format()).json() player_data = [] #print(r) … -
django import export error: Line number: 1 - import_obj() takes 3 positional arguments but 4 were given
I've upgraded a django project to the latest version of django 3.1.2 and also one of it's dependencies django-import-export which as it says helps import data to models, previously importing csv was working ok but with the update of it also to the latest version i get this error Line number: 1 - import_obj() takes 3 positional arguments but 4 were given DAVAN, LEMETEI, M, 37291003, , 4827, , KAMPI YA KANZI, , , , , , , , , 7/9/2020, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/import_export/resources.py", line 662, in import_row self.import_obj(instance, row, dry_run) TypeError: import_obj() takes 3 positional arguments but 4 were given Line number: 2 - import_obj() takes 3 positional arguments but 4 were given PARASHINA, NTANIN, M, 12740086, , 4828, , KAMPI YA KANZI, , , , , , , , , 7/9/2020, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/import_export/resources.py", line 662, in import_row self.import_obj(instance, row, … -
RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended
When I am daemonizing the celery worker it is giving me the above warning along with the following error: Traceback (most recent call last): File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 370, in start return self.obj.start() File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 316, in start blueprint.start(self) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 592, in start c.loop(*c.loop_args()) File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/loops.py", line 91, in asynloop next(loop) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 299, in create_loop item() File "/var/app/venv/env/lib/python3.7/site-packages/vine/promises.py", line 170, in call return self.throw() File "/var/app/venv/env/lib/python3.7/site-packages/vine/promises.py", line 167, in call retval = fun(*final_args, **final_kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 336, in _schedule_queue queue, callback=promise(self._loop1, (queue,)), File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 352, in _get_bulk_async return self._get_async(queue, maxcount, callback=callback) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 362, in _get_async qname, count=count, connection=self.asynsqs, File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 456, in asynsqs region=self.region File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/sqs/connection.py", line 27, in init **kwargs File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 186, in init **http_client_params) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 151, in init self._httpclient = http_client or get_client() File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/init.py", line 22, in get_client client = hub._current_http_client = Client(hub, **kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/init.py", line 13, in Client return CurlClient(hub, **kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 43, in init raise ImportError('The curl client requires the pycurl library.') ImportError: The curl client requires the … -
Django 1.6.5 urlreverse change default directory name
import django from django.core.urlresolvers import reverse print django.get_version() # 1.6.5 app -> inventory url = reverse('product', slug='foo-bar') url = '/inventory/foo-bar/ How do I get the django url to reverse and change the name of directory? For example, I am trying to achieve url='/product/foo-bar/' -
How can I search data from a table using a field from the 2 tables below
So, maybe my questions is noth enaught clearly... I'll try to show it in example. I have 3 tables: models.py class Department(models.Model): department = models.CharField(max_length=100) activate = models.BooleanField(default=True) def __str__(self): return self.department class Employee(models.Model): noEmployee = models.DecimalField(max_digits=8, decimal_places=0, default=10) # name = models.CharField(max_length=50) surname = models.CharField(max_length=100) department = models.ForeignKey(Department, on_delete=models.CASCADE, default=1) activate = models.BooleanField(default=True) def __str__(self): return str(self.noEmployee) class List_of_tasks(models.Model): myData = datetime.now() formatedDate = myData.strftime("%Y-%m-%d") task = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) responsible = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) start_date = models.DateField('Start date', default=formatedDate) finish_date = models.DateField('Finish date', default=formatedDate) finished = models.BooleanField(default=False) def __str__(self): return self.task And small class in views.py def filter(request): qs = List_of_tasks.objects.all() task_query = request.GET.get('task_contains') department_query = request.GET.get('department_contains') print(task_query) if department_query is not None: dep = Employee.objects.filter(department__department__icontains=department_query) for d in dep: print('department: ', d.noEmployee, d.name, d.surname) for d in dep: dep2 = List_of_tasks.objects.filter(responsible__noEmployee__exact=d.noEmployee) for d2 in dep2: print('Tasks: ', d2.task, d2.responsible) if is_valid_queryparam(task_query): qs = qs.filter(task__icontains=task_query) context = {'queryset': qs,} return render(request, 'appl01/export.html', context) Finding TASKS or RESPONSIBLE persons in table List_of_tasks is easy but I would like to find for example all tasks assigned to department... two tables down... As you can see I created my own method which works as I want but is not … -
Registration user with multiple usernames - Django REST
I'm trying to implement a user registration and authentication using django rest framework and I'm not sure how to implement it. The thing is that I want a user to have multiple usernames/nicknames so that's why I have a little bit troubles. The current models I have: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=50, unique=True, error_messages={ 'unique': _("Email already exists."), }, ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) gender = models.IntegerField(default=GENDER_MALE, choices=GENDER_CHOICES) date_of_birth = UnixDateTimeField(null=True, blank=True, ) ip = models.GenericIPAddressField(null=True) USERNAME_FIELD = 'email' class Meta: verbose_name = _('user') verbose_name_plural = _('users') class UserNicknames(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) username = models.CharField(max_length=10, null=False, unique=True, validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) is_current = models.BooleanField(default=False) As you can see I have the User model just like the django one but without the username and UserNicknames which contains the user nicknames (the UserNicknames.user field is the foreign key to the User.id field). The question is what is right way to implement the registration serializer? Should I get all the fields in User and UserNicknames and then do the logic or there is …