Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In order to discontinue 3rd party API access, allow to create or reset a password in python-social-auth for already registered users via 3rd part
There are certain 3rd party sites that have a daily cap for API user requests. Case in point, Linkedin which only allows 100k requests a day. Imagine your site grows so much that this wall is hit. I believe the next step would be to disable the linkedin connectivity and only allow via regular email and password. The problem is those users that signed in initially with linkedin - with what password can users try to log in using their regular emails? I've also attempted resetting a password as a user that logged in via linkedin through the reset password default django flow (tokenized link sent to their email) and the link does not even print in the console. However, when I do these steps as a user that signed in with a regular email and password, the workflow works well. What would be the steps to allow for a "resetting" for these users? PS. I wonder if it can be something via the below logic... https://python-social-auth.readthedocs.io/en/latest/backends/username.html Thanks in advance. -
Intermittent Bad Request (400) Spotify API callback using nginx + gunicorn + django
When I use nginx to serve my spotify django app with gunicorn socket handling communication, I would sometimes get Bad Request error during the user authentication callback. If gunicorn is configured as TCP with an ip and port, I don't experience the error, nor if I use django's manage.py runserver; user authenticates successfully. This intermittent issue seems to only occur when I'm using a socket connection. Checked nginx, gunicorn and django logs and didn't really get any info other than the 400 code. Using tekore python library to access spotify's api. Here's my nginx config: upstream app_server { server unix:/home/yg/Documents/projects/app/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 192.168.0.26; client_max_body_size 4G; access_log /home/yg/Documents/projects/app/logs/nginx-access.log; error_log /home/yg/Documents/projects/app/logs/nginx-error.log; location /static/ { alias /home/yg/Documents/projects/app/static/; } location /media/ { alias /home/yg/Documents/projects/app/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_buffering off; if (!-f $request_filename) { proxy_pass http://app_server; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/yg/Documents/projects/app/static/; } } -
I need to access a foreign Key element for populating a ModelForm
I'm building a forum with comment and Reply capabilities. While populating the form I'm facing a issue of Cannot assign "<Post: Post object (10)>": "Reply.comment" must be a "Comment" instance. I can understand the problem but don't know how to morph it into a Comment Instance. I'm using Django 3.1.4 The Models are as follows: class Post(models.Model): headline = models.CharField(max_length = 100) context = models.TextField() author = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) class Comment(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE) text = models.TextField(max_length = 200) author = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) class Reply(models.Model): comment = models.ForeignKey(Comment, related_name='replies', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) reply = models.TextField() views.py is as follows: class PostDetail(DetailView): model = Post def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['comment_form'] = CommentForm() context['reply_form'] = ReplyForm() return context def post(self, request, *args, **kwargs): comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = Comment( author = request.user, post = self.get_object(), text = comment_form.cleaned_data['comment'] ) comment.save() else: comment = Comment() reply_form = ReplyForm(request.POST) if reply_form.is_valid(): reply = Reply( user = request.user, comment = self.get_object(), # This line is the issue!!! … -
How to direct outside admin page after clicking save button?
is there a way after I click save button on admin page, I direct it outside admin page for example I cannot find the solution on internet http://127.0.0.1:8000/admin/app/add after I click save it open http://127.0.0.1:8000/app/ -
How to display ForeignKey Data in Django Template
I have relation of Project between Tags and a Project can have multiple tags, But I am unable to display the tags data in my template, I am trying to display data according to tag slug. But I ma getting error, Please let me know how I can display Tags data in my Template. Here is my urls.py file... path('tag/<tag_slug>', views.projecttag, name='projecttag'), here is my `models.py file... class Tags(models.Model): project = models.ForeignKey(Project, null=True, blank=True, related_name='ProjectTags', on_delete=models.CASCADE) tag_name = models.CharField(max_length=64, null=True, blank=True) tag_slug = models.SlugField(max_length=64, null=True, blank=True) here is my views.py file... def projecttag(request, tag_slug): tag = get_object_or_404(Tags, tag_slug=tag_slug) project = Project.objects.filter(ProjectTags=tag) context = {'tag':tag, 'project':project} template_name = 'pages/tags.html' return render(request, template_name, context) here is my tags.html file... {% for property in project %} <div class="single-property-box"> {{property.name}} </div> {% endfor % -
Can't send POST request from react method
I am creating a FB like app with Django and react. In the main page there's a feed where users can create posts and post them to the feed. I am trying to implement the delete post functionality but I am running into some difficulties. The logic is: The user clicks on the delete button on a post and the Browser sends and XMLHttpeRequest to the server to delete that post. Here's the react component: class Feed extends React.Component { constructor(props){ super(props); this.state = { profile_pic: profile_pic_url, user: username, posts: posts_from_server, } } handleClick() { const text = document.querySelector('#new_post_text').value; if (text.length > 1) { const data = {author: username, text: text} // send that post to the server to save it const csrftoken = Cookies.get('csrftoken'); const request = new XMLHttpRequest(); request.open('POST', '/create_new_post', true); request.setRequestHeader('X-CSRFToken', csrftoken); request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); request.onload = () => { const response = JSON.parse(request.responseText) this.setState({ posts : [{author: response.author, author_picture: profile_pic_url, text: response.text, date: response.date}, ...this.state.posts] }) document.querySelector("#new_post_text").value = ''; console.log(response) } request.send(JSON.stringify(data)) } } deletePost(post_id, author) { const post = document.getElementById(post_id) post.style.animationPlayState = 'running'; setTimeout(() =>{ this.setState({ posts: this.state.posts.filter(post => post.id != post_id) }) }, 1000) // delete the post from the server const data = {'post_author': … -
How to filter out objects in a related model without filtering out any of the objects from the primary model [Django]
Let's say I have models that look like this: # models.py class Agent(models.Model): name = models.CharField(max_length=30) class Deal(models.Model): agent = models.ForeignKey(Agent, on_delete=models.SET_NULL) close_date = models.DateField() And in my view, I'm wanting to list the deals per agent that have close dates <= 20 days into the future: # views.py class UnderContractListView(ListView): model = Agent context_object_name = 'agents' def get_queryset(self): future_date = (datetime.datetime.now() + relativedelta(days=20)).date() queryset = Agent.objects.filter(deal__closed_date__lte=future_date) return queryset Here's where I'm getting stuck The configuration above works great if I want to filter out the agents that have 0 deals; how can I filter out the deals without filtering out the agents? -
How can I show inlines dynamically in django admin
I want to show inlines dynamically depends on model value. When I override get_inlines like: # ModelAdmin def get_inlines(self, request, obj): if obj.is_show: return [SectionInline] else: return [] I got exceptions when I change the model object: ValidationError: 'ManagementForm data is missing or has been tampered with' Seems it not working. Can anyone help me to figure out the correct way? Thanks! -
Django - Logging - How to get the class name when running function GET inside it?
So I tried to create a logging for my code: views.py class name_of_API(generics.GenericAPIView): @my_logging @swagger_auto_schema def get(self, request): **running something return ... my_logging.py def my_logging(func): @wraps(func) def func_wrapper(request, *args, **kwargs): ex = None try: response = func(request, *args, **kwargs) log = logging.getLogger('main') name_of_class = func.__class__.__name__ log.info(str(name_of_class) + 'called success') except: format in settings.py 'format': '%(asctime)s.%(msecs)03d|%(levelname)s|%(process)d:%(thread)d|%(filename)s:%(lineno)d|%(module)s.%(funcName)s|%(message)s' info.log: 2020-12-21 10:30:04.845|INFO|12560:11868|logger.py:11|logger.func_wrapper| function Called success The problem here: This row below func.__class__.__name__ return function instead of name_of_API -
ModuleNotFoundError: No module named 'api.serlializer'
I've installed Django 3.1.4 and djangorestframework 3.12.2. I am attempting to run makemigrations for a music website I am building and I keep getting this error in the terminal and haven't been able to figure out what is causing it. (Django_React) PS C:\Users\BB_SO\desktop\dev\Django_React\music_site> python .\manage.py makemigrations Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\BB_SO\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, … -
Accessing django app in linux server from local machine
I am trying to access a django app in port 8000 of a linux VPS from my local machine. Port 8000 is already open public (active) target: default icmp-block-inversion: no interfaces: eth0 sources: services: cockpit dhcpv6-client ftp http https ssh ports: 5432/tcp 8080/tcp **8000/tcp** protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: I started django server using python3 manage.py runserver 74.208.210.200:8000 and tried to access it in my local machine using my server's public ip address 74.208.210.200:8000 however, the only thing I see is CONNECTION TIME_OUT the only way I can access this django app in port 8000 is from localhost If I run netstat -tulnp I see the following: `tcp 0 0 74.208.210.200:8000 0.0.0.0:* LISTEN 684680/python3 `` Please help! -
How to integrate Google's Pub/Sub with Django?
I am working on using Google's Pub/Sub with my Django website, There's document and sample program provided: https://cloud.google.com/pubsub/docs/pull#python I can now having a single .py file, but how to load the function in the process, keep it running, use it keep subscribing to my topic? Thanks -
How to add Chart.js to Wagtail Homepage panels using construct_homepage_panels hook?
I'm modifying the main dashboard of my Wagtail app to provide more useful/relevant data such as the number of open work orders, or number of customers. I am having some trouble getting my Chart.js to display in my dashboard. I've confirmed that the resource chart.js (version 2.8.0) is loading, and my canvas element is loaded onto the page as well. Still, the chart will not display. Here's some code. This is all in my 'dashboard' app. wagtail_hooks.py class WelcomePanel: order = 5000 def __init__(self, request): self.request = request self.logged_in_user = request.user.username def render(self): return render_to_string('wagtailadmin/dashboard.html', { 'logged_in_user': self.logged_in_user, }, request=self.request) # simply pass the 'request' to the panel @hooks.register('construct_homepage_panels') def add_another_welcome_panel(request, panels): panels.append(WelcomePanel(request)) templates/wagtailadmin/dashboard.html {% load static %} <h1> This text is visible </h1> <canvas id="pie_chart" height="604" width="1210" style="display: block; width: 605px; height: 302px;"></canvas> <script src="{% static 'js/chart.js' %}" type="text/javascript"><script> <script tyle="text/javascript"> var ctx = document.getElementById("pie_chart"); var stars = [135850, 52122, 148825, 16939, 9763]; var frameworks = ["React", "Angular", "Vue", "Hyperapp", "Omi"]; var myChart = new Chart(ctx, { type: "pie", data: { labels: frameworks, datasets: [ { label: "Github Stars", data: stars, backgroundColor: [ "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)", … -
Where can I publish node and python development projects?
I may soon want to find work as a full stack developer either with a company or as a free-lancer. What hosting service would be capable of running node and python (in addition to PHP and MySQL) so that I can use frameworks to create a front end. I don't want to spend hundreds of dollars a month, but I can't use some hosting sites that only allow static websites (e.g. BlueHost, which doesn't let you use node.js). I think AWS or A2 may be an option, but again, I don't want to have to pay too much. And I certainly don't want to use WordPress. I want to build things from scratch. -
Django returns UserLazyObject: TypeError: Field 'id' expected a number but got <channels.auth.UserLazyObject object
I'm using Django Channels to make a chat app following a tutorial. in my code I have a custom manager for my models. here is the manager: from import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) the problem is that when i introduce the model class in my consumer, I get this unfamiliar error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'UserLazyObject' what is a UserLazyObject ? and is there any way around it? here is my consumer.py: the model is introduce by this line of code below, commenting it or uncommenting it removes or reintroduces the error again and again. thread_obj = Thread.objects.get_or_create_personal_thread(me, other_user) from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from chat.models import Thread from django.contrib.auth.models import User class ChatConsumer(SyncConsumer): def websocket_connect(self, event): # get the two users me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) # get or create incase thread_obj = Thread.objects.get_or_create_personal_thread(me, other_user) self.room_name = 'presonal_thread_' async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) self.send({ 'type': 'websocket.accept' }) print(f'[{self.channel_name}] - connected now') … -
_set.all() not working in Django Template returning AttributeError
I am trying to add the no. of comments related to a post in my Django Project. but I keep receiving a 'Post' object has no attribute 'comment_set' AttributeError for some reason I don't understand why. My project has a Post Model class Post(models.Model): title = models.CharField(max_length=100, unique=True) ---------------------------------------- # To know how many comments def num_comments(self): return self.comment_set.all().count() <--------- Error from here class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="commented_users") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="commented_posts") content = models.TextField(max_length=160) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is sthe views.py class UserOnlyPostListView(ListView): model = Post template_name = "score/user_only_posts.html" context_object_name = 'posts' paginate_by = 4 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user).order_by('-date_posted') def get_context_data(self, *args, **kwargs): context = super(UserOnlyPostListView, self).get_context_data() user = get_object_or_404(User, username=self.kwargs.get('username')) return context Here is the template: {% for post in posts %} <td>{{ post.num_comments }}</td> {% endfor %} My question: Why am I receiving this error and how to fix it? Thank you -
How to display self-joined fields in Django?
I'm trying to build a comment section to a social-media-esque web app I'm building. I have a datatable storing comments using Django, and would like to build in a reply feature. Here is my model: class Comments(models.Model): id = models.AutoField(primary_key=True) text = models.TextField() author = models.CharField(max_length=50) creation_time = models.DateTimeField(auto_now_add=True) answer = models.ForeignKey(Answers, on_delete=models.CASCADE) replyto = models.ForeignKey('self', null=True, on_delete=models.CASCADE) def __str__(self): return self.author + ' commented: ' + self.text Essentially, whenever someone replies to a previous comment, I'd store that previous comment's ID in the "replyto" field, with which I'd like to link the current comment to that previous comment. In getting the current comment from the view I set up, I'd like to get all fields of the current comment (as outlined above) as well as the text and author of the previous comment (i.e. comment being replied to). In base SQL, I'd figured this would be a bit of self join logic. How do I do this in Django (and show the additional text and author fields of the being-replied-to comment as described above)? Thanks! -
Django inline model formset and inline model form handle initial differently
I'm using a StackedInline to populate a OneToOneField, but I want to make it optional, so I set min_num=0 and extra = 0. I also want to include default values when the user presses the "➕ Add another" button. class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): kwargs['initial'] = {'hello': 'world'} class MyInline(admin.StackedInline): form = MyForm extra = 0 min_num=0 This works. When someone presses the "➕ Add another" button, the hello field is populated with world. I also want to and do some custom validation, so it looks like I have to use BaseInlineFormSet. I moved the initial stuff to MyFormSet.__init__ class MyFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.forms: return self.forms[0].fields['hello'].initial = 'world' def clean(self): # My custom validation class MyInline(admin.StackedInline): formset = MyFormSet extra = 0 min_num=0 But the initial values are no longer populated when the user presses the "➕ Add another" button, only when the form is initially displayed with extra = 1. Is there another thing I need to do in MyFormSet to preserve the MyForm behavior? -
Django AWS S3 403 (Forbidden)
I'm hosting my Static and Media Files of my Django Project on AWS s3. The static files for admin and the image files are working fine, but some of the static files CSS & JS are giving a 403 error(URL for reference- https://maruthi-static.s3.amazonaws.com/static/css/customer_view/main/main.css). I'm using boto3-1.16.40 and django-storages-1.11, with AWS IAM user with AmazonS3FullAccess permission. The following is my code. Settings.py # STORAGES # ------------------------------------------------------------------------------ AWS_ACCESS_KEY_ID = "----" AWS_SECRET_ACCESS_KEY = "----" AWS_STORAGE_BUCKET_NAME = "maruthi-static" AWS_QUERYSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = None aws_s3_domain = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_DEFAULT_ACL = None # STATIC # --------------------------------------------------------------------------------------- AWS_STATIC_LOCATION = 'static' STATICFILES_STORAGE = "tps.storages.StaticRootS3Boto3Storage" COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy" STATIC_URL = f"https://{aws_s3_domain}/{AWS_S3_REGION_NAME}/static/" # MEDIA # ------------------------------------------------------------------------------ AWS_PUBLIC_MEDIA_LOCATION = 'media/public' DEFAULT_FILE_STORAGE = "tps.storages.MediaRootS3Boto3Storage" MEDIA_URL = f"https://{aws_s3_domain}/{AWS_S3_REGION_NAME}/media/" AWS_PRIVATE_MEDIA_LOCATION = 'media/private' PRIVATE_FILE_STORAGE = 'mysite.storages.PrivateMediaRootS3Boto3Storage' storages.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticRootS3Boto3Storage(S3Boto3Storage): location = settings.AWS_STATIC_LOCATION default_acl = "public-read" class MediaRootS3Boto3Storage(S3Boto3Storage): location = settings.AWS_PUBLIC_MEDIA_LOCATION file_overwrite = False class PrivateMediaRootS3Boto3Storage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False All my static and media files were uploaded to my s3 bucket when I ran collectstatic. I have set the … -
Joining tables in a nested serializer in django?
I am kind of at my wits end here. Been searching for hours but i can't wrap my head around it. I have the following models: class Word(models.Model): sentence = models.ForeignKey(Sentence) vocabulary = models.ForeignKey(Vocabulary) class Sentence(models.Model): text= models.ForeignKey(Text) class Text(models.Model): ... class Vocabulary(models.Model): ... class VocabularyStatus(models.Model): vocabulary = models.ForeignKey(Vocabulary) user = models.ForeignKey(User) status1 = models.IntegerField(default=1) status2 = models.IntegerField(default=1) My desired output is in the form of: text = { "sentences": { "words": { "id": 1 "vocabulary": 1 "status1": 1 "status2": 1 } } } So basically the hirarchy is Text > multiple sentences > multiple words. And the status is different based on the user who is doing the query. The reason why Vocabulary is different from Word is because multiple words can have the same vocab (e.g uppercase/lowercase words) Serializers: class TextSerializer(serializers.ModelSerializer): sentences = SentenceSerializer(many=True) class SentenceSerializer(serializers.ModelSerializer): words = WordSerializer(many=True) class WordSerializer(serializers.ModelSerializer): ... With the queryset: queryset = Text.objects.prefetch_related('sentences', 'sentences__words') It works fine for that. But i have no idea how to link the data from VocabularyStatus into that. It is already a nested serializer. I tried: queryset = Text.objects.prefetch_related('sentences', Prefetch('sentences__words', Word.objects.prefetch_related('vocabulary__vocabularystatus_set'))) But now i have no idea how to filter for the user with that or how to … -
Task schedules for django database in python
Im starting a web app with a mongo database. I want to update this database every 5 minutes so the users can have the newest data available. Before i started with django, i used crontab to execute my crawling scripts in an external server and update automatically my DB. However, ive read that it is better not to use cron with django because it should only be applied to system operations and it is not portable. What task scheduler is the best for django? Some posts suggest Celery and some others suggest RQ. Which is the way to go? Thank you in advance. -
raise ValidationError on inlineformset not showing errors
I am trying to raise ValidationError if a duplicate entry found in an inlineformset, just like in the docs: (Custom formset validation) I am debugging my code and followng it's progress and when it reaches the line: raise ValidationError("Check Duplicate Entry"), the code jumps to render the form again. The template renders with the form data left filled out but there are no validation errors appearing to say what is wrong. I'm missing something for sure. Any help appreciated. class MyInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(MyInlineFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False def clean(self): if any(self.errors): return mylist = [] for form in self.forms: myfield_data = form.cleaned_data.get("myfield") if myfield_data in mylist: raise ValidationError("Check Duplicate Entry") mylist.append(myfield_data) My tempate just has this: {% block content %} <section class="container-fluid"> {% crispy form %} </section> {% endblock content %} -
Back button to a related object
I'm building an app where I can add recipes and add ingredients to those recipes. On view recipe_details I have a button to add_new_ingredient. When I'm on new_ingredient_form I want to have back button to get back to the details of recipe. I'm trying to pass recipe's pk but it doesn't work. How am I able to pass recipe's pk to be able to back to previous view? models.py class Recipe(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=100, unique=True) preparation = models.TextField() def __str__(self): return self.title class Ingredient(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.CharField(max_length=100) amount = models.PositiveSmallIntegerField(blank=True, null=True) unit = models.ForeignKey('Unit', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.name views.py class RecipeView(generic.DetailView): model = Recipe context_object_name = 'recipe' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ingredients_list'] = Ingredient.objects.filter(recipe=self.object.pk) return context class AddIngredientView(generic.edit.CreateView): model = Ingredient fields = [ 'name', 'amount', 'unit' ] success_url = '/' template_name = 'recipes/add_ingredient.html' def dispatch(self, request, *args, **kwargs): self.recipe = get_object_or_404(Recipe, pk=self.kwargs['pk']) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): form.instance.recipe = self.recipe return super().form_valid(form) def get_success_url(self): if 'add_another' in self.request.POST: url = reverse_lazy('recipes:add_ingredient', kwargs={'pk': self.object.recipe_id}) else: url = reverse_lazy('recipes:recipe', kwargs={'pk': self.object.recipe_id}) return url add_ingredient.html {% extends "base.html" %} … -
Django: Unable to login with user
When I have registered a user, they get redirected to the login-page but I seems that my error message triggers which means that my login function is not working properly working. Any suggestions what I'm doing wrong, it worked well before. My function in views.py def LoginUser(request): if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password1=password) if user is not None: print(user) login(request, user) return redirect('/start.html') else: messages.info(request, 'Incorrect user details') context = {} return render(request, "/login.html", context) My forms.py from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth import login, authenticate from django.contrib.auth.models import User from django import forms from .models import Account, MyAccountManager class RegisterForm(UserCreationForm): #firstname = forms.EmailField() #lastname = forms.EmailField() email = forms.EmailField(required=True) class Meta: model = Account fields = ["email", "password1", "password2"] -
How to manually clear DB in a Django test?
I am using: python = "3.8.3", django="3.0.5" I have written a django test with APITestCase. I am running other tests inside my test class. I am trying to call other functions inside my test class. In order to do this I have a dictionary in a list which i mapped like this: [ { "class_name": class_name, "func_name": "test_add_product", # Comes test name "trigger_type": trigger_type, # Comes from model choices field. "request_type": RequestTypes.POST, "success": True, }, { ... }, ] I am looping these with a for loop and running each one. After each loop db should be cleared in order to not get error. I tried to do this using: # Lets say that, we have a Foo model Foo.objects.all().delete() This method works, but I want a better solution. How can I manually clear the test db before the test finishes?