Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not saving the record into mongodb DB in Django, Actually I am trying explore multiple different DB (Postgresql, Mongodb) in a single app
I am trying to use multiple different DB in a single app(todo). I am using Djongo package for dealing mongodb. Settings.py DATABASES = { 'default':{}, 'sql_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'USER': '******', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '5432', }, 'mongodb':{ 'ENGINE': 'djongo', 'NAME': 'mongo_db' } } todo/models.py class Task(models.Model): todo = models.CharField(max_length=200) status = models.BooleanField(default=False) def __str__(self): return self.todo todo/serializers.py class TodoSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' todo/views.py @api_view(['POST']) def todoCreate(request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() serializer.save(using='mongodb') return Response(serializer.data) it successfully saved the record into 'sql_db' but not save in the 'mongodb'. -
Updating two fields at once with choices in django admin
I have x and y in my model as DecimalField. Something like this: class MyModel(models.Model): x = models.DecimalField() y = models.DecimalField() I want user to select these x and y from a list of dictionaries I have. It has to be selected together. As an example: [ { "x": 1, "y": 2, }, { "x": 3, "y": 4, }, ] We have two dictionaries in the example list so user should see two choices in a dropdown. Choice one with x: 1 and y: 2 Choice two with x: 3 and y: 4 Do I need to customize some widget or field for that? If I need how can I do that? -
Translation with variable is not working in django templates
I am using django translation to swith language. It is working fine but when get variable from database and try to translate in template, it's not working but it's working in views. example: msg = ugettext_noop('New van booking has been made - %(pk)d') % {'pk': booked.pk} Notification.objects.create(note_category='4', message=msg, role='Admin', booking=booked, van=van) I have also tried msg = gettext('New van booking has been made - %(pk)d') % {'pk': booked.pk} Notification.objects.create(note_category='4', message=msg, role='Admin', booking=booked, van=van) and message is as New van booking has been made - 8. I have also done makemessages and compilemessage #: .\van\views.py:563 #, python-format msgid "New van booking has been made - %(pk)d" msgstr "" "Une nouvelle réservation de van a été faite. Numéro de réservation - %(pk)d" but when I loop this in template, that does not work. {% for note in admin_note %} <span class="d-block">{% trans note.message noop %}</span> {% endfor %} it only shows New van booking has been made - 8 in all languages. But it's working in view fine. print(gettext('New van booking has been made - %(pk)d') % {'pk': 8}) Does anyone know how can I get translation in template. NOrmal translation is working fine. -
Autocomplete with API not working in Django
I am trying to autocomplete cities in Django and it is not working. I think something is wrong with my form. HTML: <form method="post"> <input id="search_city" name="city" value="{{ request.GET.city }}" type="text" class="form-control input-lg" onkeyup="searchOpen()" placeholder="Los Angeles, CA"/> ..... A bunch more form entries ..... </form> Then we have the javascript, ajax to call the API to do the Autocomplete: function searchOpen() { var search = $("#search_city").val() var data = { search: search }; $.ajax({ url: '/api/get_city_state/', data: data, dataType: 'jsonp', jsonpCallback: 'searchResult' }); function searchResult(data) { $( "#search_city" ).autocomplete ({ source: data }); }; Here is my api function in views.py: def get_city_state(request): if request.is_ajax(): q = request.GET.get('city', '') results = search.find_city(q, best_match=False) data = request.REQUEST['callback'] + '(' + simplejson.dumps(result) + ');' else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) -
Create or update django redt framework
Hi all I have a drf database and device but device can only read and write I need do when device is doing a post request django checks if it doesnt exist then post it but if it exists update old data.Thanks -
Django dynamically create not equal q objects
I'm working on creating dynamic filters using nested AND / OR logic, and would like to include NOT as an option. This leverages Q objects to create the nested AND / OR logic. The class takes in a json object like so: filters = { 'and': { "url__is": "www.test.com", "name__is": "test" } } This gets compiled down to .filter(Q(url__is='www.test.com') and Q(name__is='test') This works via a recursive function that really just does this on each level of the json tree. return source_queryset.filter(reduce(and_, filter_list)) and_ is from the python operator library and has been working great. I'd like to add NOT as an option as well though, and can't seem to find an equivalent option to reduce a list of Q objects to. Does anyone know a way to use reduce in a way that creates the idea of not equal to a list of q objects? -
Cannot import name 'RadioChoiceInput' from 'django.forms.widgets' (Django 1.19 to 3.2 migration)
I have the following widgets.py file from a Django 1.19 version to upgrade to Djando 3.2 version. I am getting the error: from django.forms.widgets import RadioSelect, RadioChoiceInput ImportError: cannot import name 'RadioChoiceInput' from 'django.forms.widgets' (my_env/lib/python3.9/site-packages/django/forms/widgets.py) This is the code: from django.forms.widgets import RadioFieldRenderer, RadioChoiceInput class RadioChoiceInput2(RadioChoiceInput): def render(self, name=None, value=None, attrs=None, choices=()): # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs try: self.choice_label = locale.format("%.2f", float(self.choice_label), grouping=True) except ValueError: pass return format_html( '<label class="radio" {}>{} <i></i> {}</label>', label_for, self.tag(attrs), self.choice_label ) class RadioFieldRenderer2(RadioFieldRenderer): outer_html = '{content}' inner_html = '<section class="col col-2">{choice_value}{sub_widgets}' \ '<i></i></section>' last_inner_html = '<section class="col col-1 last">{choice_value}{sub_widgets}' \ '<i></i></section>' choice_input_class = RadioChoiceInput2 def render(self): id_ = self.attrs.get('id') output = [] cc = len(self.choices) for i, choice in enumerate(self.choices): choice_value, choice_label = choice if isinstance(choice_label, (tuple, list)): attrs_plus = self.attrs.copy() if id_: attrs_plus['id'] += '_{}'.format(i) sub_ul_renderer = self.__class__( name=self.name, value=self.value, attrs=attrs_plus, choices=choice_label, ) ih = self.inner_html if i == 2: ih = self.last_inner_html sub_ul_renderer.choice_input_class = self.choice_input_class output.append(format_html(ih, choice_value=choice_value, sub_widgets=sub_ul_renderer.render())) else: ih = self.inner_html if i == cc-1: ih = self.last_inner_html w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i) output.append(ih.format( choice_value=force_text(w), sub_widgets='') ) return format_html(self.outer_html, id_attr=format_html(' id="{}"', id_) … -
DateField shows None in template, but correct date in Django Admin
I have this field in my model cancel_date = models.DateField(null=True, blank=True), but it's acting weirdly. In my admin it shows correctly with the date added, but when returning it in the template as {{model.cancel_date}}, it displays None instead. Is there a reason why that would be? -
Getting data via a glue table in Django
I have a relationship as such: dictionary table dictionary_child_char table dictionary table (same as first table) Here are my models: class Dictionary(models.Model): traditional = models.CharField(max_length=50) simplified = models.CharField(max_length=50) pinyin_numbers = models.CharField(max_length=75) pinyin_marks = models.CharField(max_length=75) translation = models.TextField() level = models.IntegerField() frequency = models.IntegerField() idiom = models.BooleanField() child_char = models.ManyToManyField('Dictionary', through='DictionaryChildChar', null=True) disabled = models.BooleanField() simptradsame = models.BooleanField() class Meta: db_table = 'dictionary' indexes = [ models.Index(fields=['simplified', ]), models.Index(fields=['traditional', ]), ] class DictionaryChildChar(models.Model): class Meta: db_table = 'dictionary_child_char' from_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="from_dictionary") to_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="to_dictionary") word_order = models.IntegerField() Each dictionary item has a potential many to many relationship to another dictionary item (it's Chinese characters, so each word might be made up of several constituent characters) I am trying to see these relationships, and actually grab the dictionary entry for each: dictionary = Dictionary.objects.filter(Q(simplified=char) | Q(traditional=char)).prefetch_related('child_char__to_dictionary')[:1] item = dictionary[0] item.to_dictionary.all().values() However when I do this: print(item.to_dictionary.all().values()) I get this: <QuerySet [{'id': 92661, 'from_dictionary_id': 37607, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92662, 'from_dictionary_id': 37608, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92663, 'from_dictionary_id': 37634, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92664, 'from_dictionary_id': 37635, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92665, 'from_dictionary_id': 58861, 'to_dictionary_id': 37589, 'word_order': 1}]> How, instead of the to_dictionary_id, do I actually … -
Django Rest Framework - & on method field not working as expected
In my filterset I am doing the below: class ItemFilter(FilterSet): entry_date__gte = DateTimeFilter(field_name='entry_date', method=entry_gte_filter) entry_date__lte = DateTimeFilter(field_name='entry_date', method=entry_lte_filter) class Meta: model = Item fields = ('name', 'qty', 'entry_date__gte', 'entry_date__lte') For some reason I have to use the method field here and cannot give the lookup expr directly My methods look like below: def entry_gte_filter(queryset, name, value): name = f"{name}__gte" queryset = Item.objects.annotate( detail=models.Exists(Detail.objects.filter( **{name: value, 'id': models.OuterRef('id')}))).filter(detail=True) return queryset and def entry_lte_filter(queryset, name, value): name = f"{name}__lte" queryset = Item.objects.annotate( detail=models.Exists(Detail.objects.filter( **{name: value, 'id': models.OuterRef('id')}))).filter(detail=True) return queryset However, when I execute the below API: GET /api/items?entry_date__gte=2021-06-29&entry_date__lte=2021-07-04 I get the responses with below entry dates: 2021-06-30T00:00:00 2021-06-11T00:00:00 2021-07-02T00:00:00 I am unclear why a response with 2021-06-11 is being returned when the API mentions entry_date__gte=2021-06-29 To me it looks django filters is not working as expected when method type is used. Could anyone please help me here why djangorestframework is behaving like this and if there is any way to fix this and get the expected behavior? -
problems logging in with Django custom backend
I have been trying to get my Django custom backend to work and it refuses to accept my credentials, which are correct in the database (I have verified this). It just keeps saying email and password are incorrect. I am lost and don't know where to go from here with this. I really need help at this point. VIEWS.PY class MyLogin(LoginView): template_name = 'employees/login.html' success_url = 'employees:emp-home' authentication_form = LoginForm def get_success_url(self): return super().get_success_url() def form_valid(self, form): user = self.request.POST['username'] password = self.request.POST['password'] authenticate(EmpBackend, self.request, user, password) return HttpResponseRedirect(self.get_success_url()) MODELS.PY class EmpUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password=password) user.staff = True user.save() return user class Emp(AbstractBaseUser): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.CharField(max_length=100, default=None, unique=True) first_name = models.CharField(max_length=100, default=None, null=True) last_name = models.CharField(max_length=100, default=None, null=True) username = models.CharField(max_length=100, default=None, null=True) password = models.CharField(max_length=100, default=None) phone = models.CharField(max_length=20, default=None, null=True, blank=True) address1 = models.CharField(max_length=100, default=None, null=True, blank=True) address2 … -
How to to do Mask input in django?
I am working on a little app so I hope you will never mind if I ask some noob questions. I am taking a NIC number from a user but with proper format. Format: xxxxx-xxxxxx-x It means that when a user click in the input field, all the xx should remove and only - will be remains, so if a user types 17301, the - should be appear automatically and then user continue to write 362775 then a - should appear automatically and finally last digit entered by the user 6. This was the complete scenario, I hope I defined it very simple. Input Field Code <div class="col-md-3 mb-3"> <label for="validationCustom10">CNIC</label> <input type="number" class="form-control" id="validationCustom10" placeholder="xxxxx-xxxxxxx-x" name="contact" required> </div> -
Django - Adding custom class to label_tag
I am trying to figure out a way to add a class to my tag on my form. I want to accomplish this without something like crispyforms and if possible not having to edit the html. Based on my knowledge and googling I have spent a few hours trying to figure this out but I cannot haha. I basically just want to output a class in the label element like so: <label class='text-muted' for="id_street_address">Street Address:</label> My model is as follows: class CheckoutForm(forms.Form): street_address = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control' } )) apartment = forms.CharField(required=False, widget=forms.TextInput( attrs={ 'class': 'form-control' } )) country = CountryField(blank_label='(select country)') zip_code = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control' } )) same_billing_address = forms.BooleanField(widget=forms.CheckboxInput()) save_info = forms.BooleanField(widget=forms.CheckboxInput()) payment_option = forms.BooleanField(widget=forms.RadioSelect()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['street_address'].label = 'Street Address' self.fields['apartment'].label = 'Address 2 (optional)' self.fields['zip_code'].label = 'Zip Code' I render my form in the template like this: <form> {% csrf_token %} {% for field in form %} <div class="form-group px-3 my-3"> {{ field.label_tag }} {{ field }} {{ field.help_text }} {{ field.errors }} </div> {% endfor %} </form> Is it possible to do this? Any help is greatly appreciated -
stop Django admin actions from showing project wide
I've got a project with quite a few admin-actions. Currently I'm registering them like so: @admin.action(description='Some admin action description') def do_something_action(self, request, queryset): pass Some of these are being added to the admin-class of another app so I cannot simply add the function directly on the class where they are needed. The problem is that these actions are shown project-wide, on every admin-screen. How can I stop this behaviour, and manually set them where they are wanted? If it matters, it's Django3.2. -
DRF & Pillow: Error: The submitted data was not a file. Check the encoding type on the form
I wrote CreateAPI for Member model. The model contains "photo" ImageField. I need insert onto the photo the watermark and save the result to the field. I do it and add to the request (so serializer can work and save Member with the "updated" photo with the watermark). class MemberCreateView(CreateAPIView): #... def create(self, request, *args, **kwargs): if request.data.get('photo'): # insert watermark img = Image.open(request.FILES['photo'], mode='r') watermark = Image.open('static/members/watermark.png'),mode='r') img.paste(watermark, (0, 0)) # add to request request.data['photo'] = img serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I got this error in Postman json (testing API): { "photo": [ "The submitted data was not a file. Check the encoding type on the form." ] } -
Getting unexpected error while using Django signals
Models.py ROLES = ( ('1', 'student'), ('2', 'creator'), ('3', 'mentor') ) class User(AbstractUser): role = models.CharField(max_length=2, choices=ROLES, default=1) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=40) signals.py from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from student.models import Student, User @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Student.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.student.save() I am trying to add a student in the database whenever a new user registers, for this purpose i am using Django signals but it is giving a strange error that i am not able to understand, error that i am facing is User has no student -
when i start a app in djago with docker-compose it makes its folder under root user whats the problem?
when I want to make changes to files of that app it doesnt let me and wants root password. I tried to change access permissions with chmod and it work but still I think this must be a way so I dont have to do that every time make a app. I use this command to start a app: docker-compose exec web python manage.py startapp appname -
Is it possible to get the value of a Factory boy Faker object for use in another field while making a DjangoModelFactory
I am trying to use factory boy to create a model instance for events, but I am needing to see if I can access the result of a Faker declaration in another field. In the code below, I want to access the start_time field in the end_time field so I can create a datetime that is 1 hour from the start_time. It complains that start_time is a faker object, and not a datetime object. How do I get the Faker class to render its information so I can use it in the end_time field? class EventFactory(DjangoModelFactory): class Meta: model = Event client = factory.SubFactory( ClientFactory, ) customer = factory.SubFactory( CustomerFactory, ) resource = factory.SubFactory( ResourceFactory, ) title = Faker("sentence", nb_words=5) start_time = Faker( "date_time_between_dates", datetime_start=datetime.datetime.now(), datetime_end=datetime.datetime.now() + datetime.timedelta(days=30), ) end_time = start_time + datetime.timedelta(hours=1) all_day = False background_color = None border_color = None text_color = None duration = datetime.timedelta(hours=1) -
Django unit testing: applied to JSON and excel files
first of all i'm sorry if i made English mistakes. I'm new to Django tests, i'm trying to make automation tests for file application. accessed files are (excel, zip, pickle or csv file). Views.py def create(self, request, *args, **kwargs): project_owner = request.POST.get('project_owner') if project_owner is None: return Response('error', status=500) try: # project = Project.objects.filter(id=request.POST.get('project_owner')) project_owner = request.POST['project_owner'] file = request.FILES.get('input_file') project_id = request.POST['projectId'] except (AttributeError, TypeError, Exception): raise AssertionError('The project does not exist') logger.warning('The project does not exist, please create a project!') return Response({'msg': str(e)}, status=500) project = Project.objects.filter(id=project_id).first() if project is None: return Response('project id for filter doesn\'t exist', status=500) if file is None: messages.error(request, 'Upload one of these files: ' '[excel, zip, pickle or csv file]') return HttpResponseRedirect(reverse('project-detail', args=(project_id,))) logger.info(f'Creation of the file: {file.name}') was_handle = False if file.name.endswith(('.zip', '.rar', '.7Z', '.zipx')): was_handle = handle_zip_file(file, project) elif file.name.endswith(('.xlsx', '.xlsm', '.xls', '.xlsb', '.xlt', '.xlr', '.csv')): was_handle = handle_file(file, project) if was_handle: messages.success(request, f'{file.name} successfully uploaded!') else: messages.error(request, 'Upload one of these files: ' '[excel, zip, pickle or csv file]') module_name = project.task.get_module_name() ModuleManager.execute(module_name, 'reloading_properties', request.user.id, project_id) logger.info(f'The file "{file.name}" was created') return HttpResponseRedirect(reverse('project-detail', args=(project_id,))) ---------------- Test_creation view ------------------------- ----------creation file Method-------- def create_file(self, file): csrf_client = Client(enforce_csrf_checks=True) context = … -
How i can filter the query Django form with relations
seniors! Please help with filtering the selection in the fields, how can this be done? using basic creatingView to create a form (ModelForm) Help me please, i have Models: class Filials(models.Model): Fullname=models.CharField(max_length=30,blank=False) Entity=models.CharField(max_length=20,blank=True) City=models.CharField(max_length=15,blank=True) INN = models.IntegerField(max_length=20,blank=True,null=True) def __str__(self): return self.Fullname def get_absolute_url(self): return f'/{self.id}' class Department(models.Model): Filial=models.ForeignKey(Filials, on_delete=models.CASCADE, blank=True) Fullname = models.CharField(max_length=30,blank=False) def __str__(self): return f'{self.Filial}|{self.Fullname}' class SubDepartment(models.Model): Department=models.ForeignKey(Department, on_delete=models.CASCADE, blank=True) Fullname = models.CharField(max_length=30, blank=False) def __str__(self): return self.Fullname class Employee(models.Model): Fullname=models.CharField(max_length=60,blank=False) Position = models.CharField(max_length=30,blank=False) Filial= models.ForeignKey(Filials, on_delete=models.CASCADE, blank=True) Department=models.ForeignKey(Department,on_delete=models.CASCADE, blank=True) SubDepartment=models.ForeignKey(SubDepartment,on_delete=models.CASCADE, blank=True) Fired=models.BooleanField(default=False) Fired_date=models.DateField(blank=True,null=True) Created_date=models.DateField(auto_now=True) Login = models.CharField(max_length=20,blank=False) Password=models.CharField(max_length=15,blank=False) Phone = models.CharField(max_length=12,blank=False) Wordkey=models.CharField(max_length=40,blank=True) def __str__(self): return self.Fullname def get_absolute_url(self): return f'/{self.id}' and forms.py : class CreateEmployee(forms.ModelForm): Fullname = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Fullaname" })) Position = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Position" })) Filial = forms.ModelChoiceField(empty_label=None, queryset=Filials.objects.all(), required=True, widget=Select(attrs={ 'class': "form-control", "placeholder": "Filial" })) Department = forms.ModelChoiceField(queryset=Department.objects.all(), required=True, widget=Select(attrs={ 'class': "form-control", "placeholder": "Department" })) SubDepartment = forms.ModelChoiceField(queryset=SubDepartment.objects.all(), required=True, widget=Select(attrs={ 'class': "form-control", "placeholder": "SubDepartment" })) Fired = forms.BooleanField(required=False) Login = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Login" })) Password = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Password" })) Phone = forms.CharField(max_length=60, required=True, widget=TextInput(attrs={ 'class': "form-control", "placeholder": "Phone" })) Wordkey = forms.CharField(max_length=60, required=False, widget=TextInput(attrs={ 'class': "form-control", "placeholder": … -
Django update_or_create throws an error, but works properly from shell
Say I have two models which are bound by OneToOne relation. class Person(models.Model): ... class Pear(models.Model): consumer = models.OneToOneField( Person, on_delete=models.CASCADE ) color = models.CharField() ... Person ModelSerializer nests Pear ModelSerializer. Person ModelSerializer also has update method which calls update_or_create for Pear. It looks like this. class PearSerializer(serializers.ModelSerializer): class Meta: model = Pear fields = '__all__' class PersonSerializer(serializers.ModelSerializer): pear = PearSerializer(required=False) class Meta: model = Person fields = '__all__' def update(self, instance, validated_data): pear_data = validated_data.pop('pear') ... if pear_data is not None: obj, created = Pear.objects.update_or_create( consumer=pear_data.get('consumer'), defaults={'color': pear_data.get('color')} ) ... So it throws an error saying that the consumer field value should be unique. At the same time update_or_create with the same parameters and absolutely same data works perfectly if called through shell. What am I missing? Thanks. -
Show posts liked by users
I am building a BlogApp and I am stuck on a Problem. I have a two models named Post and FavoriteUsers. Post for creating posts. FavoriteUsers for adding favorite users through ManyToManyField. What i am trying to do :- I am trying to see posts which are liked by favorite users of request.user. user_1 can add favorite multiple users. AND user_1 can see all the posts liked by favorite users. First i am accessing posts which are created by favorite users (which is successfully working) and then i am accessing posts which are liked by favorite users (which is not working). BUT when i try to show the posts which are liked by favorite users then nothing is showing. models.py class BlogPost(models.Model): blog_post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) blog_post_title = models.CharField(max_length=500,default='') likes = models.ManyToManyField(User, related_name='post_like', blank=True) class FavoriteUsers(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='parent_user') favorite_users = models.ManyToManyField(User, related_name='favorite_users', blank=True) views.py def show_favourite_users(request): objects = FavoriteUsers.objects.filter(favorite_users=request.user) context = {'objects':objects} return render(request, 'show_favourite_users.html', context) show_favourite_users.html {% for obj in objects %} {% for users in obj.favorite_users.all %} <!-- For access favorite users --> {% for posts in users.blogpost_set.all %} <!-- For access the blogpost title through blogpost_set --> {{ posts.blog_post_title }} {% for like in posts.favorite_users.likes.all … -
timyMCE allowed tags in django
In django I am using tinyMCE field for admin. I need to add a set of tags allowed by me, how can I do this? 'paste_as_text': True, not suitable, need to write a list and make it universally -
MySQL replication for Graphene Django
I'm using Graphene as a GraphQL server in Django. I set up a MySQL replica in Django. My setting is pretty simple. Read requests -> Replica. Write requests -> Source Mutations works in the next way: They modify data and then return modified/new data. Graphene modifies data in Source and immediately selecting them from Replica. The problem is that updated data is not immediately appearing in Replica DB (because of Replication delay). As result, some mutations simply do not work. I have a solution - specifying the Django database in every mutation. Didn't tried it yet. But the project is huge, and this requires a lot of changes in the codebase. I'm looking for simpler solutions. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'HOST': MYSQL_HOST, 'PORT': '3306', }, 'read_replica': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name_replica', 'USER': 'root', 'HOST': MYSQL_HOST_REPLICA, 'PORT': '3306', } } DATABASE_ROUTERS = ['app.db_router.DatabaseRouter'] class DatabaseRouter: def db_for_read(self, model, **hints): return 'read_replica' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True -
Django Allauth - Facebook Login does not produce email
I have issues with the django-allauth facebook login. I have configured the facebook login successfully and I am able to send a request to facebook and get the user's information back to my console to create the user to login. I have met an unusual issue in this process however. When I print the results I obtain from the facebook API to inspect the results, I manage to get a dictionary with "first_name", "last_name" and "name" populated with the facebook user's information but the field "email" and "username" carry a value of None. This is problematic because instead of being able to move forward with the account creation, the user is shown an allauth default html page with a form to enter the email/username. I would like to skip this page altogether and I could if I had the email in the first place. The dictionary that I get is the "data" coming out of allauth/socialaccount/adapter.py function populate_user(populate_user(self, request, sociallogin, data). Maybe I should have the email at the different step? My settings are set up as such: LOGIN_URL = 'login' LOGIN_REDIRECT_URL = '/' LOGOUT_URL = 'logout' LOGOUT_REDIRECT_URL = 'login' SOCIAL_AUTH_RAISE_EXCEPTIONS = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQURIED = True ACCOUNT_AUTHENTICATION_METHOD …