Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating project manager system using django
I am creating a project manager system with using Django backend. But I am not sure what is the best approach to build a model for this. For example planning to establish a system structure like: class Organization(models.Model): user = models.ManyToManyField(User) organization_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) organization_name = models.CharField(max_length=255) def __str__(self): return self.organization_name Organization Model creates a record when a new user created in Database and bind the user id to itself. class Role(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.name This model take the [read, edit] roles. class Project(models.Model): user = models.ForeignKey(User,on_delete=models.DO_NOTHING) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) project_name = models.CharField(max_length=255) def __str__(self): return self.project_name When a project created. It takes the users' organization. So the project can only seen by the users which participated with same organization. class ProjectParticipant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.user ProjectParticipant controls the which user read or edit the project. I am not sure this is the good approach to build a project manager system. If there are flaws, how can I fix those... -
SVG not rendering
My django project is storing images on AWS. https://race-hub.herokuapp.com/ All png and jpg files are rendering as expected but svg files are not. I've checked various threads on this including content-type to be used for uploading svg images to AWS S3 I've checked the file type is set to "image/svg+xml" on AWS and that the files exist and render fine in AWS. -
Generate PDF file in Django using xhtml2pdf
I tried to generate a PDF file based on the information that comes from client side. I fetched the data using request.POST. @csrf_exempt def create_pdf(request): if request.POST: context = {} data = json.loads(request.POST.get("users")) // I didn't use it. context["title"] = "AMIR" render_to_pdf( template_path="useres/users_template.html", context=context) return HttpResponse(response) and to render pdf file I've wrote the code down below: def render_to_pdf(template_path, context={}): # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response when I call render_to_pdf in create_pdf view It doesn't return pdf file! How do I should return it? -
django_filters, how do I query based on associated model?
My problem is like so, I am using django-tables2 and I want to list some people on my page but these people should go through some queries. These queries will change according to information from other models.if the query is ok, this person will be in my table. # My models class AgeGroup(models.Model): age_group = models.CharField(choices=age_choices, max_length=5) class SolvedExam(models.Model): age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='solved_exam_age_group') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='solved_exam') class Person(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person') age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='person_age_group') * * * class Exam(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person') age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='exam_age_group') * * * # my view class PersonList(SingleTableMixin, FilterView): table_class = PersonTable model = Person queryset = Person.objects.all() paginate_by = 10 template_name = 'person/person-list.html' filterset_class = PersonFilter def get_queryset(self): super(Ogrenciler, self).get_queryset() return Person.objects.filter( **some query** ) raise Http404 I want to list the students if there are exams which is not finished in the person's age group. Thank you very much! -
Pycharm Django Macos Catalina Zsh abort and file tracking disabled
I been moving some PyCharm projects to my new iMac, but with 1 of my project im having issues when I try to run my custom Django commands, witch do work properly in other projects. To give you an overview, this is happening: When I try to run the project in PyCharm (run server): Process finished with exit code 134 (interrupted by signal 6: SIGABRT) When I manual try to run a Django command, it does seem to see the command file but it returns: Process finished with exit code 134 (interrupted by signal 6: SIGABRT) When I copy the command and try to execute it myself: /Users/gerd2020/Documents/Projecten/werkblad/venv/bin/python /Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py testdit /Users/gerd2020/Documents/Projecten/werkblad File tracking disabled zsh: abort /Users/gerd2020/Documents/Projecten/werkblad/venv/bin/python testdit im confused , when I do a collect static that does seem to work. Any ideas where I got to look? -
Django: Why am I getting ValueError when referring to a ForeignKey using a varchar?
My application (called users) includes these two models: class RankingType(models.Model): type_code = models.CharField(max_length=16, unique=True) description = models.CharField(max_length=64) def __str__(self): return f'{self.description}' class RankingProfile(models.Model): user = models.ForeignKey( User, to_field='username', on_delete=models.PROTECT, related_name='ranking_profile_as_user', blank=False ) type_code = models.ForeignKey( RankingType, to_field='type_code', on_delete=models.PROTECT, related_name='ranking_profile_as_type', blank=False, default='btb_buyer' ) profile_name = models.CharField(max_length=64) price_weight = models.IntegerField(default=100) transhipment_weight = models.IntegerField(default=0) earliest_etd_weight = models.IntegerField(default=0) latest_eta_weight = models.IntegerField(default=0) def __str__(self): return f'{self.profile_name}' makemigrations and migrate work fine. I then run some code that loads the users_rankingtype table from a CSV and then users_rankingprofile from another CSV. The users_rankingtype table loads without problem, but when I try to run the code that loads the users_rankingprofile it fails on the first insertion with a ValueError: Cannot assign "'btb_buyer'": "RankingProfile.type_code" must be a "RankingType" instance. Here's the code that loads the table: file_in = path + 'users_rankingprofile.csv' count_rankingprofile = 0 with open(file_in) as csvfile: reader = csv.DictReader(csvfile) for row in reader: r = RankingProfile( profile_name=row['profile_name'], price_weight=row['price_weight'], transhipment_weight=row['transhipment_weight'], earliest_etd_weight=row['earliest_etd_weight'], type_code=row['type_code'], username=row['username'], latest_eta_weight=row['latest_eta_weight'], ) r.save() count_rankingprofile = count_rankingprofile + 1 I use PyCharm, and so I can inspect the RankingType table. The first row of the users_rankingtype table has btb_buyer in the type_code column is in the table. What am I doing wrong? Thanks and regards...Paul -
What is the best way to deploy a django app in 2020?
I have been looking for the best way to deploy my Django app I have been found some solutions and suggestions, but I'm still not sure which one is the best way. Many youtube videos suggest that the serverless solution such as 'Amazon Elastic or Google App Engine' is the best way. I would be very grateful if an experienced Django developer would share with me what is the best way to Deploy a Django application today. -
How to send value to filter in if condition django?
In my html, I want to send this values to my filter but I got this error : ValueError at / invalid literal for int() with base 10: '{{request.user.id}}' My HTML: <span><i{% if post|liked:"{{request.user.id}},{{post.id}}" %} class="fa fa-heart pointer" {% else %} class="fa fa-heart-o pointer" {% endif %} aria-hidden="true"></i> <span class="text-dark">{{ post.likes.count }}</span> My Filter: @register.filter() @stringfilter def liked(value, args): values = args.split(',') user_id, post_id = values user = User.objects.get(id=user_id) post = Post.objects.get(id=post_id) is_liked = post.likes.get(id=user_id) if is_liked != None: return True else: return False Thanks for any answer. -
ai want to separate products based on id stored in postgresql database in django tell me template syntax
i tried this {% for i in object %} {% if i.get(id=1) %} Rs {{i.price}} {% endif %} {% endfor %} but shows error like TemplateSyntaxError Could not parse the remainder: '(id=1)' from 'i.get(id=1)' -
How to test custom authentication backend in django
I wrote a custom authentication backend, I used it in my views to prove that it is working, however I would like to test it so in case it breaks in future for whatever reason, I would know. I think the problem may be because I have no request in the test, so no request is passed into the authenticate method. If this is the problem, then how can I pass a valid request into the authenticate method and test it so the test passes. In other words, can someone please show me a test that passes for the authentication backend below backends.py class EmailBackend(BaseBackend): def authenticate(self, request, email=None, password=None): try: user = User.objects.filter(email=email).first() if user.check_password(password): return user else: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None test_backends.py class TestUserBackend(TestCase): def test_authenticate(self): user = UserFactory() authenticated_user = authenticate(email=user.email, password=user.password) self.assertEqual(authenticated_user, user) UserFactory() is from factory boy. I have also checked that user.password is hashed and the same as user.password which is also hashed. But I keep getting None != the user.email that was generated . Thanks for your help. -
Trying to inject one html page into another after an AJAX call but returning blank
I'm trying to inject an html template with a django function on it, into another html template. The function rests on an AJAX call for its variables. My AJAX call seems to be firing correctly (after checking in the Chrome dev tools) but the result is not showing on the html page as it should be. Here is the AJAX call //dashboard $(document).ready(function(){ console.log('Document Ready') $.ajax({ type: "GET", url : '/electra/playlist', dataType: "json", data: { 'venue': 'venue', 'list': 'list', }, success: function(data){ $("#playlist").html(data); console.log(data) }, failure: function(errMsg) { alert(errMsg); } }); }); Here is the html file where the Django function occurs playlist.html <!--what is the purpose of this fragmented code?--> <div class="user_playlists"> <ul> {% for item in playlist %} <li> <div> <h6 class="playlist-name">{{ item.list }}</h6> <h6 class="venue-name">{{ item.venue }}</h6> </div> </li> {% endfor %} </ul> </div> And here is the portion of the dashboard.html template where the playlist.html function should be injected: <body> {% block content %} <div class="container-fluid" style="padding:15px"> <!--location --> <div class="row"> <div class="col-sm-3"> <h3 class="list-heading"> Your Playlists </h3> <div id="playlist"> </div> </div> </div> </div> {% endblock %} Please note I have tried with {% include "playlist.html" %} and would like to avoid this if I can, … -
Why am I getting an smtp authentication with Django on PythonAnywhere
If you go on my webapp. You'll see a reset password option at the bottom of the login form but you need to register an account first and then try resetting your password. If you then type in your email and send, you will get a 500 Error page which I added custom styling to. So there was an error in my app in production, which does not show up in development. Everything worked perfect when I ran the localhost and tried it. I hosted my Django app on pythonanywhere so I went on my profile on PythonAnywhere and went to my log files and found this: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials m67sm7365001qkf.98 - gsmtp') 2020-10-10 08:08:56,103: OK: /password-reset/ Traceback (most recent call last): File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/contrib/auth/views.py", line 222, in dispatch return super().dispatch(*args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) … -
Changing ordering of model in the admin views
I have a User model in Django, in which I defined class Meta with ordering. It's defined like this: class Meta: verbose_name = _('user') verbose_name_plural = _('users') ordering = ('-speedy_net_site_profile__last_visit',) swappable = 'AUTH_USER_MODEL' But, I have two apps - Speedy Net and Speedy Match, and in Speedy Match I want a different order ( ordering = ('-speedy_match_site_profile__last_visit',) ). How can I do this? -
What is the appropriate way to use a ModelForm field as an argument to upload_to?
I have a ModelForm, where two of the fields are lastname and firstname. As several files are being uploaded by many different people, I would like to group the files into a directory based on their names. I've been trying to use a custom formatted string to do this, but so far I'm getting an error that there are not enough arguments for format string, and I am wondering if it as something to do with the form not being saved yet. My attempt to generate a filename based on form fields is: def filename_path(instance, filename): return os.path.join('applicant_documents/%s_%s/%s' % instance.last_name, instance.first_name, filename) and the field from my model is defined as: documents = models.FileField(upload_to=filename_path) Am I doing something wrong, or is this not possible? -
For what is better Django and for what Wordpress?
I asked this question because I would like to have an answer from a person with experience in that field. If something in my question is "wrong-formulated" tell me. (I know that Django and Wordpress are different thing, for this reason I'd want to know more) -
How to let PIL's Image.open find files from static?
I want to access a file in static from a module called "generate.py" inside my app. However I don't really have any idea how to do it. I believe I've properly "installed" the app because i can access the .html file in the App Things I've tried in generate.py 1 - from django.conf.urls.static import static Image.Open(static('resources/App/template/photothatiwanttoopen.jpg')) Error I get from code above: 'list' object has no attribute 'read' 2 - from django.conf import settings Image.Open(settings.STATIC_URL+'resources/App/template/photothatiwanttoopen.jpg') Error I get from code above: [Errno 2] No such file or directory: '/static/resources/App/template/photothatiwanttoopen.jpg' Here's my folder structure view - Project - App - templates - App - app.html - apps.py - generate.py <<< Script - models.py - urls.py - views.py - Project - settings.py and stuffs - static - resources - App - template - photothatiwanttoopen.jpg - manage.py and stuffs Here's last few lines of my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Let me know if you need any more information. -
Google App Engine Resource Error on the Django Deployment Tutorial
I have been looking for a great way to deploy my Django application and a Found Google App Engine Flex a pretty good solution. I have not much experience in application deployment so I follow along with the (Official Google Tutorial about the deployment. On the last step, the tutorial instructs me to deploy the application within the cmd prompt: gcloud app deploy. I follow along. Everything seems fine until I get this message: Updating service [default] (this may take several minutes)... After a while I get this message: Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [13] Flex operation projects/keen-opus-292007/regions/us-east1/operations/98cb5ea1-6231-40dc-a6e7-d44ddac73f77 error [INTERNAL]: An internal error occurred while processing task /app-engine-flex/insert_flex_deployment/flex_create_resources>2020-10-10T07:36:04.734Z7747.ue.0: Deployment Manager operation keen-opus-292007/operation-1602315365254-5b14c1e2a05d7-340fb934-bf85bfd7 errors: [code: "RESOURCE_ERROR" location: "/deployments/aef-default-20201010t093403/resources/aef-default-20201010t093403" message: "{\"ResourceType\":\"compute.beta.regionAutoscaler\",\"ResourceErrorCode\":\"403\",\"ResourceErrorMessage\":{\"code\":403,\"message\":\"The caller does not have permission\",\"status\":\"PERMISSION_DENIED\",\"statusMessage\":\"Forbidden\",\"requestPath\":\"https://compute.googleapis.com/compute/beta/projects/keen-opus-292007/regions/us-east1/autoscalers\",\"httpMethod\":\"POST\"}}" ] Every time I rerun the command gcloud app deploy I get the exact same error. Any idea how to fix that? Google Search doesn't reveal anything for me. -
Django Shopify Integration
I'm planning to create a dashboard in Django. I want to extract data from Shopify Database and integrate it to my Django app. For example, I want to get the customer's info in Shopify and Show it automatically to my Django app. How am I going to do this ? -
How to set user.id as username and password in django?
I want to set user id as username as well as password at a time of user registration in django. How can I do it ? -
How can do for-loop like this
How can I do for-loop like this in Django? list = ['AAA', 'BBB', 'CCC'] ========================================== {% for x in len(list), for y in list %} <p>{{x}}: {{y}}</p> {% endfor %} -
Shortcut to set all the fields in serializers to 'required=False'?
sorry if its duplicate, but I am not able to find the solution. Is there any way to set all the fields in serializers as required=False in one line, rather than declaring each field and explicitly write required=False for each field ? -
Unable to run django project due to error in manage.py file
I am working on django project. My python version is 2.7.15 and django version is 1.11.29. When I am trying to execute python manage.py runserver I am getting error as follows - File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax to solve this I removed from exc and run again then it throws error as follows - Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 13, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? May be the similar questions already available on stackoverflow itself but these solutions are not working in my case hence I am asking wrt my problem. Please suggest me how to resolve it? Thanks in advance. -
Django OperationalError: no such column: blog_post.slug
I'm a newbie of Django development. I have to create a blog, when I want to show the blog list, I got an error below. I guess that 'slug' column is not be created before I have the first migrations. And I re-migrate again, but it still has the same problem. Here are my code scripts: Thanks for your help! This is the error: -
How to send HTML in email using Django?
i am New in Django. i want to send html via Email using django. i am using following Code send_mail( 'Email Title', 'My Message', 'webmaster@localhost', [to mail], fail_silently=False, ) This Code is Sending simple strings,not sending HTML. for example if i pass <h1>test</h1> in my message body then it will return same. i want to apply <h1> tag in 'test'. How to do that ? -
Python equivalent of uidai ekyc authentication java implementaion
I'm implementing the Uidai Aadhaar verification process in python Django. I have the java code for the same. I tried to implement some functions. But I don't know how to implement the encryption and some other kinds of stuff. How to implement the exact code in python? ''' public class AuthAUADataCreator { public static final int AES_KEY_SIZE = 128; public static final int GCM_NONCE_LENGTH = 12; public static final int GCM_TAG_LENGTH = 16; private static final String JCE_PROVIDER = "BC"; private static final String ASYMMETRIC_ALGO = "RSA/ECB/PKCS1Padding"; private static final String ALGO = "AES/GCM/NoPadding"; private static final int SYMMETRIC_KEY_SIZE = 256; public static final int AUTH_TAG_BIT_LENGTH = 128; private static final String CERTIFICATE_TYPE = "X.509"; private PublicKey publicKey; private Date certExpiryDate; private String certPath; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS"); String otptxn = this.dateFormat.format(new Date()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String time = this.sdf.format(new Date()); File certificatePath = null; File DualcertificatePath = null; static { Security.addProvider(new BouncyCastleProvider()); } public AuthAUADataCreator() { } public AuthAUADataCreator(InputStream publicKeyFileName) { InputStream fileInputStream = null; try { CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE, JCE_PROVIDER); fileInputStream = publicKeyFileName; X509Certificate cert = (X509Certificate) certFactory.generateCertificate(fileInputStream); this.publicKey = cert.getPublicKey(); this.certExpiryDate = cert.getNotAfter(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not …