Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django blog upload by user functionality
I am creating a website using django. In this website users will create an account, after that they will be able to make blogs and publish them just like medium. So for adding features like creating and publishing blogs in django is there any particular library I can use ( django-cms seemed different to me, please suggest something other) . Thank you very much in advance. It will be really helpful. -
Having trouble with writing data to the Django SQL Lite DB
Hey guys I'm trying to build a basic auction site to learn Python and I have an issue with writing data to the db using Django (SQL Lite). I used "python manage.py inspectdb" and found that the database is updated and built fine with all 5 fields I'm looking to use. I am building a Watchlist feature and when the user clicks "Add to Watchlist", it's supposed to add it to that users watchlist - however it's not adding any data - even when I hard code the data in like I have it now. I included the code for the new Post option, which I wrote and is working just fine even though it's very similar to the Watchlist feature. I just can't figure out why it's not working. Here is my code: views.py: def watchlist(request, username): if request.method == "POST": new = Watchlist.objects.create(username = username, title = "Monkey", description = "Eats bananas", price = 300, category = "Animals") new.save() return render(request, "auctions/watchlist.html") else: query = Watchlist.objects.all() return render(request, "auctions/watchlist.html", { "queries": query }) watchlist.html: % block body %} <h2>Watch List</h2> <ul> {% for query in queries %} <li><a href="/watchlist/{{query.user}}">{{ query.title }} - {{ query.description }} - ${{ query.price … -
How to add/update django relationships using React
I have the following models... class Category(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200) likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) published_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) def __str__(self): return self.text class Answer(models.Model): text = models.TextField() likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) published_at = models.DateTimeField(auto_now_add=True) question = models.ForeignKey(Question, on_delete=models.CASCADE) and the serializers are... class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class QuestionSerializer(serializers.ModelSerializer): correctness = serializers.SerializerMethodField() class Meta: model = Question fields = '__all__' def get_correctness(self, instance): total_likes = instance.likes + instance.dislikes try: correctness = (instance.likes / total_likes) * 100 return round(correctness, 2) except ZeroDivisionError: return None class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = '__all__' my views are... class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer @action(detail=True) def questions(self, request, pk=None): category = Category.objects.get(pk=pk) questions = category.question_set.all() serializer = QuestionSerializer(questions, many=True) return Response(serializer.data) class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.all() serializer_class = QuestionSerializer @action(detail=True) def answers(self, request, pk=None): question = Question.objects.get(pk=pk) answers = question.answer_set.all() serializer = AnswerSerializer(answers, many=True) return Response(serializer.data) class AnswerViewSet(viewsets.ModelViewSet): queryset = Answer.objects.all() serializer_class = AnswerSerializer and my urls.py file... router.register('api/categories', CategoryViewSet, 'categories') router.register('api/questions', QuestionViewSet, 'questions') router.register('api/answers', AnswerViewSet, 'answers') I am able to update the likes and dislikes for … -
Delete and recreate database in the middle of Django test
I'm making a test function in Django to test that a new implementation of a certain method results in the same database as the old implementation. (To compare the databases, I make a request to get all instances of some models, parse it into a dictionary, delete some of the id values, JSONify the dictionaries into strings, and then make Counters out of the dictionaries.) As part of this, in the middle of the test case, I'd like to be able to delete the database and then recreate it. How can this be done? I can delete all the tables and reset the sequence numbers, but sqlsequencereset returns no lines of SQL, and cursor.execute(f"delete from sqlite_sequence where name='{table_name}'" doesn't seem to do anything to the sequence numbers. I'd like to reset the sequence numbers to ensure that the foreign keys values from the two implementations can be compared for equality. Is there a way to completely delete and recreate the database? I'm using SQLite3. -
HTTP Error 401: Unauthorized error: while making graphql query in Django which works fine outside Django
I am using shopify_python_api and making a graphql query to my Shopify store. The problem is that the code I wrote runs perfectly fine as a standalone python file outside a Django project but when I merge it with the project and put the codes inside the app, it suddenly raises HTTP Error 401: Unauthorized error. Django console: https://dpaste.com/ARD2JW7XZ Django_error_image My codes are as below # credentials shopify_secret = { 'domain': 'nameoftheshop', 'API_KEY': os.environ['API_KEY'], 'PASSWORD': os.environ['API_KEY'] } # start the session & activates session = shopify.Session( f'{shopify_secret["domain"]}.myshopify.com', '2020-07', shopify_secret['PASSWORD']) shopify.ShopifyResource.activate_session(session) random_query = ''' { shop { id name description email } } ''' shopify.GraphQL().execute(random_query) I have tried so hard to find the answer for this error for weeks, but to no avail. The problem is I have literally zero idea why and how this error arises. Is it something to do with the session? If anyone can shed a light on this I would be very much grateful. Thank you. -
Send html email from django model?
i am trying to send email from django model but once i tried to submit it through me error context must be a dict rather than Context. how to resolve this class DriverEmail(CommBase): template = models.ForeignKey( DriverEmailTemplate, models.SET_NULL, null=True, blank=True, related_name="items", ) email = models.CharField(max_length=1024) driver = models.ForeignKey("drivers.Driver", models.CASCADE) sent_at = models.DateTimeField(_("sent at"), null=True, blank=True) def save(self, *args, **kwargs): if not self.sent_at: self.email = self.driver.email ctx = Context({ "driver": self.driver, "template": self.template, "body": self.body, }) template = get_template('email_template.html') content = template.render(ctx) if self.email: try: send_mail( subject=self.title, message="", html_message=content, from_email="DigitalFleet <contact@vivadrive.io>", recipient_list=[self.email], ) self.sent_at = now() except Exception as e: pass else: self.sent_at = now() self.key = secrets.token_hex(15) return super().save(*args, **kwargs) using those self.template contain text like this and when i tried to send email its just send me variable as a string its not show that variable name, so how can i use that will get driver variable instead of string self.template text image : Hey ,{{driver.first_name}} Here here is your register code {{driver.code}} Why is that happening ? From what I've found about this error it is somehow connected to sending string variable dictionary to template renderer, but mine's not empty driver... -
How to prevent redirection to UserChangeForm after user creation in django admin?
Hi i am new to django and i want to know is there a way to control redirection in django admin after a user is created in django admin Any sort of help or info would be appreciated Thanks -
Django Rest & React Frontend - Multiple React Apps or not?
so this is more of a best practice like question. Currently I am running a django rest api with react for the frontend. Lets think of a project model which will then include a mission and a result (it will be more in the end but for simplicity lets stay with it). So it can be like: /projects /project/1/ /project/1/mission /project/1/result I am now overthinking whether I should include multiple react apps or build one or two big react apps with react router for the subpage routing. To clarfiy: Is it best practice to: A) Build one react app for each page which will be quite a lot easier for me and I can make use of django context and the native django routing. But the react apps itself will only cover a very small function subset and I will have to create many django templates. or B) Build only a few react apps and use react router for the subpaging. So for example /projects/<int:pk> is the starting point for react and /mission and /result will then be handled by react router in the same react app. Which will bloat up the react app but reduce ongoing js load i … -
Django request.user returning None
I have a user, the one I'm logged in. This user is called "chau". He follows another user, one called "hola". Im sure about this. I checked it in Django Admin. So i'm trying to do this: def followings(request): if request.method == "GET": print(request.user.follows) But i'm getting network.User.None I don`t know why. I checked literally 20 times to see if request.user does not follow anybody, but he does! Down here is my model structure: class User(AbstractUser): follows = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by') I did make migrations, and it said that were already applied. -
Fix a page loader which is not running when clicking item from other pages?
I have a page loader that runs whenever i click the items(hyperlinked) from a bootstrap-table and it runs perfectly fine.But when i paginates the table and then click any item from the from the table then no loader appears. I am doing this project on django and using bootstrap-table (extension of bootstrap) Here is the code that is used for page loader HTML: <div id="pageloader"> <p class="display-4"><strong>This may take some time so sit back and relax.</strong></P> <img src="{%static 'appname\img\preloader.gif'%}"> </div> CSS: #pageloader { background: rgb( 245, 245, 220); display: none; height: 100%; position: fixed; width: 100%; z-index: 9999; } #pageloader img { left: 50%; margin-left: -32px; margin-top: -25px; position: fixed; top: 50%; } #pageloader p { margin-top: 18%; text-align: center; } JS: <script> $(function(){ $('a.explorelink').click(function(){ $("#pageloader").fadeIn(); }); }); </script> How make the page loader works even when i click any item from another page ? Thanks in Advance. -
pass part of url as a value to view in django
I am creating a django project, in which i have list of items displayed on my webpage. Each item has a predefined URL, for eg. url of item 'a' is "https://example.com/b?node=item-a". So following is the URL pattern matcher I have written in urls.py : url(r'example.com/<str:suburl>',views.display_details) Now redirecting from example.com to example.com/b?node=item-a happens using the HTML <a> tag for this item. So when I am redirected to the items page I want to grab the "b?node=item-a" (suburl) part of the url and use it in the views.display_details function written in views.py file. Can anyone please me how can i implement this. Thanks in advance. -
Django - Model1.object1 same as Model2.object1
I have three models: Customer, Game and Tipp. I want a relation between every game and Tipp. So every user can guess a result for a game: class Tipp(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) result_hometeam1 = models.IntegerField(null=True, blank=True) class Game(models.Model): hometeam1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name="hometeam1", blank=True, null=True) result_hometeam1 = models.IntegerField(null=True, blank=True) class Customer(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) In the model Tipp I want a object called hometeam1 which should have the same value as I have selected in the model Game. I tried to do like hometeam1 = models.CharField(max_length=120, default=Game.objects.filter(gameday=week)) or hometeam1 = models.ForeignKey(Game.hometeam1, on_delete=models.CASCADE) but I havn't found a solution for this. Please, I am django newbie :D -
Creating questions Form with If / else conditions - What is the best approach?
I need to build a Form that ask the user questions. The issue is that the questions I need to ask (all of which are multi choices, Radio type) leads to other questions. The point is, the user answer set the next question and so on. In the back-end, I have a DB of questions, by the answer of the user, the next question appear to him, based on conditions of if / elif / else without submit button. After these sets of questions, it will reach a result that will be saved into a var that will be used in my program. What is the best approach for this type of form? Will I need to use ModelForm? Where will I write my conditions? views / template? Thanks! -
ModuleNotFoundError: No module named 'djcelerykombu' while usinf django-celery
I am trying to use django-celery with kombu with python 3.7 and Django2.2 and following this tutorial: https://hashedin.com/blog/a-guide-to-sending-scheduled-reports-via-email-using-django-and-celery/ I have set up everything as mentioned in the tutorial but, When I ran the command: python manage.py celery worker --beat --loglevel=info --without-gossip --without-mingle --without-heartbeat I gave me the following error: ModuleNotFoundError: No module named 'djcelerykombu' And here is the full traceback: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\abc\Desktop\abc\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\abc\Desktop\abc\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\abc\Desktop\abc\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\abc\Desktop\abc\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\abc\Desktop\abc\env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "c:\users\abc\appdata\local\programs\python\python37\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, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'djcelerykombu' I have all the packages and their dependencies installed in my env like: amqp-1.4.9 anyjson-0.3.3 billiard-3.3.0.23 celery-3.1.26.post2 django-celery-3.3.1 kombu-3.0.37 and still, it is throwing me this error not sure why? … -
How to limit Django REST api to only ONE user?
I'm coding a REST API with Django and I need to make some urls limited to the only use of it's creator. I'm actualy using an authentication token but in fact anyone with a token can use my api so I need to limit some functionalities to specific users. An example would be like that: Jonh Doe Token: roh2938rhe63eh0832yey3289 public --> domain.com/api/bobby/public/ public --> domain.com/api/jonhdoe/public/ private --> domain.com/api/jonhdoe/private/ And somehow only Jonh Doe could access to that private url even though the returned data is the same as usual, but just private. Thanks in advantage. -
How to filter page lists in the wagtail admin so editors only see pages from group there a part of?
I have a menu item which lists all the pages at once from all the parent pages in the Wagtail admin. I would like there to display only the posts that are published by the users from the group that the currently logged in user is a part of. I managed to use this code to limit the users to only view their own posts and think that this can be expanded to what i'm looking for. #admin.py class PageAdmin(ModelAdmin): model = BlogPage menu_icon = "doc-full" menu_label = "All Posts" list_display = ("title", "date", 'owner') def get_queryset(self, request): qs = super().get_queryset(request) #only show articles from the current user return qs.filter(owner=request.user) modeladmin_register(PageAdmin) Thanks -
how to use django_ssl_auth to authenticate by ssl certificate
I'm new to python, and my first project requires to use ssl certificate to authenticate user by ssl certificate? which will be provided to user by us. I found django_ssl_auth, but i cant understand how to user it, as users dont need to be registered in the system, and they need this certificate in order to ask a question (for example) by rest request. it is not a standard project.Provided certificates can expire, so user need to ask for another certificate in order to ask a system questions. I cant understand how to use django_ssl_auth in django rest framework & how to test if ir works. Will be glad to get some ideas or sample rest projects which use django_ssl_auth. @freenode -
Conditionally change background image based on user selection, using Django?
Hi this seems to be a simple issue but I'm new to programming, Python & Django. I'm creating a multiple choice quiz using Python which has 10 questions, and can be viewed as a web-application by the user - similar to the Django polls app. Based on the answer the user selects for each question, I want the background image to change conditionally. 2 different background images - when the answer is wrong vs right, in the results webpage. At the moment, I am able to load the static image but not conditionally based on the user's choice selection. Looks like it should be an if/else html tag? What is the best way to go about this? Thanks in advance! templates > quizzes > results.html: {% if selected_choice == 'Apple' %} <h1 style= 'color:white;' class="correct">Correct! Good job.</h1> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'quizzes/style2.css' %}"> {% else %} <h1 style= 'color:white;' class="wrong">Wrong!! The correct answer is Apple.</h1> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'quizzes/style3.css' %}"> {% endif %} -
How to bulk_create using a django-mptt model?
I need to use bulk_create on a django-mptt model, but I am getting an error: django.db.utils.IntegrityError: null value in column "lft" violates not-null constraint DETAIL: Failing row contains (2, Magic, null, null, null, null, null, null, 1). How can I bulk create a django-mptt model without hard coding lft, rght, and tree_id? MRE models.py: from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', ) name = models.CharField(max_length=255) tcgplayer_category = models.ForeignKey('tcgplayer.TcgCategory', on_delete=models.PROTECT, blank=True, null=True) class Meta: unique_together = ( ('parent', 'name'), ) def __str__(self): return self.name class TcgCategory(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) name = models.CharField(max_length=255) class CategoryGroup(models.Model): id = models.IntegerField(primary_key=True) category = models.ForeignKey('tcgplayer.TcgCategory', on_delete=models.CASCADE) fixtures/category.json: [{ "model": "tcgplayer.tcgcategory", "pk": 1, "fields": { "name": "Magic", } }, { "model": "tcgplayer.categorygroup", "pk": 1, "fields": { "category": 1, "name": "10th Edition", } }, { "model": "tcgplayer.categorygroup", "pk": 2, "fields": { "category": 1, "name": "7th Edition", } }] tasks.py: def convert_categories(category_ids): root_categories = TcgCategory.objects.filter(id__in=category_ids) category_parents = Category.objects.bulk_create([ # error is thrown here Category( tcgplayer_category_id=model['id'], name=model['name'], ) for model in root_categories.values('id', 'name') ]) for parent in category_parents: category_groups = CategoryGroup.objects.filter(category_id=parent.tcgplayer_category_id) category_models.extend([ Category( tcgplayer_category_id=model['id'], name=model['name'], parent=parent, ) for model in category_parents.values('id', 'name') ]) Category.objects.bulk_create(category_models) -
How to use a variable from jinja2 in a for block
I am trying use a Jinja2 with variable inside of a for block as a dictionary parameter. {% for x in dict_one %} {% with id=x.id %} <tr> <th scope="row">{{x.id}}</th> <td> {% for a, b in dict_two.id.items %} Key: {{a}} Value {{b}} {% endfor %} </td> </tr> {% endwith %} {% endfor %} In this scenario my page doesn't display any data. In the case when I will hardcode this line changing id in 11 (a value that display in my table from x.id) it works. {% for a, b in dict_two.11.items %} The solution should make possible to use the with-variable inside of accessing a dictionary's item. -
How to filter a django queryset using two joined tables
I have an searchable dropdown which fetch data directly from the tables(models). This is my query in mysql and need equeivalent django query for this: SELECT CI.name, RG.name, CA.name FROM cities_city AS CI JOIN cities_country AS CA ON CI.country_id=CA.id JOIN cities_region AS RG ON CI.region_id=RG.id; The tables are something like this: region table: id --------- name -------- country table: id --------- name -------- city table: id --------- name -------- region_id ---- country_id and this is my queryset in django: qs = City.objects.all() if self.q: qs = qs.filter(name__icontains=self.q).select_related('region', 'country').values('name', 'region.name', 'country.name') where self.q is the inserted value by user. -
I am using lightsail and route53 to deploy my site, But bad request 400 is appear
I am using nginx and gunicorn server And i followed steps of the aws docs and other's blog, But Always face this error message My nginx setting is when trying sudo systemctl status nginx And my instance's settings here I made A record and here's nameserver is updated here And i add records in hosting area I had a very hard time to handle this... What am i do? -
DJANGO: Is it possible to inherit a template consisting dynamically generated content in django?
I am trying to create a webpage which has two parts. An index list of all items (that persists throughout) Detail of the selected index item I created a LIST VIEW and a DETAIL VIEW for the same but the problem is both views cannot be called on the same template. I tried to list all the items in 'reports_list.html' and then inherit this template to 'report_detail.html' to see if the index list stays but it doesn't. Is there a way to accomplish this? -
How to change the button based on the user input?
I am implementing a pypi package called django-shopping-card https://pypi.org/project/django-shopping-cart/, so the users can see their saved posts. My issue is that I could not make the button to display "Remove Post" instead of "Add to Card", if the post was added already. I have tried to create a different method to pass the posts which have been saved, but that caused a an error, as I cannot access the key and values of the cart without for loop. I am new to this and I would highly appreciate any comments and suggestions. def add_fav(request, id): cart = Cart(request) post = Auction.objects.get(id=id) cart.add(product=post) return redirect("watchlist") def item_clear(request, id): cart = Cart(request) product = Auction.objects.get(id=id) cart.remove(product) return redirect("watchlist") def items_clear(request): cart = Cart(request) cart.clear() return redirect("watchlist") def get_cart(request): return render(request, 'auctions/watchlist.html', {'cart': Cart(request)}) listings.html {% block body %} {% for auction in object_list %} <div class="col-md-4"> <div class="card mb-2"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'listing' auction.pk %}">{{ auction.name }}</a></h5> Price: {{ auction.price }}<br> <p class="card-text">{{ auction.description|slice:":10" }} ...</p> {{ auction.author }} Category: {{ auction.category }} <hr><img class="card-img-top" src="{{ auction.image.url }}" alt="no" ><br> {% for key,value in request.session.cart.items|slice:1 %} <br> {% if value.product_id == auction.id %} - <a href="{% url 'remove_fav' value.product_id%}">Delete</a> … -
Server error 500 on Django when deployed on Heroku when debug is set to False
Website is fine when debug is true, but when set to false it gives me a server error 500 evertime on every page. When i go into heroku logs --tail it tells me there is a status 500 issue. I have set up my allowed host so that is not an issue. Does anyone have any suggestions on what the root of the issue could be? Would appreciate any advice, thanks.