Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Digitalocean Django Ubuntu
could someone please let me know, which command should I use for Configure the Python 3 Virtualenv ? I'm using https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html this guide, but after the command "virtualenv ." I have python 2.7 in my bin folder instead of 3+ -
Static files not found when Docker container is running in Django React app
I am trying to run my Docker image to see it on my browser yet all that appears is an empty screen, upon inspection I see the following errors: [2020-09-12 17:31:42 +0000] [12] [INFO] Starting gunicorn 20.0.4 [2020-09-12 17:31:42 +0000] [12] [INFO] Listening at: http://0.0.0.0:8000 (12) [2020-09-12 17:31:42 +0000] [12] [INFO] Using worker: sync [2020-09-12 17:31:42 +0000] [14] [INFO] Booting worker with pid: 14 Not Found: /static/js/2.8ba00362.chunk.js Not Found: /static/js/main.8eee128b.chunk.js Not Found: /static/css/2.7253a256.chunk.css Not Found: /static/css/main.a85cbe2c.chunk.css Not Found: /static/js/2.8ba00362.chunk.js Not Found: /static/js/main.8eee128b.chunk.js The commands I have run are: docker build . -t projecthub and docker run -d -p 8000:8000 --name theprojecthub projecthub:latest I am very unsure why these static files are even being looked for, I cannot seem to find any reference to them in my code. Does anybody know what I should do? Here is my Dockerfile: FROM stefanomil/django-npm:latest RUN mkdir usr/src/app WORKDIR /usr/src/app COPY frontend ./frontend COPY backend ./backend WORKDIR /usr/src/app/frontend RUN npm install RUN npm run build WORKDIR /usr/src/app/backend ENV DJANGO_PRODUCTION=True RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python3 manage.py collectstatic && \ python3 manage.py makemigrations && \ python3 manage.py migrate && \ gunicorn project_hub.wsgi --bind 0.0.0.0:$PORT Here are the relevant parts of my settings.py file: … -
How to display data inside query search django
i read the django docs and found a way to search database. According to docs >>> Author.objects.filter(name__contains='Terry') [<Author: Terry Gilliam>, <Author: Terry Jones>] What is want is to display all variables associated with an author. For example, Terry Gilliam name, email id, phone number, which are in my database. Instead of just displaying the following line [<Author: Terry Gilliam>, <Author: Terry Jones>] -
Django - failed registration, displaying reason back to user
I'm using the built in django user model, but having trouble feeding back to the user why their registration details are failing. In this example, i'm trying to display the reason back to the user, for why there registration has failed. For example, not meeting the models password requirements, existing user etc. I have... # forms.py - so they supply their email address for verification class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ("email",) # views.py def register(request): if request.method == "GET": return render( request, "users/register.html", {"form": CustomUserCreationForm} ) elif request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_valid = False user.save() else: messages.info(request, 'invalid registration details') return render(request, "users/register.html", {"form": CustomUserCreationForm}) How do I find out why forms.if_valid() fails, and pass it back to the user? At the moment, it just gives a generic message back, with no user feedback as to why it didn't work. Thanks -
Foreign Key to two different Django Models
For my CRM I am trying to create an History model, that should store every change or action made on a specific Ticket (aka Customer Request). In this scenario two type of users are involved: Resources and Customers. Since both can make an action that should be stored in the History table (ex. Customers can open the ticket and Resources can close it) I was wondering what is the right way to achieve this as a Foreign Key (actor) class TicketHistory(models.Model): ticket = models.ForeignKey("Tickets", on_delete=models.PROTECT, related_name="ticket") action = models.ForeignKey("HistoryActions", on_delete=models.PROTECT, related_name="action") resourceActor = models.ForeignKey("Resources", ...) customerActor = models.ForeignKey("CustomerUsers" ...) date = models.DateTimeField(auto_now_add=True) As you can see I've initially decided to create two different fields, but I don't think it is the best solution. How would you do this? -
Storing TimeSeries data with a django application in addition to using PostresQL based on performance
I need some advice. After extensive research I still don't have a clear straightforward answer. I am runnning a django app with a PostgresQL DB (AWS RDS) and I am storing TimeSeries data there and I am using REST framework as API tech. Right now I am storing the time-series data with json-fields in the PostgresQl DB. My model could be simplified like this: class TimeSeries(..): data_json = JSONField( help_text="Data for time series in JSON format. Valid JSON expected." ) Let's say in a loop I send about 30 time-series objects with about 8760 (hours p year) values in the json field ({"1":"23.12", ... {"8760":"234.11"}) the script to create the objects needs about 3min. When I send 30 time-series objects with about 525 600 values (minutes p year) the script to create the objects takes about 1hour!! To query all this data back it also takes me roughly 3-4 minutes. This is by far too long. And it won't stay with 30 objects but will increase significantly. I will create/update the hourly/minute data every day or week. I want to reduce at least the query-time to seconds or even better be instantaneously. But also the creation time. But I don't … -
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)