Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm having an issue with this. Trying to install mysqlclient with 'pip install mysqlclient' but it's bringing out this error
Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. exit code: 1 [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-hyrw6bdf/mysqlclient_3a83953da9be4f2d8196d1a7de0c4479/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-hyrw6bdf/mysqlclient_3a83953da9be4f2d8196d1a7de0c4479/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-hyrw6bdf/mysqlclient_3a83953da9be4f2d8196d1a7de0c4479/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. note: This is an issue with the package mentioned above, not pip. -
Using concurent.futures raise me a strange AttributeError on django python with channels
I'm facing an issue trying to use the concurrent.futures package in python. I'm working on a website using django and channels to perform asynchronous comunication. I have to load data from many url and i want to be able to do it with multiprocessing. Unfortunately i'm enable to make this code work as it always give me an AttributeError. Could it be related to the architecture of django or channels ? I'm using the ProcessPoolExecutor in a channels receive() function inside a WebSocket Object. Here is a sample of my code : class CreateValuesConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def create_single_value(self, card): print('start create_single_value') condition = Condition.objects.filter(short_name='NM')[0] card_language = Language.objects.filter(short_name='FR')[0] seller_origin = Language.objects.filter(short_name='FR')[0] value = card.create_value(condition, card_language, seller_origin) if value is not None: message = "models.value." + str(value.id) + ' : create | card_name = ' \ + card.name_en.lower() + " | price = " + str(value.cheaper_price) is_error = 0 else: error = ParsingError.objects.filter(card=card)[0] message = error.message is_error = 1 self.send(text_data=json.dumps({ 'message': message, 'is_error': is_error })) print('end') def receive(self, text_data): json_data = json.loads(text_data) extension = Extension.objects.get(pk=json_data["id"]) cards_to_value = Card.objects.filter(extension=extension) today = datetime.now() for card in cards_to_value: values = Value.objects.filter(card=card, date__year=today.year, date__month=today.month, date__day=today.day) for value in values: print('delete' + … -
Is it possible to access to the admin page once the application is uploaded to the internet? | Django
I'm very new on django and I want to ask just a simple question: in the developing phase, I can easily access to the admin page of django. I'm wondering if this is still possible to do when the website will be uploaded. I'm sorry for the trivial question, hope you will help me. -
problems puling data out of django database and testing it
really sorry but a complete beginner here with Django and Python. I am trying to pull some data out of a database so I can assert against it in the testing faze but I am having problems understanding how to get the data out of the model. Any help would be appreciated. My code: Models.py class CurrentAccountState(AccountState): enable_personal_profile = models.BooleanField(default=False) class CurrentAccountSetting(TimestampedModel): ACCOUNT_SEND_TO_OPTIONS = ( ("buyer", _("Receipt sent to the buyer")), ("payment_profile_contact", _("Receipt sent to payment profile contact")), ) account_state = models.ForeignKey( CurrentAccountState, related_name="account_settings", on_delete=models.CASCADE ) payment_profile_id = models.CharField(max_length=36) send_to = models.CharField(max_length=32, choices=SEND_TO_OPTIONS, default="buyer") views.py @action(detail=True, methods=["post"]) def update_state(self, request, pk=None): integration = AccountServiceManager.get_by_name(str(pk)) if not account: raise Http404() return Response("", status=status.HTTP_200_OK) test update_state.py def test_update_state(self): user = self.admin_user self.client.force_login(user) account = AccountFactory( name="account name", enabled=True, provider=str_to_kebab_case("account name") ) payload = { "enable_personal_profile": True, "payment_profile_settings": [ { "payment_profile_id": "Something", "send_to": "buyer", }, { "payment_profile_id": "Something else", "send_to": "payment_profile_contact", } ] } response = self.client.post(f"{self.url}/account/update_state", data=json.dumps(payload), content_type="application/json") assert response.status_code == status.HTTP_200_OK account_account = CurrentAccountSetting.objects.all() assert len(account_account) == 1 assert account_account.enable_personal_payment_profile is True What I am struggling with is understanding how I can pull the data out of the actual database so I can make assertions in the test. Currently the len(account_account) … -
Different users/groups should see different rows when editing post?
Let's say, I have a model: class Post(models.Model): title = models.charfield(max_length=50) content = models.TextField() approved = models.BooleanField(default=False) and I have 2 user groups/types: editor manager Managers can make posts and edit every line of it (title, content, approved). Editors should only be able to edit certain rows, such as Title and Content, they shouldn't be able to edit the approved field, they shouldn't even see it. Is there a way to do this? I want to hide some inputs based on the user's role/group they're in. -
How to make/use Navigations Menu for Header and Sider in ReactJS using Django Rest API?
Hi There, I want to make my header menu using Django Rest API based on roles/groups. I am using ReactJS as Frontend and Django as Backend. It's like users can see and use links based on their roles/Groups in the Rest api. Any Idea? -
Django model validation not raising Exception on full_clean()
I have a Model and ModelForm with custom validator (which only allows "H" or "A" in the CharField): def home_away_valid(value): return value == 'H' or value == 'A' class Team(models.Model): name = models.CharField(max_length=180) home = models.CharField(max_length=2, validators=[home_away_valid], default='H', db_index=True) class TeamForm(ModelForm): class Meta: model = Team fields = ['home', 'name'] However when I run full_clean() with another value (not H or A) it doesn't not raise a validation exception: try: team = TeamForm({ 'name': 'Test Team', 'home': 'S' }) team.full_clean() new_team = team.save() print(new_team.id) except ValidationError as e: print(e) Why does this not raise an Exception? (I have tried doing the full_clean() on both the ModelForm and Model, neither raises an Exception) -
How i can remove or hide the second lign of this table [duplicate]
I have a table this is my code How i can remove all the second lign 'Date'? new = output_df.groupby([output_df['Date'].dt.date, 'type']).size().unstack(fill_value=0) new.sort_values(by=['Date'], ascending=True) new['Total per date'] = output_df.groupby([output_df['Date'].dt.date])['type'].count() new.loc['Total', :] = new.sum(axis=0) new = new.astype(int) enter image description here -
Django filter where model doesn't have a foreign object or foreign field is equal to
I have two models Community and UserCommunity Community Model class Community(models.Model): # Community name name = models.CharField(max_length=64) slug = models.CharField(max_length=40, blank=True) admins = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="admins", blank=True ) admins = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="admins", blank=True ) members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="members", blank=True, ) ------ UserCommunityModel class UserCommunity(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="user" ) group = models.ForeignKey( Community, on_delete=CASCADE, related_name="group") role = models.CharField(max_length=15, blank=True, null=True) # True is in community, false is not in community active = models.BooleanField(null=True, blank=True) I need to get all the community objects where a user is not part of the community I've tried using this Community.objects.filter(group__user=request.user.id, group__active=False,state=location.state, group_discoverability="public").exclude( hofAdmins__isnull=True, admins__isnull=True, members__isnull=True)[:10] But this returns the communities which has a UserCommunity object, UserCommunity object is created when user joins the community. Any help would be appreciated, thanks! -
ImportError: cannot import name 'ExceptionReporterFilter'
Getting an error in my Django project. ImportError: cannot import name 'ExceptionReporterFilter' I'm using it in the following class from django.views.debug import ExceptionReporterFilter class JSONExceptionReporterFilter(ExceptionReporterFilter): pass I'm using Django==2.2.1 What can be the fix for this? -
Print Multiselect checkbox options of 1 input field in 4 columns
I am using Django Form to get one input from user, this is a check-box field where user can select multiple values. Since the number of options are more than 100, I am trying to show them in 4 columns based on option values. I mean, if option value starts with 'A-' then in first column if option value starts with 'B-' then second column so on. Example: [ ] A-Opt-1 | [ ] B-Opt-6 | [ ] C-Opt-11 | [x] D-Opt-16 [ ] A-Opt-2 | [x] B-Opt-7 | [ ] C-Opt-12 | [x] D-Opt-17 [ ] A-Opt-3 | [ ] B-Opt-8 | [ ] C-Opt-13 | [ ] D-Opt-18 [x] A-Opt-4 | [ ] B-Opt-9 | [x] C-Opt-14 | [ ] D-Opt-19 [ ] A-Opt-5 | [ ] B-Opt-10 | [x] C-Opt-15 | [ ] D-Opt-10 -
Django Rest Framework:How to calculate percentage of video duration?
In my project, I have a video section in which I want to calculate the percentage of time the user will watch. Through the below URL can access the details of video URL : video/video_id output: "video": { "id": "84e7288c-dc09-44aa-850c-08546a98ffde", "deleted": null, "datetime_created": "02/04/2022 06:56 AM", "datetime_updated": "02/04/2022 06:56 AM", "video_name": "video name3", "description": "description about video", "duration": "00:33:20", "create_date": "02/04/2022 06:56 AM", "video_type": "micro", "file_url": "https://vimeo.com/216763352", "general_status": "high", "review_status": "draft", "video_number": "VD6129", "created_by": null }, "duration": "00:33:20" is the total duration of video. How to calculate the percentage of video time that the user is watching, if passing the time in total seconds like { "time":200 } -
best way to edit or update object in Django
i'm new in django and django rest framework, i create an app with multiple models and they have ForeignKey and ManytoManyField My question is what is the best way to add object, update field , set value (ForeignKey),or create object in django when have multiple models with multiple relations Signals , override save , create , update method in serializers or anything else -
Generate sphinx documentation with Django tags
I am trying to generate a sphinx documentation using the Read the Docs template for a Django project. I am documenting it using the Django tags For example Download :model:`ManagementSoftware.Order` CSV When I try to generate the documentation with the command make html I get the error docstring of ManagementSoftware.views.DownloadOrdersCSV:1: ERROR: Unknown interpreted text role "model". What should I do? Is there any sphinx extension to include those tags? Thanks in advance -
How to do model instance in django update views
views.py def visitor(request): fruser = FRUser.objects.get(id=1) if request.method == "POST": fruser.uid = request.POST.get('visitor_nric_no') fruser.name = request.POST.get('name') fruser.company_name = request.POST.get('company_name') fruser.user_type = request.POST.get('userType') fruser.visit_purpose = request.POST.get('purposeOfVisit') fruser.valid_from_date = request.POST.get('validFrom') fruser.valid_till_date = request.POST.get('validTill') fruser.save() print(fruser.name) return render(request,'kiosk/visitor-checkIn/photo-registration.html',{'fruser':fruser}) else: return render(request, 'kiosk/visitor-checkIn/visitor-new-registration.html') models.py class FRUser(models.Model): image = models.ForeignKey(to=Image, on_delete=models.CASCADE, null=True) frtemplate = models.ForeignKey(to=FRTemplate, on_delete=models.CASCADE, null=True) name = models.TextField(null=True) user_type = models.TextField(null=True) uid = models.TextField(null=True) company_name = models.TextField(blank=True, null=True) visit_purpose = models.TextField(blank=True, null=True) employee_number = models.TextField(blank=True, null=True) designation = models.TextField(blank=True, null=True) valid_from_date = models.DateField(null=True) valid_till_date = models.DateField(null=True) valid_from_time = models.TimeField(null=True) valid_till_time = models.TimeField(null=True) is_blacklisted = models.BooleanField(default=False, null=True) is_other_visit_purpose = models.BooleanField(default=False, null=True) is_active = models.BooleanField(default=True, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='+', null=True) modified_date = models.DateTimeField(auto_now=True, null=True) modified_by = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='+', null=True) html <form id="visitorRegistration" data-bind="submit: save" method="post" action="/kiosk/visitor/{{fruser.id}}"> <div class="row"> <div class="col-lg-4 col-12"> <div class="form-group"> <label class="text-white float-left pl-3">User Type</label> <input type="text" class="form-control bord-r form-control-s" value="{{ fruser.user_type }}" disabled="disabled" name="userType"> </div> </div> <div class="col-lg-4 col-12"> <div class="form-group"> <label class="text-white float-left pl-3">Name <i class="text-danger">*</i></label> <input type="text" class="form-control bord-r form-control-s" name="name" data-bind="value: name" value="{{ fruser.name }}" > </div> </div> <div class="col-lg-4 col-12"> <div class="form-group"> <label class="text-white float-left pl-3">NRIC/FIN Number</label> <input type="text" class="form-control bord-r form-control-s" name="visitor_nric_no" value="{{ fruser.uid }}"> </div> </div> <div class="col-lg-4 … -
DRF: FieldError Cannot resolve keyword 'microcontrollers' into field when trying to join models
I am trying to serialize two models so that i get the name field from one and the rest of the data from another. However when i try to join them i get the following error. FieldError at /api/CUTAQ/SE1/testdata/ Cannot resolve keyword 'microcontrollers' into field. Choices are: altitude, co, frame, hum, latitude, longitude, microcontroller, microcontroller_id, name, no2, o3, pres, so2, temp, time_received, time_taken I am fairly new to Django and i am trying to understand what part of the code is causing the problem. Models.py class MeasurementsBasic(models.Model): microcontroller = models.OneToOneField('Microcontrollers', related_name='measurements_basic', primary_key=True, on_delete=models.CASCADE) time_taken = models.DateTimeField() time_received = models.DateTimeField(blank=True, null=True) frame = models.IntegerField(blank=True, null=True) temp = models.FloatField(blank=True, null=True) hum = models.FloatField(blank=True, null=True) pres = models.FloatField(blank=True, null=True) co = models.FloatField(blank=True, null=True) no2 = models.FloatField(blank=True, null=True) o3 = models.FloatField(blank=True, null=True) so2 = models.FloatField(blank=True, null=True) latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True) altitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True) name = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = True db_table = 'measurements_basic' unique_together = (('microcontroller', 'time_taken'),) class Microcontrollers(models.Model): name = models.CharField(max_length=25) serial_number = models.CharField(max_length=20, blank=True, null=True) type = models.CharField(max_length=15, blank=True, null=True) software = models.CharField(max_length=20, blank=True, null=True) version = models.CharField(max_length=5, blank=True, null=True) date_installed = models.DateField(blank=True, null=True) date_battery_last_replaced = models.DateField(blank=True, null=True) … -
Convert a list into Django Queryset
Here I am trying for a different way. My products will show in two way if user is passing location then first take the location and then usually do my filter using django-filters. It is working fine my filter unless I have problem with list object has no attribute model. I am trying to simplify my problem. I have multi vendor ecommerce and now user want to see the closeby vendor products and then advance filtering. everythin will be okay If I can convert a list into queryset. this is my views.py @api_view(['GET']) def getProducts(request): nearby_locations = get_locations_nearby_coords(23.7106, 90.4349, 5) if(nearby_locations.count() > 0): products = [] for i in nearby_locations: print(i.name) products.extend(list(Product.objects.all().filter(user__id=i.id))) filterset = ProductFilter(request.GET, queryset=products) if filterset.is_valid(): products = filterset.qs else: products = Product.objects.all() filterset = ProductFilter(request.GET, queryset=products) if filterset.is_valid(): products = filterset.qs page = request.query_params.get('page') paginator = Paginator(products, 10) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if page == None: page = 1 print(products) page = int(page) serializer = ProductSerializer(products, many=True) return Response({'products': serializer.data, 'page': page, 'pages': paginator.num_pages}) in my first if i have a list of products and then I am passing this list as queryset because I have to … -
Optimization queries with foreign key to self model
I have following models.py class Comment(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="replys") ... class Notification(models.Model): comment = models.ForeignKey(Comment, null=True, on_delete=models.CASCADE) ... and serializers.py class CommentSerializer(serializers.ModelSerializer): replys = serializers.SerializerMethodField() ... def get_replys(self, obj): queryset = obj.replys.select_related("author", "author__avatar").prefetch_related("author__engagement") serializer = CommentSerializer(queryset, many=True, context=self.context) return serializer.data class NotificationSerializer(serializers.ModelSerializer): comment = CommentSerializer(read_only=True) ... class Meta: model = models.Notification fields = "__all__" and service.py from django.contrib.auth import get_user_model def send_notifs(recipient): from vitalvoices.vital_notif.serializers import NotificationSerializer latest_notifications = Notification.objects.select_related( "comment", "comment__author", "comment__author__avatar", "comment__topic", "comment__parent", ).prefetch_related( "comment__author__engagement", "comment__reports", "comment__parent__replys", ).filter(recipient=recipient, checked=False).order_by("-pk")[:20] notifications_data = NotificationSerializer(latest_notifications, many=True).data After queries optimization I have this log SQL - SELECT "discussions_comment"."id", "discussions_comment"."author_id", "discussions_comment"."topic_id", "discussions_comment"."parent_id", "discussions_comment"."body", "discussions_comment"."created_at" FROM "discussions_comment" WHERE "discussions_comment"."parent_id" IN (82) Time - 0.001 SQL - SELECT "discussions_comment"."id", "discussions_comment"."author_id", "discussions_comment"."topic_id", "discussions_comment"."parent_id", "discussions_comment"."body", "discussions_comment"."created_at", "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", ... FROM "discussions_comment" LEFT OUTER JOIN "users_user" ON ("discussions_comment"."author_id" = "users_user"."id") LEFT OUTER JOIN "core_mediafile" ON ("users_user"."avatar_id" = "core_mediafile"."id") WHERE "discussions_comment"."parent_id" = 154 Time - 0.031 I have many queries such as second query. Maybe this problem linked with recursive relation (ForeignKey to self model). How can to optimize these queries using Django ORM? -
Use or for filter combination
I have two query like this below, Both,It works correctly, but I want to use OR for these sentences. I have ideas to use Q But it has complex filter. cls.objects.filter(point1__gt=0).filter(point1__lt=100) cld.objects.filter(point2__gt=0).filter(point2__lt=100) Is there any method to use OR for this sentenses? -
href attribute in django templates not fetching data?
I have a series of buttons in my frontend that display dynamically produced data like shown I am creating a href for each of these buttons where I am sending that dynamic data to a views.py using URL's. href in HTML: <a href="{% url 'test_this' button_type='IP' test_data=stats_data.location %}"><button type="button" >{{stats_data.location}} Service </button></a> urls.py pattern : urlpatterns = [ path('', dashboard_page, name ="home"), path('test/<str:button_type>/<str:test_data>', test_page, name = "test_this") ] URL produced on clicking the button: http://127.0.0.1:8000/dashboard/test/IP/202.154.121.13 My URL seems to be correct but I get this error: Reverse for 'test_this' with keyword arguments '{'button_type': 'IP', 'test_data': ''}' not found. 1 pattern(s) tried: ['dashboard/test/(?P<button_type>[^/]+)/(?P<test_data>[^/]+)$'] I dont get an error when I hard code Button_type and test_data values. Why am I not able to parse test_data=stats_data.location into <str:test_data>? -
VSCode: failed to load available options for Django's `load` template tag?
Suppose down there I can choose crispy_forms_tags (since I have installed) and others. The "Loading..." just persists without listing all available options. How to fix it please? Thank you. -
How can I check my society models name contains city's id or not?
I want to check my society's name contains the city's id and locality's id or not. First I want to iterate each society name and get city id by locality id and check that city name is appended at the end of the society name or not if yes then update all the society names by removing the city name. Second Then again I want to iterate each society name and get locality id and check the locality name is appended at the end of the society name or not if yes then update all the society names by removing the locality name. society.py class Society(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. locality = models.ForeignKey('Locality', models.DO_NOTHING, db_column='localityId', blank=True, null=True, related_name='society_set') # Field name made lowercase. dot_com_database_id = models.IntegerField(db_column='dotComDatabaseId', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'societies' locality.py class Locality(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. city = models.ForeignKey('City', models.DO_NOTHING, db_column='cityId', blank=True, null=True, related_name='locality_set') # Field name made lowercase. connect_database_id … -
Chained Dropdown in ModelFormset_Factory - Django
I want chained dropdown list in model formset. I have 4 models in my app App_Prod - Category, Product, OrderInfo, Order In my form, I used two views combinely. OrderInfo and Order So the choice list of product field of the Order model should be dependent on the category field of the OrderInfo model. Like if I select Electronics category the choice list should return only laptop and mobile option instead of showing all. See the image for your better understanding. Please suggest me what should I edit in my codes, or is there any other way to do so. models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) def __str__(self): return self.name class OrderInfo(models.Model): category = models.ForeignKey(Category, related_name='orderInfo', on_delete=models.CASCADE) date = models.DateField() def __str__(self): return self.category.name class Order(models.Model): info = models.ForeignKey(OrderInfo, related_name='orders', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='productName', on_delete=models.CASCADE, null=True) quantity = models.IntegerField() def __str__(self): return self.product.name forms.py class OrderInfoForm(forms.ModelForm): date = forms.DateField(widget=DateInput) class Meta: model = OrderInfo fields = ["category","date",] class OrderForm(forms.ModelForm): class Meta: model = Order fields = ["product","quantity",] widgets = { 'product': forms.Select(attrs={'class': 'formset-field form-control'}), 'quantity': forms.NumberInput(attrs={'class': 'formset-field form-control'}), } views.py def order_create(request): … -
How can I filter items in DjangoRestFramework?
I am complete beginner and I made a django project a while ago. Its main purpose is adding restaurants and categories and food menu respectively. For now, it is working well, if I go to the required restaurant, it shows its categories. But now, I want to improve it via Vuejs and that's why I'm trying to make Django REST API. But I can't filter categories and food according to their restaurant, because category model is not directly connected to restaurant model. My models.py is: from django.db import models from django.conf import settings class Restaurant(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="restaurant", on_delete=models.CASCADE) name = models.CharField(max_length=256, db_index=True) slug = models.SlugField(max_length=256, unique=True) logo = models.ImageField(upload_to='logos/', blank=True) def __str__(self): return str(self.name) class Category(models.Model): name = models.CharField(max_length=256, db_index=True) slug = models.SlugField(max_length=256, unique=True) icon = models.ImageField(upload_to='categories/', blank=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return str(self.name) class Food(models.Model): restaurant = models.ForeignKey(Restaurant, related_name='foods', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='foods', on_delete=models.CASCADE) name = models.CharField(max_length=256, db_index=True) slug = models.SlugField(max_length=256, blank=True) price = models.IntegerField(default=0) description = models.TextField(blank=True) image = models.ImageField(upload_to='foods/', blank=True) available = models.BooleanField(default=True) def __str__(self): return str(self.name) As you see, category class is not directly connected to restaurant. It is filtered with views.py. My views.py is: from django.shortcuts … -
can't login with facebook using allauth library using Django because of CSRF token and gave me CSRF verification failed. Request aborted
i have a server deployed in AWS using Django and every thing working fine until i tap on login with facebook Button it shows the normal facebook login popup and after typing my email and password instead of going to the next page it gave me CSRF verification failed. Request aborted. as you can see i've {% csrf_token %} in the code for showing login with facebook button using js_sdk: {% extends 'restaurant/base_auth.html' %} {% load bootstrap4 %} {% block title %}Akalat-Shop{% endblock %} {% block heading %}Akalat-Shop - Sign In{% endblock %} {% block content %} {% load socialaccount %} {% providers_media_js %} <a href="{% provider_login_url "facebook" method="js_sdk" %}">Login with Facebook</a> <form action="" method="post"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-primary btn-block">Sign In</button> </form> <div class="text-center mt-3"> <a href="{% url 'restaurant_sign_up' %}">Become a Restaurant</a> </div> {% endblock %} also i tried those in settings.py : LOGIN_REDIRECT_URL = '/' ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' SOCIAL_AUTH_REDIRECT_IS_HTTPS = True //all configurations of facebook login my views.py i've checked also for using @csrf_exempt: from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required(login_url="/restaurant/sign_in/") def restaurant_home(request): return redirect(restaurant_order) from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required(login_url="/restaurant/sign_in/") def restaurant_order(request): if request.method == "POST": order = Order.objects.get(id=request.POST["id"]) if order.status == …