Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotate based on related field, with filters
class IncomeStream(models.Model): product = models.ForeignKey(Product, related_name="income_streams") from_date = models.DateTimeField(blank=True, null=True) to_date = models.DateTimeField(blank=True, null=True) value = MoneyField(max_digits=14, decimal_places=2, default_currency='USD') class Product(models.Model): ... class Sale(models.Model): product = models.ForeignKey(Product, related_name="sales") created_at = models.DateTimeField(auto_now_add=True) ... With the above model, suppose I want to add a value to some Sales using .annotate. This value is called cpa (cost per action): cpa is the value of the IncomeStream whose from_date and to_date include the Sale created_at in their range. Furthermore, from_date and to_date are both nullable, in which case we assume they mean infinity. For example: <IncomeStream: from 2021-10-10 to NULL, value 10$, product TEST> <IncomeStream: from NULL to 2021-10-09, value 5$, product TEST> <Sale: product TEST, created_at 2019-01-01, [cpa should be 5$]> <Sale: product TEST, created_at 2021-11-01, [cpa should be 10$]> My question is: is it possible to write all these conditions using only the Django ORM and annotate? If yes, how? I know F objects can traverse relationships like this: Sale.objects.annotate(cpa=F('offer__income_streams__value')) But then where exactly can I write all the logic to determine which specific income_stream it should pick the value from? -
Why my codes showing during during runtime? (Django)
I just wanna ask what's wrong with my codes? <div class="form-row"> <div class="form-group col-md-6"> <label><b>Lot Area: </b></label> <input type="text" id='lot_area' class="form-control" oninput="amount_calculate()" value="{{form.c_lot_area}}"> </div> </div> I am using Django. When I run it, the codes also display. It always shows the double quotes and the right arrow during runtime. -
Celery AttributeError : 'download_all' object has no attribute 'location'
I want to create a progress bar for my project. I have a class and this class has some functions. Especially, one of them takes a long time (def download_all) and this is my main reason for wanting to create a progress bar. I successfully set up celery, celery-progress, etc. and they work all fine. My problem is this: I want to integrate the progress bar to download_all function. I It gives an error: AttributeError: 'download_all' object has no attribute 'location' I am sure that this error is because of the celery task because when I run it without celery, it works. This is my code. How can I do it? views.py def setup_wizard(request): ... task = (functions.myClass(n_username, n_password, n_url, n_port, db_password, username=request.user.username)).delay(5) task_id = task.download_all(request.user.username, setup.nessus_username, setup.nessus_password, setup.nessus_url, setup.nessus_port, setup.db_password, username=request.user.username).task_id // in task_id download_all parameters, I had to user request.user.username instead of "self" parameter. ... context = { ... 'task_id':task_id } functions.py @shared_task(bind=True) class myClass(): def __init__(self, nessus_user, nessus_password, nessus_url, nessus_port, db_password, username): self.location = zt_dosya_url self.static_fields = {} self.download_all(n_user, n_password, n_url, n_port, db_password) self.send(username) ... def download_all(self, n_user, n_password, n_url, n_port, db_password): if not os.path.exists(self.location): os.mkdir(self.location) else: shutil.rmtree(self.location, ignore_errors=True) os.mkdir(self.location) ... for s in scans: i = … -
AttributeError: 'str' object has no attribute '__name__' creating OTREE investment game with Pycharm,
I am working on a game where investors have a specific fund with multiple rounds of investments. In case they invest in any round, their available fund for the subsequent rounds should be adjusted for that. If the initial budget was $1000 and the participant invest $50 in round 2, then for third he should have $950. Please have a look and help me class Constants(BaseConstants): name_in_url = 'investment' players_per_group = None num_rounds = 1 budget = cu(1000) class Player(BasePlayer): investment = models.CurrencyField(label="How much will you invest?") def set_funds(self): players = self.get_players() investment = [p.investment for p in players] self.total_investment = sum(investment) for player in players: player.funds = Constants.budget - player.total_investment def investment_error_message(player, value): print('value is', value) if value > player.funds: return 'Cannot offer more than your remaining fund' class investment(Page): form_model = 'player' form_fields = ['investment'] class ResultsWaitPage(WaitPage): pass class Results(Page): pass page_sequence = ['investment'] -
width not correct in when using d-flex in Bootstrap 5.0
I have a base.html file that I am using as a template in my Django project. I used d-flex to create top nav and sidebar but I am struggling to set up width and height on each website to 100%. When running it as a static page everything is ok but when I try to run it in Django then the result is like this: As you can see the width and height are not 100% but they are adjusting somehow to the content. How can I fix this? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Starlab - {% block title %}{% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.7/css/all.css"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"> </script> </head> <body> <div class="d-flex w-100" id="wrapper"> <!-- Sidebar--> <div class="border-end bg-white text-center" id="sidebar-wrapper" style="width: 275px;"> <div class="sidebar-heading border-bottom bg-light text-center" style="height: 55px;"></div> <div class="list-group list-group-flush"> <a class="list-group-item list-group-item-action list-group-item-light p-3" href="{% url 'homepage' %}">Home pge</a> <a class="list-group-item list-group-item-action list-group-item-light p-3" href="/products">Products</a> <a class="list-group-item list-group-item-action list-group-item-light p-3" href="/articles">Articles</a> </div> <div class="list-group-item p-3">Categories <ul> {% for tag in tags %} <div class="text-center"><a href={% url 'tagged' tag.slug %}>{{tag.name}}</a></div> {% empty %} … -
Django HyperlinkedModelSerializer on a table that has a field marked as pk + fk
I have this table which has a field marked as a primary key, when it also is a foreign key. Isn't ideal, but need to deal with this at the moment. class Profile(models.Model): class Meta: verbose_name_plural = "Profiles" member = models.OneToOneField( Member, on_delete=models.CASCADE, primary_key=True, ) ... Now I have a django-rest-framework serializer for the Member and Profile models, that looks like this, class MemberSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Member fields = ('id', 'role_id', 'user_id') class MemberProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ['member_id','bio','address','mobile'] The question I have is that, when I have the 'member_id' extracted from MemberProfileSerializer, it lists down the id correctly (this is the id that is pk for Profile, and is also fk to the Member table) But if I need to extract more information from the Member model, and to do that, if I add a reference to the MemberSerializer, I get back an empty object in the results! class MemberProfileSerializer(serializers.HyperlinkedModelSerializer): member_id = MemberSerializer() class Meta: model = Profile fields = ['member_id','bio','address','mobile'] Any suggestions on why this could be happening! -
get all children of category id in a list drf
I have a model like this class Catgeory(models.Model): name = models.CharField() parent = models.ForeignKey('self', related_name='children') Now I need to write a piece of code to return a list of all children ids for a specified category for example, I have a category like that General (id=1) --> Electronics (id=2) --> Mobile phones (id=3) --> Apple (id=4) If I want to get children of Electronics it should return [3, 4] But I have been trying to find a solution for 3 hours, unfortunately, I could not solve it yet. I can get all parents by one child but cannot get children by a parent. If anybody has a solution or any idea, can you help? Any help would be appreciated! Thank you very much! -
TypeError: argument should be a bytes-like object or ASCII string, not 'dict'
I am getting this error when I am decrypting the encrypted message.I fetched the the encrypted message from the db in django views as pw = donator.objects.filter(emai=email).values('passw')and passed the pw object in the decrypt_message() function. The decrypt_messag() function is : def decrypt_message(encrypted_message,key): """ Decrypts an encrypted message """ f = Fernet(key) decrypted_message = f.decrypt(encrypted_message) return decrypted_message.decode() The error message is: File "C:\Users\Neelesh Singh\workspace\BookHouse\donatorapp\views.py", line 129, in decrypt_message f = Fernet(key) File "C:\Users\Neelesh Singh\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 37, in __init__ key = base64.urlsafe_b64decode(key) File "C:\Users\Neelesh Singh\AppData\Local\Programs\Python\Python39\lib\base64.py", line 131, in urlsafe_b64decode s = _bytes_from_decode_data(s) File "C:\Users\Neelesh Singh\AppData\Local\Programs\Python\Python39\lib\base64.py", line 45, in _bytes_from_decode_data raise TypeError("argument should be a bytes-like object or ASCII " TypeError: argument should be a bytes-like object or ASCII string, not 'dict' -
How to overwrite clean and clean_fieldname for ModelFormMixin
I found this How to properly overwrite clean() method and this Can `clean` and `clean_fieldname` methods be used together in Django ModelForm? but it seems to work differently if one is using the generic class mixins ModelFormMixin. My class is also derived from ProcessFormView. Is def form_valid(self, form): the only point where I can overwrite the form handling process? -
Why my codes showing during during runtime? (Django)
I just wanna ask what's wrong with my codes? I am using Django. When I run it, the codes also display. Here's the output -
Django admin Access All queryset in change_list
I am using Django admin to display a list of orders . The goal is to access all objects without pagination. in the change_list_result.html i have found a result variable {% load i18n static jazzmin %} {% if result_hidden_fields %} <div class="hiddenfields"> {% for item in result_hidden_fields %}{{ item }}{% endfor %} </div> {% endif %} {% if results %} <div class="card"> <div class="card-body table-responsive p-0"> <table id="result_list" class="table table-striped"> <thead> <tr> {% for header in result_headers %} <th class="{% header_class header forloop %}" tabindex="0" rowspan="1" colspan="1"> <div class="text"> {% if header.sortable %} <a href="{{ header.url_primary }}">{{ header.text|capfirst }}</a> {% else %} <span>{{ header.text|capfirst }}</span> {% endif %} {% if header.sorted %} <a href="{{ header.url_remove }}"> <div style="margin-top: .2em;" class="fa fa-times float-right"> </div> </a> {% if header.ascending %} <i style="margin-top: .2em;" class="fa fa-sort-alpha-down"> </i> {% else %} <i style="margin-top: .2em;" class="fa fa-sort-alpha-up"> </i> {% endif %} {% endif %} </div> </th> {% endfor %} </tr> </thead> <tbody> {% for result in results %} <tr role="row" class="{% cycle 'even' 'odd' %}"> {% for item in result %}{{ item }}{% endfor %} </tr> {% endfor %} </tbody> </table> </div> </div> {% endif %} the problem is that variable contains only the pagination … -
Common Remote Database connect to Django
I'm new to Django, I would like to start a project with my friend where we would need to have a database. We are thinking how to do it. Is there any remote database where we can save and share data at once. Thank you -
setting Django in VS code
I started learning Django framework and I supposed to use vs code as editor, I created a folder and an environment in command prompt, I followed a tutorial, after creating the project and the work environment the command was "workon test" (where "test" is my environment) and it works fine in command prompt as it shows " ((test) ) C:\Users\DELL\projects\telusko> ". The same is followed in VS code terminal but it not directing to my environment(test). Help me to get out of this trouble. -
How add claims to SAML IDP metadata
I built the SSO integration project, I will be an IDP identity provider and our third party will be an SP services provider. I used this code https://github.com/OTA-Insight/djangosaml2idp to prepare my Idp. everything is with it very well and already I tested it by https://sptest.iamshowcase.com/. But I have a question how I can add claims to this generated metadata so that helps our SP use it? here is the generated metadata file: <ns0:EntityDescriptor entityID="http://localhost:9000/idp/metadata/" validUntil="2022-11-06T12:46:57Z"> <ns0:Extensions> <ns1:DigestMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#md5"/> <ns1:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#ripemd160"/> <ns1:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <ns1:DigestMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#sha224"/> <ns1:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ns1:DigestMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#sha384"/> <ns1:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha512"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2009/xmldsig11#dsa-sha256"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-md5"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha224"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"/> <ns1:SigningMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"/> </ns0:Extensions> <ns0:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol" WantAuthnRequestsSigned="false"> <ns0:KeyDescriptor use="signing"> <ns2:KeyInfo> <ns2:X509Data> <ns2:X509Certificate> MIID/TCCAuWgAwIBAgIUd3caFbHlYy3TQxRxYS4e/8ya0bYwDQYJKoZIhvcNAQEL BQAwgY0xCzAJBgNVBAYTAlNBMQ8wDQYDVQQIDAZSaXlhZGgxDzANBgNVBAcMBlJp eWFkaDELMAkGA1UECgwCSVQxCzAJBgNVBAsMAklUMRcwFQYDVQQDDA5sb2NhbGhv c3Q6OTAwMDEpMCcGCSqGSIb3DQEJARYabS5hbG51ZmFpc2kydGFrYW1vbC5jb20u c2EwHhcNMjExMDE3MDkzMTQwWhcNMzExMDE3MDkzMTQwWjCBjTELMAkGA1UEBhMC U0ExDzANBgNVBAgMBlJpeWFkaDEPMA0GA1UEBwwGUml5YWRoMQswCQYDVQQKDAJJ VDELMAkGA1UECwwCSVQxFzAVBgNVBAMMDmxvY2FsaG9zdDo5MDAwMSkwJwYJKoZI hvcNAQkBFhptLmFsbnVmYWlzaTJ0YWthbW9sLmNvbS5zYTCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBALLSHO71t9ewIWjIIQcrGlzMlDTwQ0DwQEUkYiw9 wgqRRaBrvEthraYkCB8OPho9fUORB46UxFQeYMq7r0Njdc8Zv/MRmu1uQFWwk0DT Qr39coL5528OhktEotTO0LHbSoxpATiAGfmTA/UeQ+eSYPUKKdo4Dd/UEmzz19Dq pqK2I38v6hnb41XyR71zE+W/IalvJR3p2JODAmsiN3nIP2kbdviKZiy0bXkrzODe dZmc4v4p86v3X9SH/zJ2upcA3s9dGqcBok15shzVAqJnd3uNZzRwn8ZxW36Vv6xy LBxJv/viLFH9xX8beR4h8KWrGK2rgM7KuJHo1tGrEzJmA+0CAwEAAaNTMFEwHQYD VR0OBBYEFA6pioh/oBZg8ANNThtWfGxx2mWxMB8GA1UdIwQYMBaAFA6pioh/oBZg 8ANNThtWfGxx2mWxMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEB AHt4m2hdFZp/ZxxcAsUD1Acweiibq+NqmSU6LJURK7Qw/CJUQFL845RXkzbbVnhq /HEvesd0qnmLgd8qH7voHCn6tFTWLk6kw6Axj4cv0qW4PKoz37PVKgG5mNiijgXX 3VbulniOqkuXqoijNb9pZvV63TFXtzz+BkM4uivs9cu8ndKU+sqiUgZGYe+xSIcl j8qP9DeU4D5XaSYKUSOIXbLJebklxbnpnGunM6O0ZWdVwfbV6U4FwTqnZtQWHT0m A5q+hK6L9CrBBkMP+12ACbBgENF6JrsVGyBN36FdAbA/uwTsynMdwn4zMC1xefj0 6/w0SoJP54KNrj9dG7AwXq4= </ns2:X509Certificate> </ns2:X509Data> </ns2:KeyInfo> </ns0:KeyDescriptor> <ns0:KeyDescriptor use="encryption"> <ns2:KeyInfo> <ns2:X509Data> <ns2:X509Certificate> MIID/TCCAuWgAwIBAgIUd3caFbHlYy3TQxRxYS4e/8ya0bYwDQYJKoZIhvcNAQEL BQAwgY0xCzAJBgNVBAYTAlNBMQ8wDQYDVQQIDAZSaXlhZGgxDzANBgNVBAcMBlJp eWFkaDELMAkGA1UECgwCSVQxCzAJBgNVBAsMAklUMRcwFQYDVQQDDA5sb2NhbGhv c3Q6OTAwMDEpMCcGCSqGSIb3DQEJARYabS5hbG51ZmFpc2kydGFrYW1vbC5jb20u c2EwHhcNMjExMDE3MDkzMTQwWhcNMzExMDE3MDkzMTQwWjCBjTELMAkGA1UEBhMC U0ExDzANBgNVBAgMBlJpeWFkaDEPMA0GA1UEBwwGUml5YWRoMQswCQYDVQQKDAJJ VDELMAkGA1UECwwCSVQxFzAVBgNVBAMMDmxvY2FsaG9zdDo5MDAwMSkwJwYJKoZI hvcNAQkBFhptLmFsbnVmYWlzaTJ0YWthbW9sLmNvbS5zYTCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBALLSHO71t9ewIWjIIQcrGlzMlDTwQ0DwQEUkYiw9 wgqRRaBrvEthraYkCB8OPho9fUORB46UxFQeYMq7r0Njdc8Zv/MRmu1uQFWwk0DT Qr39coL5528OhktEotTO0LHbSoxpATiAGfmTA/UeQ+eSYPUKKdo4Dd/UEmzz19Dq pqK2I38v6hnb41XyR71zE+W/IalvJR3p2JODAmsiN3nIP2kbdviKZiy0bXkrzODe dZmc4v4p86v3X9SH/zJ2upcA3s9dGqcBok15shzVAqJnd3uNZzRwn8ZxW36Vv6xy LBxJv/viLFH9xX8beR4h8KWrGK2rgM7KuJHo1tGrEzJmA+0CAwEAAaNTMFEwHQYD VR0OBBYEFA6pioh/oBZg8ANNThtWfGxx2mWxMB8GA1UdIwQYMBaAFA6pioh/oBZg 8ANNThtWfGxx2mWxMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEB AHt4m2hdFZp/ZxxcAsUD1Acweiibq+NqmSU6LJURK7Qw/CJUQFL845RXkzbbVnhq /HEvesd0qnmLgd8qH7voHCn6tFTWLk6kw6Axj4cv0qW4PKoz37PVKgG5mNiijgXX 3VbulniOqkuXqoijNb9pZvV63TFXtzz+BkM4uivs9cu8ndKU+sqiUgZGYe+xSIcl j8qP9DeU4D5XaSYKUSOIXbLJebklxbnpnGunM6O0ZWdVwfbV6U4FwTqnZtQWHT0m A5q+hK6L9CrBBkMP+12ACbBgENF6JrsVGyBN36FdAbA/uwTsynMdwn4zMC1xefj0 6/w0SoJP54KNrj9dG7AwXq4= </ns2:X509Certificate> </ns2:X509Data> </ns2:KeyInfo> </ns0:KeyDescriptor> <ns0:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="http://localhost:9000/idp/slo/post/"/> <ns0:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="http://localhost:9000/idp/slo/redirect/"/> <ns0:NameIDFormat> urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress </ns0:NameIDFormat> <ns0:NameIDFormat> urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified </ns0:NameIDFormat> <ns0:NameIDFormat> urn:oasis:names:tc:SAML:2.0:nameid-format:transient </ns0:NameIDFormat> <ns0:SingleSignOnService … -
Could not parse the remainder: ',' from ''twitter:source_delete','
I want to append td to my table using ajax but I have a little problem, how to add the source.twitter_id in url?? the error that I got is "Could not parse the remainder: ',' from ''twitter:source_delete',' " I tried also {% url 'twitter:source_delete', source.twitter_id %} it also error. javascript function appendToUsrTable(source) { console.log(source.twitter_id) $("#sourceTable > tbody:last-child").append(` <tr class="record" id="source-${source.twitter_id}"> <td>{{forloop.counter}}</td> <td>${source.source_acct}</td> <td><p data-placement="top" data-toggle="tooltip" title="Delete"><a href="{% url 'twitter:source_delete' ${source.twitter_id} %}" class="source_delete btn btn- danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete"><span class="las la-trash-alt del_s"></span></a></p></td> </tr> `); } views.py class CreateCrudUser(View): def get(self, request): name_source = request.GET.get('source_acct', None) print(name_source) obj = Source.objects.create( source_acct = name_source ) source = {'twitter_id':obj.twitter_id,'source_acct':obj.source_acct} data = { 'source': source } return JsonResponse(data) -
Why are pictures not displayed in django?
Why are the pictures that are loaded through the admin panel in Django not displayed? this is code of views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Goods.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:1] def description(self): return self.description_text def price(self): return self.price_text def image(self): return self.image_sale this is code of models.py class Goods(models.Model): description_text = models.CharField(max_length=200) price_text = models.CharField(max_length=200) image_sale = models.ImageField(blank=True, upload_to='media/') pub_date = models.DateTimeField('date published', null=True) def __str__(self): return self.image_sale this is code of settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' And this construction this is code of app urls.py from django.urls import path from . import views app_name = 'Homepage' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] -
absolute path? `upload_to` of models.FileFIeld
I have FileField in models.py class DocFile(models.Model): document = models.FileField(upload_to='_mat/') It works well for local(mac),and the file is stored under /Users/whitebear/myproj/_mat/ However I do the same thing on server (Ubuntu 20, using ENGINX-unit) It shows the error PermissionError: [Errno 13] Permission denied: '/_mat' But, /var/www/html/myproj/_mat/ permission is 777 So I guess, somehow it trys to make /_mat as absolute path ..??? If I set upload_to like this , document = models.FileField(upload_to='/var/www/html/myproj_mat/') It says to use 'relative path' These are error stack trace. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/var/www/html/aicomposer/current/defapp/views.py", line 350, in post entry.save() File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/anaconda3/envs/aiwave/lib/python3.8/site-packages/django/db/models/query.py", line 1270, … -
Display model items grouped by the category they belong to (kanbam board style) using Django and Vue.js
Hi I hope you are all well. Am working on a kanban board app with Django as backend and Vue.js. as frontend. I have 2 models: Status and Items. Items contains status as a foreignkey from Status model. api/models.py from django.db import models from django.contrib.auth.models import User class Status(models.Model): created_by = models.ForeignKey(User, related_name='status', on_delete=models.CASCADE, null=True) status = models.CharField(max_length=50, null=True) def __str__(self): return self.status class Items(models.Model): PRIORITY_CHOICES = ( ("High", "danger"), ("Medium", "info"), ("Low", "primary"), ) notes = models.CharField(max_length=255, null=True) status = models.ForeignKey(Status, null=True, blank=True, on_delete=models.CASCADE) priority = models.CharField(max_length=15, null=True,choices=PRIORITY_CHOICES, default="2") start_date = models.DateField(null=True) end_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='task', on_delete=models.CASCADE, null=True) def __str__(self): return self.notes And am using class based views in my api/views.py views.py screenshot api/serializers.py from rest_framework import serializers from .models import Items, Status class ItemsSerializer(serializers.ModelSerializer): class Meta: model = Items read_only_fields = ( 'created_by', 'created_at', ) fields = ('id','notes','status','priority','start_date','end_date') class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status read_only_fields = ( 'created_by', ) fields = ('status','id','pk') The problem - I want to display items created in my app in a column whereby the column name is the Status.status and under every column I want to display all Items.notes(items represents tasks that user creates) that contain … -
How to use celery progress bar in a function in the class?
I want to create a progress bar for my project. I have a class and this class has some functions. Especially, one of them takes a long time (def download_all) and this is my main reason for wanting to create a progress bar. I successfully set up celery, celery-progress, etc. and they work all fine. My problem is this: I want to integrate the progress bar to download_all function. I try a lot of things but it gives errors. This is my code. How can I do it? views.py def setup_wizard(request): ... task = (functions.myClass(n_username, n_password, n_url, n_port, db_password, username=request.user.username)) task_id = task.task_id ... context = { ... 'task_id':task_id } functions.py @shared_task(bind=True) class myClass(): def __init__(self, nessus_user, nessus_password, nessus_url, nessus_port, db_password, username): self.location = zt_dosya_url self.static_fields = {} self.download_all(n_user, n_password, n_url, n_port, db_password) self.send(username) ... def download_all(self, n_user, n_password, n_url, n_port, db_password): ... for s in scans: i = 0 scanner.scan_name = s['name'] ... // I have to get the values of progress bar from here //for example // progress_recorder.set_progress(i + 1, len(scans), f'On iteration {i}') ... i += 1 -
Django multiple user types migration error
I'm trying to create a multiple user types using Django Abstract User but whenever I try to migrate the changes it gives me an error. As I'm still new to Django, I don't understand that it means Here is my models code: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_customer = models.BooleanField(default = False) is_seller = models.BooleanField(default = False) name = models.CharField(max_length = 60) And whenever I try to migrate this model I get this error: ERRORS: Accounts.CustomUser.groups: (fields.E304) Reverse accessor for 'Accounts.CustomUser.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'Accounts.CustomUser.groups' or 'auth.User.groups'. Accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'Accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'Accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'Accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'Accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'Accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'Accounts.CustomUser.user_permissions'. -
How to manage a form with many-to-many intermediate table fields and class-based views?
I would like to be able to edit an article directly via the web page where it is displayed. For this I use the UpdateView. My "News" model has a many to many relationship with my "User" model. The intermediate model is called "NewsUpdate" and it has 2 additional fields (update_date and update_reason). I can display and run the edit form of my "News" model, but I can't add the "update_reason" field and validate it. Is it possible to do this with the generic views? Thank you in advance! models : class News(models.Model): ... image = models.ImageField(upload_to='contents', null=True, blank=True) uuid = models.UUIDField(default=uuid.uuid4, unique=True, verbose_name='UUID') author = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Auteur', related_name='create_news') news_update_user = models.ManyToManyField(AUTH_USER_MODEL, through='contents.NewsUpdate', related_name='news_update_user') news_delete_user = models.ManyToManyField(AUTH_USER_MODEL, through='contents.NewsDelete', related_name='news_delete_user') class NewsUpdate(models.Model): news = models.ForeignKey(News, on_delete=models.CASCADE, related_name='updated_news') updater = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Auteur', related_name='news_updater') update_date = models.DateTimeField(auto_now=True, null=True, verbose_name='Modification le') update_reason = models.CharField(max_length=250, verbose_name='Raison de la modification') class Meta: unique_together = ('news', 'updater') class User(AbstractUser): first_name = models.CharField( max_length=30, blank=True, null=True, verbose_name='Prénom' ) last_name = models.CharField( max_length=30, blank=True, null=True, verbose_name='Nom' ) ... News update view : class NewsUpdateView(SuccessMessageMixin, UpdateView): model = News template_name = 'contents/news_update.html' success_message = 'La news a bien été mise à jour !' fields = ['category', 'title', 'content', … -
fetch dosent bring any data
when i use fetch to bring the list of notes and consol.log it nothing shows up. The url is not wrong i have carefully checked it. Here is the code: import React, { useState, useEffect } from 'react' const NotesListPage = () => { let [notes, setNotes] = useState([]) useEffect(() => { }, []) let getNotes = async () => { let response = await fetch('http://127.0.0.1:8000/api/notes/') let data = await response.json() console.log(data) setNotes(data) } return ( <div> </div> ) } export default NotesListPage here is the api part: @api_view(['GET']) def getNotes(request): notes = Note.objects.all() serializer = NoteSerializer(notes, many=True) return Response(serializer.data) -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when i try to import models in consumers.py on heroku
i run my django project on local which import models on consumers.py that work but when i deploy on heroku error occurred 2021-11-06T10:22:14.039525+00:00 app[web.1]: Traceback (most recent call last): 2021-11-06T10:22:14.039542+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2021-11-06T10:22:14.039607+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2021-11-06T10:22:14.039607+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 170, in entrypoint 2021-11-06T10:22:14.039690+00:00 app[web.1]: cls().run(sys.argv[1:]) 2021-11-06T10:22:14.039697+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 232, in run 2021-11-06T10:22:14.039772+00:00 app[web.1]: application = import_by_path(args.application) 2021-11-06T10:22:14.039778+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/utils.py", line 12, in import_by_path 2021-11-06T10:22:14.039824+00:00 app[web.1]: target = importlib.import_module(module_path) 2021-11-06T10:22:14.039830+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-11-06T10:22:14.039892+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-11-06T10:22:14.039898+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-11-06T10:22:14.039963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-11-06T10:22:14.040002+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-11-06T10:22:14.040040+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-11-06T10:22:14.040078+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-11-06T10:22:14.040124+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-11-06T10:22:14.040163+00:00 app[web.1]: File "/app/./spotgame/asgi.py", line 16, in <module> 2021-11-06T10:22:14.040212+00:00 app[web.1]: import spotifymusicgame.routing 2021-11-06T10:22:14.040218+00:00 app[web.1]: File "/app/./spotifymusicgame/routing.py", line 3, in <module> 2021-11-06T10:22:14.040261+00:00 app[web.1]: from . import consumers 2021-11-06T10:22:14.040268+00:00 app[web.1]: File "/app/./spotifymusicgame/consumers.py", line 59, in <module> 2021-11-06T10:22:14.040324+00:00 app[web.1]: from .models import roomInfo 2021-11-06T10:22:14.040330+00:00 app[web.1]: File "/app/./spotifymusicgame/models.py", line 10, in <module> 2021-11-06T10:22:14.040373+00:00 app[web.1]: class songModel(models.Model): 2021-11-06T10:22:14.040379+00:00 app[web.1]: File … -
How to disable django forms radio button depending on anotehr radio button value
I have a Django form with two sets of radio buttons. I would like to block two choices in the second set depending on the selected button in the first set. How can I do that? Do I have to write a function for it in views? forms.py DOWNLOAD_CHOICES = [("all", "All values"), ("all_divide", "All values separated per IfcType"), ("unique", "Unique values"), ("unique_divide", "Unique values separated per IfcType")] FORMAT_CHOICES = [("xlsx", "Excel (.xlsx)"), ("csv", "comma-separated values (.csv)")] class DownloadForm(forms.Form): file_format = forms.ChoiceField(choices=FORMAT_CHOICES, widget=forms.RadioSelect()) file_download = forms.ChoiceField(choices=DOWNLOAD_CHOICES, widget=forms.RadioSelect()) model_form_download.html <form action="" name="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Download"> </form> I think that my views.py is not relevant to this question, so I am not posting it now. It is too long anyways... -
PYTHON DJANGO HOSTING IN GODADDY - FACING FOLLOWING ERROR "The requested URL was not found on this server."
I'm trying to host a python django test site in godaddy cpanel hosting. My first index page has only heading and "next page" link. Whereas the next page has few test text. On choosing the next page i get an error as Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. I am not sure why my next page is not being accessible.